feat(i18n): @xenia/i18n translations, language resolution and venue-time formatting

Platform-v2 step 2.4 (APPS_PLATFORM D-11, D-12, §7.2, §8):
- i18next 26.7.2 + react-i18next 17.1.13 (exact); en/el locale files
  (common, dev); createI18n, I18nProvider, useLanguage, setUserLanguage
  (screen first, then PATCH /api/auth/me through an app-provided save)
- resolveLanguage: user -> device -> venue -> en
- useFormat(): dates/times always in the venue zone from bootstrap (24 h,
  DST-safe, business dates never shifted), relative times, money and
  numbers per language; parseNumber accepts a comma or a dot
- scripts/check-i18n.mjs guard: keys missing in en, placeholder mismatches,
  dates formatted without the venue zone in new code (fails); missing el (warns)
- @xenia/ui components read their texts from UiLabelsProvider; useUiLabels()
  supplies the translated set
- dev-only /i18n-sample in the manager; ui.mjs e2e checks it with the browser
  in New York; unit tests in run-all; lockfile keeps both apps' versions
- new pack rule CS-17

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 19:51:11 +02:00
co-authored by Claude Opus 5.5
parent 3580f2815c
commit dbb8d5f0f4
38 changed files with 1206 additions and 48 deletions
+5 -1
View File
@@ -50,6 +50,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `docker-compose.yml` / `docker-compose.dev.yml` | Prod (pull images) / dev override (build + expose ports) |
| `package.json`, `package-lock.json`, `packages/` | **npm workspace** for the frontends (D-15): `waiter_pwa`, `manager_dashboard` and the shared `packages/{ui,i18n,api,access}` (imported from source, no build step). One lockfile at this root; the apps have none of their own. |
| `packages/ui/` | Shared design tokens, Tailwind preset and base components (CS-16). Visual check: `npm run dev:manager` → `/ui-gallery` |
| `packages/i18n/` | Translations (`locales/<lang>/<ns>.json`), language resolution, venue-time / money / number formatting, the comma-or-dot number parser, and the guard `scripts/check-i18n.mjs` (CS-17). Sample: `/i18n-sample` (dev) |
| `.dockerignore` | The frontend images build with **`client-services/` as context** (`-f waiter_pwa/Dockerfile .`), so this file decides what Docker sees. The backend still builds from `local_backend/`. |
---
@@ -145,7 +146,7 @@ The native plugins (`@capacitor/*`, `@capgo/*`) are pinned to **exact** versions
## Testing
Automated tests cover the native-app/LAN work and licensing. See **[tests/e2e/README.md](../tests/e2e/README.md)**.
- **Unit (seconds):** `python -m pytest tests -q` in `local_backend/`, `npm test` in `waiter_pwa/`, and `npm test -w @xenia/ui` at the workspace root.
- **Unit (seconds):** `python -m pytest tests -q` in `local_backend/`, `npm test` in `waiter_pwa/`, and `npm test -w @xenia/ui` / `npm test -w @xenia/i18n` at the workspace root.
- **End-to-end:** `node run-all.mjs` in `tests/e2e/`. That covers install.sh, licensing with a real cloud, browser modes, and the Android emulator suites. `--no-android` skips the emulator.
**CS-11. Tests follow the code.** When you change something a test covers (licensing, LAN IP, TLS, pairing, rediscovery, bundles, install.sh, the proxy config), run its suite and update the test in the same commit. Run `node run-all.mjs` before every release.
@@ -164,6 +165,9 @@ Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overri
**CS-16. Shared UI lives in `packages/ui` and never restyles an app** (branch `platform-v2`, D-15, §9).
Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`), components use `.x-*` classes (`src/components.css`); neither file has element selectors, resets or anything that applies outside `.x-*` (the waiter keeps its own `--bg`/`--text`…; the manager's Tailwind classes keep their meaning). Theme comes from `data-theme` (`light`/`dark`/`system`) and `data-venue-theme` on `<html>`. Tailwind apps use `@xenia/ui/tailwind-preset` (adds `bg-surface`, `text-ink-2`, `rounded-control`… only). A colour change must pass `npm test -w @xenia/ui` (WCAG AA for every pair the components use, every venue theme, light and dark). Components take their visible text as props with English defaults until `@xenia/i18n` (2.4). New components get a section in `packages/ui/gallery/Gallery.jsx` (dev-only `/ui-gallery` in the manager) and checks in `tests/e2e/ui.mjs`.
**CS-17. Frontend text is a key; dates are venue time** (branch `platform-v2`, D-11, D-12, §7.2, §8).
New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root.
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).
+1
View File
@@ -10,6 +10,7 @@
},
"dependencies": {
"@tanstack/react-query": "^5.62.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0",
"axios": "^1.7.9",
"lucide-react": "^1.14.0",
+3 -1
View File
@@ -54,8 +54,9 @@ import SettingsPage from './pages/Settings/SettingsPage'
import NotesPage from './pages/NotesPage'
import PermissionGuard from './components/PermissionGuard'
// @xenia/ui visual check page, dev builds only (left out of production bundles)
// Visual check pages for the shared packages, dev builds only (left out of production bundles)
const UiGallery = import.meta.env.DEV ? lazy(() => import('@xenia/ui/gallery')) : null
const I18nSample = import.meta.env.DEV ? lazy(() => import('@xenia/i18n/sample')) : null
function Spinner() {
return (
@@ -113,6 +114,7 @@ export default function App() {
<Routes>
<Route path="/setup" element={<SetupWizard />} />
{UiGallery && <Route path="/ui-gallery" element={<Suspense fallback={null}><UiGallery /></Suspense>} />}
{I18nSample && <Route path="/i18n-sample" element={<Suspense fallback={null}><I18nSample /></Suspense>} />}
<Route path="/login" element={<SetupGuard><LoginPage /></SetupGuard>} />
<Route path="/kds" element={<RequireAuth><KdsPage /></RequireAuth>} />
+91 -10
View File
@@ -16,6 +16,7 @@
"version": "0.0.0",
"dependencies": {
"@tanstack/react-query": "^5.62.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0",
"axios": "^1.7.9",
"lucide-react": "^1.14.0",
@@ -1777,15 +1778,6 @@
"browserslist": ">= 4.21.0"
}
},
"manager_dashboard/node_modules/use-sync-external-store": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"manager_dashboard/node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
@@ -1844,6 +1836,15 @@
}
}
},
"node_modules/@babel/runtime": {
"version": "7.29.14",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.14.tgz",
"integrity": "sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@emnapi/core": {
"version": "1.9.2",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.2.tgz",
@@ -2304,6 +2305,43 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/html-parse-stringify": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-4.0.1.tgz",
"integrity": "sha512-0zHsZJrK7S3K2aucXWL6ycoYJ/iNtIcFHC/nYQgFklPtrv5LpJctIiSCroWZWeuoXvuyFdzp6KzjJQ+OT5MfFw==",
"license": "MIT",
"funding": {
"url": "https://locize.com"
}
},
"node_modules/i18next": {
"version": "26.7.2",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.7.2.tgz",
"integrity": "sha512-RsOY3BeaCDdkk52NeJSFAXELQ2rQXBO/tOub6L8ue2ICPfR/FRDWDOfEDg4xMPd1SqO5goVYQ6i72qWEUB/PPw==",
"funding": [
{
"type": "individual",
"url": "https://www.locize.com/i18next"
},
{
"type": "individual",
"url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
},
{
"type": "individual",
"url": "https://www.locize.com"
}
],
"license": "MIT",
"peerDependencies": {
"typescript": "^5 || ^6 || ^7"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
@@ -2656,6 +2694,33 @@
"react": "^19.2.5"
}
},
"node_modules/react-i18next": {
"version": "17.1.13",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.1.13.tgz",
"integrity": "sha512-ZxhOSlyKSKPtbUNPLwYMmE3w3bhoc0jaZJZ6bc7wGOT6cLbrbs//6m01HxCLtFdSjHvFpwFwoPhxxzIlHSs9cw==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.7",
"html-parse-stringify": "^4.0.1",
"use-sync-external-store": "^1.6.0"
},
"peerDependencies": {
"i18next": ">= 26.2.0",
"react": ">= 16.8.0",
"typescript": "^5 || ^6 || ^7"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
},
"react-native": {
"optional": true
},
"typescript": {
"optional": true
}
}
},
"node_modules/react-is": {
"version": "19.2.5",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.5.tgz",
@@ -2785,6 +2850,15 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/use-sync-external-store": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/vite": {
"version": "8.0.9",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.0.9.tgz",
@@ -2877,7 +2951,14 @@
},
"packages/i18n": {
"name": "@xenia/i18n",
"version": "0.0.0"
"version": "0.0.0",
"dependencies": {
"i18next": "26.7.2",
"react-i18next": "17.1.13"
},
"peerDependencies": {
"react": "^19.0.0"
}
},
"packages/ui": {
"name": "@xenia/ui",
+36
View File
@@ -0,0 +1,36 @@
{
"actions": {
"save": "Αποθήκευση",
"cancel": "Ακύρωση",
"delete": "Διαγραφή",
"edit": "Επεξεργασία",
"add": "Προσθήκη",
"close": "Κλείσιμο",
"back": "Πίσω",
"retry": "Δοκιμάστε ξανά",
"confirm": "Επιβεβαίωση",
"done": "Τέλος",
"search": "Αναζήτηση"
},
"status": {
"loading": "Φόρτωση…",
"saving": "Αποθήκευση…",
"saved": "Αποθηκεύτηκε",
"error": "Κάτι πήγε στραβά",
"offline": "Δεν υπάρχει σύνδεση με τον διακομιστή"
},
"language": {
"label": "Γλώσσα",
"changed": "Η γλώσσα άλλαξε",
"notSaved": "Η γλώσσα άλλαξε σε αυτή την οθόνη αλλά δεν αποθηκεύτηκε στο προφίλ σας"
},
"ui": {
"close": "Κλείσιμο",
"dismiss": "Απόρριψη",
"loading": "Φόρτωση",
"moreInfo": "Περισσότερες πληροφορίες",
"notifications": "Ειδοποιήσεις",
"backspace": "Διαγραφή",
"pinProgress": "{{count}} από {{total}} ψηφία"
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"sample": {
"title": "Γλώσσες και μορφές",
"intro": "Αλλάξτε τη γλώσσα: όλα τα κείμενα της σελίδας αλλάζουν αμέσως, χωρίς επαναφόρτωση.",
"greeting": "Γεια σου, {{name}}!",
"items_one": "{{count}} είδος στην παραγγελία",
"items_other": "{{count}} είδη στην παραγγελία",
"venueZone": "Ζώνη ώρας καταστήματος",
"deviceZone": "Ζώνη ώρας αυτής της συσκευής",
"venueNow": "Τώρα στο κατάστημα",
"fixedTime": "Παραγγελία που στάλθηκε στις 10:00 UTC την 1η Ιουλίου 2026",
"businessDate": "Εργάσιμη ημέρα 2026-11-13",
"money": "Ποσό",
"number": "Αριθμός",
"relative": "Πριν από πέντε λεπτά",
"typePrice": "Πληκτρολογήστε τιμή (με κόμμα ή τελεία)",
"parsed": "Διαβάστηκε ως",
"invalid": "δεν είναι αριθμός",
"openDialog": "Άνοιγμα παραθύρου",
"dialogTitle": "Μεταφρασμένα στοιχεία",
"dialogBody": "Το κουμπί κλεισίματος, η ένδειξη φόρτωσης και η βοήθεια (i) χρησιμοποιούν τις μεταφρασμένες ετικέτες."
}
}
+36
View File
@@ -0,0 +1,36 @@
{
"actions": {
"save": "Save",
"cancel": "Cancel",
"delete": "Delete",
"edit": "Edit",
"add": "Add",
"close": "Close",
"back": "Back",
"retry": "Try again",
"confirm": "Confirm",
"done": "Done",
"search": "Search"
},
"status": {
"loading": "Loading…",
"saving": "Saving…",
"saved": "Saved",
"error": "Something went wrong",
"offline": "No connection to the server"
},
"language": {
"label": "Language",
"changed": "Language changed",
"notSaved": "Language changed on this screen but couldn't be saved to your profile"
},
"ui": {
"close": "Close",
"dismiss": "Dismiss",
"loading": "Loading",
"moreInfo": "More info",
"notifications": "Notifications",
"backspace": "Delete",
"pinProgress": "{{count}} of {{total}} digits entered"
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"sample": {
"title": "Languages and formats",
"intro": "Switch the language: every text on this page changes at once, without reloading.",
"greeting": "Hello, {{name}}!",
"items_one": "{{count}} item in the order",
"items_other": "{{count}} items in the order",
"venueZone": "Venue time zone",
"deviceZone": "This device's time zone",
"venueNow": "Now at the venue",
"fixedTime": "An order sent at 10:00 UTC on 1 July 2026",
"businessDate": "Business date 2026-11-13",
"money": "Money",
"number": "Number",
"relative": "Five minutes ago",
"typePrice": "Type a price (comma or dot)",
"parsed": "Read as",
"invalid": "not a number",
"openDialog": "Open a dialog",
"dialogTitle": "Translated components",
"dialogBody": "The close button, the spinner and the help tip use the translated labels."
}
}
+14 -2
View File
@@ -3,9 +3,21 @@
"version": "0.0.0",
"private": true,
"type": "module",
"description": "i18next setup, en/el resources and format helpers for time, money and numbers (plan step 2.4).",
"description": "Translations (i18next, en/el), language resolution and venue-time formatting: dates, money, numbers (plan step 2.4).",
"main": "src/index.js",
"exports": {
".": "./src/index.js"
".": "./src/index.js",
"./sample": "./sample/Sample.jsx"
},
"scripts": {
"test": "node --test \"tests/*.test.mjs\"",
"check": "node scripts/check-i18n.mjs"
},
"dependencies": {
"i18next": "26.7.2",
"react-i18next": "17.1.13"
},
"peerDependencies": {
"react": "^19.0.0"
}
}
+102
View File
@@ -0,0 +1,102 @@
// Sample screen for @xenia/i18n (plan step 2.4 "done when"): the language switches live,
// and times show the VENUE's clock even on a device set to another time zone.
// Dev builds only: the manager mounts it at /i18n-sample under import.meta.env.DEV.
// The venue comes from GET /api/platform/bootstrap when a backend is running; otherwise
// the defaults (Europe/Athens, EUR).
import { useEffect, useMemo, useState } from 'react'
import { Button, Dialog, Field, InfoTip, Input, Select, Spinner, UiLabelsProvider } from '@xenia/ui'
import '@xenia/ui/styles.css'
import { createI18n, I18nProvider, LANGUAGE_NAMES, parseNumber, resolveLanguage, useFormat, useLanguage, useTranslation, useUiLabels } from '../src/index.js'
const FIXED = '2026-07-01T10:00:00Z'
const page = { minHeight: '100vh', background: 'var(--x-canvas)', color: 'var(--x-ink)', fontFamily: 'var(--x-font-sans)', padding: 'var(--x-space-6)' }
const card = { background: 'var(--x-surface)', border: '1px solid var(--x-line)', borderRadius: 'var(--x-radius-card)', padding: 'var(--x-space-6)', maxWidth: 720, display: 'grid', gap: 'var(--x-space-4)' }
const row = { display: 'grid', gridTemplateColumns: '220px 1fr', gap: 'var(--x-space-3)', alignItems: 'baseline' }
const muted = { color: 'var(--x-ink-2)' }
function Row({ label, children, testId }) {
return <div style={row}><span style={muted}>{label}</span><span data-testid={testId}>{children}</span></div>
}
function Content({ venue }) {
const { t } = useTranslation('dev')
const f = useFormat()
const { language, languages, changeLanguage } = useLanguage()
const [typed, setTyped] = useState('3,50')
const [open, setOpen] = useState(false)
const parsed = parseNumber(typed)
const [deviceZone] = useState(() => Intl.DateTimeFormat().resolvedOptions().timeZone)
const [now, setNow] = useState(() => Date.now())
const [fiveMinutesAgo] = useState(() => Date.now() - 5 * 60 * 1000)
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 1000)
return () => clearInterval(timer)
}, [])
return (
<div style={page}>
<div style={card}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 'var(--x-space-4)' }}>
<h1 style={{ margin: 0, fontSize: 'var(--x-text-heading)' }} data-testid="title">{t('sample.title')}</h1>
<Select
aria-label={t('common:language.label')} size="sm" value={language}
onChange={e => changeLanguage(e.target.value)}
options={languages.map(l => ({ value: l, label: LANGUAGE_NAMES[l] }))}
/>
</div>
<p style={{ margin: 0, ...muted }}>{t('sample.intro')}</p>
<Row label="t('sample.greeting')" testId="greeting">{t('sample.greeting', { name: 'Maria' })}</Row>
<Row label="plural, 1 / 3">{t('sample.items', { count: 1 })} · <span data-testid="plural">{t('sample.items', { count: 3 })}</span></Row>
<Row label={t('sample.venueZone')} testId="venue-zone">{f.timeZone}{venue ? '' : ' (default)'}</Row>
<Row label={t('sample.deviceZone')} testId="device-zone">{deviceZone}</Row>
<Row label={t('sample.venueNow')}>{f.formatDateTime(now, 'dateLong')} · {f.formatTime(now, 'timeSeconds')}</Row>
<Row label={t('sample.fixedTime')} testId="fixed-time">{f.formatDateTime(FIXED)}</Row>
<Row label={t('sample.businessDate')} testId="business-date">{f.formatDate('2026-11-13', 'dateLong')}</Row>
<Row label={t('sample.relative')} testId="relative">{f.formatRelative(fiveMinutesAgo)}</Row>
<Row label={t('sample.money')} testId="money">{f.formatMoney(1234.5)}</Row>
<Row label={t('sample.number')} testId="number">{f.formatNumber(1234.567)}</Row>
<Field label={t('sample.typePrice')} hint={`${t('sample.parsed')}: ${parsed == null ? t('sample.invalid') : f.formatMoney(parsed)}`}>
<Input value={typed} onChange={e => setTyped(e.target.value)} inputMode="decimal" data-testid="price-input" />
</Field>
<div style={{ display: 'flex', gap: 'var(--x-space-3)', alignItems: 'center' }}>
<Button variant="secondary" onClick={() => setOpen(true)}>{t('sample.openDialog')}</Button>
<InfoTip>{t('sample.dialogBody')}</InfoTip>
<Spinner size="sm" />
</div>
<Dialog open={open} onClose={() => setOpen(false)} title={t('sample.dialogTitle')}
footer={<Button onClick={() => setOpen(false)}>{t('common:actions.done')}</Button>}>
{t('sample.dialogBody')}
</Dialog>
</div>
</div>
)
}
function Labels({ children }) {
return <UiLabelsProvider labels={useUiLabels()}>{children}</UiLabelsProvider>
}
export default function Sample() {
const [venue, setVenue] = useState(null)
const i18n = useMemo(() => createI18n({ language: 'en', defaultNS: 'dev' }), [])
useEffect(() => {
let alive = true
fetch('/api/platform/bootstrap')
.then(r => (r.ok ? r.json() : null))
.then(b => {
if (!alive || !b?.venue) return
setVenue(b.venue)
i18n.changeLanguage(resolveLanguage({ user: b.user?.language, venue: b.venue.language }))
})
.catch(() => {})
return () => { alive = false }
}, [i18n])
return (
<I18nProvider i18n={i18n} venue={venue}>
<Labels><Content venue={venue} /></Labels>
</I18nProvider>
)
}
+125
View File
@@ -0,0 +1,125 @@
// Translation and time-zone guard (plan step 2.4, APPS_PLATFORM §7.2, §8).
//
// node packages/i18n/scripts/check-i18n.mjs (from client-services/; also run by npm test -w @xenia/i18n)
//
// ERRORS (exit 1):
// - a key used in code (t('…'), i18nKey="…") that isn't in the English files
// - a key whose {{placeholders}} differ between en and el
// - in new code (packages/*, terminal/): toLocaleString/-DateString/-TimeString or
// new Intl.DateTimeFormat( without a timeZone — dates must be shown in venue time (useFormat)
// WARNINGS (exit 0): English keys missing in Greek, Greek keys that English doesn't have.
//
// Only files that import react-i18next or @xenia/i18n are scanned for keys, so v1 code with
// its own `t` variables doesn't confuse it. A file's default namespace is the first
// useTranslation('ns') in it ("common" otherwise); "ns:key" overrides. Plural keys
// (key_one/key_other) count as the base key. Dynamic keys (t(`x.${y}`)) are skipped.
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const PKG = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const CS = path.resolve(PKG, '..', '..')
const LOCALES = path.join(PKG, 'locales')
const SOURCE = 'en'
const quiet = process.argv.includes('--quiet')
const errors = []
const warnings = []
const rel = p => path.relative(CS, p).split(path.sep).join('/')
// ── Locale files ─────────────────────────────────────────────────────────────
function flatten(obj, prefix = '', out = {}) {
for (const [k, v] of Object.entries(obj)) {
const key = prefix ? `${prefix}.${k}` : k
if (v && typeof v === 'object') flatten(v, key, out)
else out[key] = String(v)
}
return out
}
const langs = readdirSync(LOCALES).filter(d => statSync(path.join(LOCALES, d)).isDirectory())
const keys = {} // keys[lang]["ns:key"] = text
for (const lang of langs) {
keys[lang] = {}
for (const file of readdirSync(path.join(LOCALES, lang)).filter(f => f.endsWith('.json'))) {
const ns = file.slice(0, -5)
let data
try { data = JSON.parse(readFileSync(path.join(LOCALES, lang, file), 'utf8')) } catch (e) {
errors.push(`${lang}/${file}: invalid JSON (${e.message})`); continue
}
for (const [k, v] of Object.entries(flatten(data))) keys[lang][`${ns}:${k}`] = v
}
}
const placeholders = text => [...text.matchAll(/\{\{\s*([\w.]+)[^}]*\}\}/g)].map(m => m[1]).sort().join(',')
for (const lang of langs.filter(l => l !== SOURCE)) {
for (const [k, v] of Object.entries(keys[SOURCE])) {
if (!(k in keys[lang])) warnings.push(`${lang}: missing ${k}`)
else if (placeholders(v) !== placeholders(keys[lang][k])) {
errors.push(`${lang}: ${k} has placeholders {${placeholders(keys[lang][k])}}, English has {${placeholders(v)}}`)
}
}
for (const k of Object.keys(keys[lang])) if (!(k in keys[SOURCE])) warnings.push(`${lang}: ${k} isn't in English (remove it or add it to en)`)
}
const known = new Set(Object.keys(keys[SOURCE]).map(k => k.replace(/_(zero|one|two|few|many|other)$/, '')))
const exists = k => known.has(k) || (k in keys[SOURCE])
// ── Source files ─────────────────────────────────────────────────────────────
function walk(dir, out = []) {
if (!existsSync(dir)) return out
for (const name of readdirSync(dir)) {
if (name === 'node_modules' || name === 'dist' || name.startsWith('dist-') || name === 'android') continue
const p = path.join(dir, name)
if (statSync(p).isDirectory()) walk(p, out)
else if (/\.(jsx?|mjs|tsx?)$/.test(name)) out.push(p)
}
return out
}
const packages = readdirSync(path.join(CS, 'packages')).map(d => path.join(CS, 'packages', d))
// New code: every package (minus tests/scripts) and the terminal app. The v1 apps join as they're converted (phases 4, 6).
const newCode = [...packages.flatMap(p => ['src', 'gallery', 'sample'].map(d => path.join(p, d))), path.join(CS, 'terminal', 'src')]
const keyScan = [...newCode, path.join(CS, 'manager_dashboard', 'src'), path.join(CS, 'waiter_pwa', 'src')]
// The one place allowed to build Intl.DateTimeFormat directly (it always passes timeZone)
const TIME_ALLOW = new Set(['packages/i18n/src/format.js'])
const used = new Set()
for (const file of [...new Set(keyScan.flatMap(d => walk(d)))]) {
const text = readFileSync(file, 'utf8')
const r = rel(file)
const isNew = newCode.some(d => file.startsWith(d + path.sep))
if (isNew && !TIME_ALLOW.has(r)) {
text.split('\n').forEach((line, i) => {
if (/^\s*(\/\/|\*)/.test(line)) return
if (/\.toLocale(Date|Time)?String\(/.test(line) && !/timeZone/.test(line)) {
errors.push(`${r}:${i + 1}: toLocale…String() without timeZone; use useFormat() (venue time, §7.2)`)
}
if (/new Intl\.DateTimeFormat\(/.test(line) && !/timeZone/.test(line)) {
errors.push(`${r}:${i + 1}: Intl.DateTimeFormat without timeZone; use useFormat() (venue time, §7.2)`)
}
})
}
if (!/from ['"](react-i18next|@xenia\/i18n)['"]/.test(text)) continue
const defaultNs = text.match(/useTranslation\(\s*['"]([\w-]+)['"]/)?.[1] || 'common'
const found = [
...[...text.matchAll(/\bt\(\s*(['"])([^'"`$\n]+)\1/g)].map(m => [m[2], m.index]),
...[...text.matchAll(/i18nKey=(['"])([^'"]+)\1/g)].map(m => [m[2], m.index]),
]
for (const [raw, index] of found) {
const key = raw.includes(':') ? raw : `${defaultNs}:${raw}`
used.add(key)
// fallbackNS: a plain key also resolves from common
const ok = exists(key) || (!raw.includes(':') && exists(`common:${raw}`))
if (!ok) {
const line = text.slice(0, index).split('\n').length
errors.push(`${r}:${line}: key "${key}" is not in locales/${SOURCE}`)
}
}
}
// ── Report ───────────────────────────────────────────────────────────────────
if (!quiet) for (const w of warnings) console.log(`warning ${w}`)
for (const e of errors) console.log(`ERROR ${e}`)
const total = Object.keys(keys[SOURCE]).length
console.log(`i18n: ${langs.join('/')} · ${total} English keys · ${used.size} used in code · ${errors.length} error(s), ${warnings.length} warning(s)`)
process.exit(errors.length ? 1 : 0)
+4
View File
@@ -0,0 +1,4 @@
import { createContext } from 'react'
/** The venue formatters for the current language (filled by <I18nProvider>, read by useFormat()). */
export const FormatContext = createContext(null)
+135
View File
@@ -0,0 +1,135 @@
// Formatting dates, times, money and numbers (APPS_PLATFORM §7.2). Every date/time is
// shown in the VENUE's time zone (from bootstrap), never the device's: a phone or PC set
// to another zone must still show the restaurant's clock. No React: unit-tested in Node.
//
// const f = createFormatters({ language: 'el', timeZone: 'Europe/Athens', currency: 'EUR' })
// f.formatTime('2026-07-01T10:00:00Z') → "13:00"
// f.formatMoney(1234.5) → "1.234,50 €" (en: "€1,234.50")
//
// The backend sends ISO-8601 UTC with "Z" (§7.1). A string without an offset is read as
// UTC too (that's what the backend stores); a plain "YYYY-MM-DD" (business dates) is a
// calendar date and is never shifted by a time zone.
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, intlLocale } from './locale.js'
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/
const HAS_OFFSET = /(?:[zZ]|[+-]\d\d:?\d\d)$/
/** A Date from what the backend sends (ISO string, epoch ms, Date); null if unusable. */
export function toDate(value) {
if (value == null || value === '') return null
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value
if (typeof value === 'number') return new Date(value)
if (typeof value !== 'string') return null
if (DATE_ONLY.test(value)) return new Date(`${value}T00:00:00Z`)
const iso = HAS_OFFSET.test(value) ? value : `${value.replace(' ', 'T')}Z`
const d = new Date(iso)
return Number.isNaN(d.getTime()) ? null : d
}
// Named styles, so screens agree on what "a date" looks like. 24-hour clock everywhere.
export const DATE_STYLES = {
time: { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' },
timeSeconds: { hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' },
date: { day: '2-digit', month: '2-digit', year: 'numeric' }, // 13/11/2026
dateShort: { day: '2-digit', month: '2-digit' }, // 13/11
dateLong: { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' },
dateMedium: { day: 'numeric', month: 'short', year: 'numeric' }, // 13 Nov 2026
weekday: { weekday: 'long' },
datetime: { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' },
datetimeShort: { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' },
}
/**
* The formatters for one language + venue. Cheap to call often: Intl objects are cached.
* @param {{ language?: string, timeZone?: string, currency?: string }} opts
*/
export function createFormatters({ language = 'en', timeZone = DEFAULT_TIMEZONE, currency = DEFAULT_CURRENCY } = {}) {
const locale = intlLocale(language)
const cache = new Map()
const intl = (kind, key, make) => {
const k = `${kind}|${key}`
if (!cache.has(k)) cache.set(k, make())
return cache.get(k)
}
const dtf = (style, zone) => intl('dt', `${style}|${zone}`, () => {
const options = typeof style === 'string' ? DATE_STYLES[style] : style
if (!options) throw new Error(`unknown date style "${style}"`)
return new Intl.DateTimeFormat(locale, { ...options, timeZone: zone })
})
/** Any style from DATE_STYLES (or an Intl options object), in venue time. '' for no value. */
function formatDateTime(value, style = 'datetime') {
if (typeof value === 'string' && DATE_ONLY.test(value)) return formatDate(value, style)
const d = toDate(value)
return d ? dtf(typeof style === 'string' ? style : JSON.stringify(style), timeZone).format(d) : ''
}
const formatTime = (value, style = 'time') => formatDateTime(value, style)
/** A calendar date. A "YYYY-MM-DD" string is shown as that day exactly; a timestamp as its venue-time day. */
function formatDate(value, style = 'date') {
if (typeof value === 'string' && DATE_ONLY.test(value)) {
const d = toDate(value)
return dtf(style, 'UTC').format(d)
}
const d = toDate(value)
return d ? dtf(style, timeZone).format(d) : ''
}
/** "5 minutes ago", "in 2 hours", "yesterday", "now"; beyond ~4 weeks, the date. */
function formatRelative(value, now = Date.now()) {
const d = toDate(value)
if (!d) return ''
const rtf = intl('rt', 'auto', () => new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }))
const sec = Math.round((d.getTime() - (now instanceof Date ? now.getTime() : now)) / 1000)
const abs = Math.abs(sec)
if (abs < 45) return rtf.format(0, 'second')
if (abs < 45 * 60) return rtf.format(Math.round(sec / 60), 'minute')
if (abs < 22 * 3600) return rtf.format(Math.round(sec / 3600), 'hour')
if (abs < 26 * 86400) return rtf.format(Math.round(sec / 86400), 'day')
return formatDate(d)
}
/** Money in the venue currency: "12,50 €" (el), "€12.50" (en). '' for null. */
function formatMoney(amount, { currency: cur = currency, signDisplay = 'auto', decimals = 2 } = {}) {
if (amount == null || amount === '' || !Number.isFinite(Number(amount))) return ''
const nf = intl('money', `${cur}|${signDisplay}|${decimals}`, () => new Intl.NumberFormat(locale, {
style: 'currency', currency: cur, signDisplay, minimumFractionDigits: decimals, maximumFractionDigits: decimals,
}))
return nf.format(Number(amount))
}
/** A number with the language's separators. decimals: exact digits; maxDecimals: up to. */
function formatNumber(value, { decimals, maxDecimals = 2 } = {}) {
if (value == null || value === '' || !Number.isFinite(Number(value))) return ''
const nf = intl('num', `${decimals}|${maxDecimals}`, () => new Intl.NumberFormat(locale, decimals != null
? { minimumFractionDigits: decimals, maximumFractionDigits: decimals }
: { maximumFractionDigits: maxDecimals }))
return nf.format(Number(value))
}
/** 0.235 → "23,5 %" (el) / "23.5%" (en). */
function formatPercent(ratio, { maxDecimals = 1 } = {}) {
if (ratio == null || !Number.isFinite(Number(ratio))) return ''
return intl('pct', String(maxDecimals), () => new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: maxDecimals })).format(Number(ratio))
}
/** Today's date in the venue, "YYYY-MM-DD" (for date pickers and "today" filters). */
function venueToday(now = new Date()) {
return venueDateKey(now)
}
/** The venue-time calendar day of a timestamp, "YYYY-MM-DD". */
function venueDateKey(value) {
const d = toDate(value)
if (!d) return ''
const parts = intl('key', timeZone, () => new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })).formatToParts(d)
const get = t => parts.find(p => p.type === t).value
return `${get('year')}-${get('month')}-${get('day')}`
}
return {
language, locale, timeZone, currency,
formatDateTime, formatTime, formatDate, formatRelative,
formatMoney, formatNumber, formatPercent, venueToday, venueDateKey,
}
}
+39
View File
@@ -0,0 +1,39 @@
import { useContext, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { FormatContext } from './context.js'
import { SUPPORTED_LANGUAGES } from './locale.js'
/** formatTime, formatDateTime, formatDate, formatRelative, formatMoney, formatNumber, formatPercent, venueToday… */
export function useFormat() {
const ctx = useContext(FormatContext)
if (!ctx) throw new Error('useFormat() needs an <I18nProvider> above it')
return ctx
}
/** { language, languages, changeLanguage } for language pickers (screen only; see setUserLanguage to save). */
export function useLanguage() {
const { i18n } = useTranslation()
return {
language: i18n.resolvedLanguage || i18n.language,
languages: SUPPORTED_LANGUAGES,
changeLanguage: lng => i18n.changeLanguage(lng),
}
}
/**
* The @xenia/ui components' own texts, translated (common:ui.*). Use once at the root:
* <UiLabelsProvider labels={useUiLabels()}>
*/
export function useUiLabels() {
const { t, i18n } = useTranslation('common')
const language = i18n.resolvedLanguage || i18n.language
return useMemo(() => ({
close: t('ui.close'),
dismiss: t('ui.dismiss'),
loading: t('ui.loading'),
moreInfo: t('ui.moreInfo'),
notifications: t('ui.notifications'),
backspace: t('ui.backspace'),
pinProgress: (count, total) => t('ui.pinProgress', { count, total }),
}), [t, language]) // eslint-disable-line react-hooks/exhaustive-deps
}
+50
View File
@@ -0,0 +1,50 @@
import i18next from 'i18next'
import { initReactI18next } from 'react-i18next'
import { FALLBACK_LANGUAGE, SUPPORTED_LANGUAGES, normalizeLanguage } from './locale.js'
import { NAMESPACES, resources } from './resources.js'
const DEV = typeof import.meta !== 'undefined' && !!import.meta.env?.DEV
/**
* One i18next instance per app, ready synchronously (resources are bundled).
*
* const i18n = createI18n({ language: resolveLanguage({ venue: 'el' }) })
* <I18nProvider i18n={i18n} venue={bootstrap.venue}>…</I18nProvider>
*
* A key missing in the current language falls back to English. A key missing in English
* too renders the key itself and, in dev builds, warns in the console (and
* scripts/check-i18n.mjs fails on it before it gets that far).
* `extra` adds resources ({ el: { myns: {...} } }) on top of the bundled ones.
*/
export function createI18n({ language = FALLBACK_LANGUAGE, defaultNS = 'common', extra } = {}) {
const i18n = i18next.createInstance()
i18n.use(initReactI18next).init({
resources: mergeResources(resources, extra),
lng: normalizeLanguage(language) || FALLBACK_LANGUAGE,
fallbackLng: FALLBACK_LANGUAGE,
supportedLngs: SUPPORTED_LANGUAGES,
ns: NAMESPACES,
defaultNS,
fallbackNS: 'common',
interpolation: { escapeValue: false }, // React escapes already
returnNull: false,
initAsync: false,
saveMissing: DEV,
missingKeyHandler: DEV ? (lngs, ns, key) => console.warn(`[i18n] missing key "${ns}:${key}" (${lngs.join(', ')})`) : undefined,
react: { useSuspense: false },
})
const setHtmlLang = lng => { if (typeof document !== 'undefined') document.documentElement.lang = lng }
setHtmlLang(i18n.language)
i18n.on('languageChanged', setHtmlLang)
return i18n
}
function mergeResources(base, extra) {
if (!extra) return base
const out = { ...base }
for (const [lng, namespaces] of Object.entries(extra)) {
out[lng] = { ...(out[lng] || {}) }
for (const [ns, data] of Object.entries(namespaces)) out[lng][ns] = { ...(out[lng][ns] || {}), ...data }
}
return out
}
+25 -3
View File
@@ -1,3 +1,25 @@
// @xenia/i18n — i18next setup, en/el resources and format helpers for time, money and numbers (plan step 2.4).
// Imported from source by Vite (no build step). Filled in by its plan step.
export {}
// @xenia/i18n — translations, language choice and venue-time formatting for every
// frontend (APPS_PLATFORM D-11, D-12, §7.2, §8; plan step 2.4). Imported from source by Vite.
//
// const i18n = createI18n({ language: resolveLanguage({ user, device, venue }) })
// <I18nProvider i18n={i18n} venue={bootstrap.venue}>
// <UiLabelsProvider labels={useUiLabels()}>… (@xenia/ui component texts)
// const { t } = useTranslation('manager'); const { formatTime, formatMoney } = useFormat()
//
// Rules: never toLocaleString()/Intl.DateTimeFormat without the venue zone (use useFormat);
// new UI text is a key in locales/en (+ el); run `npm test -w @xenia/i18n` (includes
// scripts/check-i18n.mjs) after adding keys.
export { createI18n } from './i18n.js'
export { setUserLanguage } from './language.js'
export { I18nProvider } from './provider.jsx'
export { useFormat, useLanguage, useUiLabels } from './hooks.js'
export { createFormatters, toDate, DATE_STYLES } from './format.js'
export { parseNumber } from './number.js'
export {
SUPPORTED_LANGUAGES, FALLBACK_LANGUAGE, LANGUAGE_NAMES, DEFAULT_TIMEZONE, DEFAULT_CURRENCY,
resolveLanguage, normalizeLanguage, intlLocale,
} from './locale.js'
export { NAMESPACES } from './resources.js'
// Re-exported so apps depend on one package for translation
export { useTranslation, Trans } from 'react-i18next'
+17
View File
@@ -0,0 +1,17 @@
import { FALLBACK_LANGUAGE, normalizeLanguage } from './locale.js'
/**
* Switch the signed-in user's language: the screen changes at once, then the choice is
* saved to their profile (PATCH /api/auth/me {language}) through `save`, which the app
* provides (its API client; @xenia/api from 2.5). Pass `language: null` to go back to
* inheriting (device → venue), with `fallback` = the language to show then.
* If saving fails the screen keeps the new language and the error is rethrown, so the
* caller can say "changed here, not saved".
*/
export async function setUserLanguage(i18n, language, { save, fallback } = {}) {
const lng = normalizeLanguage(language)
if (language && !lng) throw new Error(`unsupported language "${language}"`)
await i18n.changeLanguage(lng || normalizeLanguage(fallback) || FALLBACK_LANGUAGE)
if (save) await save(lng ?? '')
return i18n.language
}
+40
View File
@@ -0,0 +1,40 @@
// Languages and their Intl locales, and the D-12 resolution order. No React, no i18next:
// unit-tested in Node (tests/locale.test.mjs).
/** Languages with a full set of locale files. English is the source and the fallback. */
export const SUPPORTED_LANGUAGES = ['en', 'el']
export const FALLBACK_LANGUAGE = 'en'
/** Each language in its own name, for language pickers (never translated). */
export const LANGUAGE_NAMES = { en: 'English', el: 'Ελληνικά' }
/** Same default as the backend (core/timeutil.py DEFAULT_TZ); bootstrap always sends the real one. */
export const DEFAULT_TIMEZONE = 'Europe/Athens'
export const DEFAULT_CURRENCY = 'EUR'
// en-GB rather than en-US: day/month order and a 24-hour clock, as everyone in Greece expects
const INTL_LOCALES = { en: 'en-GB', el: 'el-GR' }
/** The Intl locale (BCP 47) for one of our language codes. */
export function intlLocale(language) {
return INTL_LOCALES[normalizeLanguage(language)] || INTL_LOCALES[FALLBACK_LANGUAGE]
}
/** 'el-GR' → 'el', 'EN' → 'en'; anything we don't support → null. */
export function normalizeLanguage(value, supported = SUPPORTED_LANGUAGES) {
if (!value || typeof value !== 'string') return null
const base = value.trim().toLowerCase().split(/[-_]/)[0]
return supported.includes(base) ? base : null
}
/**
* Which language to show (D-12, APPS_PLATFORM §8): the user's own choice, then the
* device's configured language, then the venue default, then English.
* resolveLanguage({ user: bootstrap.user?.language, device: device?.config?.language, venue: bootstrap.venue.language })
*/
export function resolveLanguage({ user, device, venue, supported = SUPPORTED_LANGUAGES } = {}) {
return normalizeLanguage(user, supported)
|| normalizeLanguage(device, supported)
|| normalizeLanguage(venue, supported)
|| FALLBACK_LANGUAGE
}
+71
View File
@@ -0,0 +1,71 @@
// Reading numbers people type (roadmap: "accept , as the decimal separator").
// Staff type prices and quantities with a comma (Greek habit) or a dot (phone keypads,
// English habit). Both must work, whatever the UI language. Unit-tested in Node.
/**
* Parse a typed number. Returns a Number, or null when the text isn't a number.
*
* "3,50" → 3.5 "3.50" → 3.5 ",5" → 0.5 "1.234,56" → 1234.56
* "1,234.56" → 1234.56 "1.234.567" → 1234567 "€ 12,00" → 12 " -2,5 " → -2.5
*
* Rules:
* - spaces, the € sign and a trailing % are ignored
* - both "," and "." present: the LAST one is the decimal separator, the other groups thousands
* - only one kind present, once: it's the decimal separator ("2,500" is 2.5, not 2500 —
* a POS sees prices far more often than four-digit amounts typed with a separator)
* - only one kind present, several times: thousands separators, groups of exactly 3 digits
*
* Options: { decimals } rounds the result (e.g. 2 for money); { allowNegative = true }.
*/
export function parseNumber(input, { decimals, allowNegative = true } = {}) {
if (typeof input === 'number') return Number.isFinite(input) ? round(input, decimals) : null
if (typeof input !== 'string') return null
let s = input.replace(/[\s\u00a0\u202f€]/g, '').replace(/%$/, '')
if (!s) return null
let sign = 1
if (s[0] === '-' || s[0] === '+') {
if (s[0] === '-') sign = -1
s = s.slice(1)
}
if (sign < 0 && !allowNegative) return null
if (!/^[\d.,]+$/.test(s) || !/\d/.test(s)) return null
const lastComma = s.lastIndexOf(',')
const lastDot = s.lastIndexOf('.')
let normalized
if (lastComma >= 0 && lastDot >= 0) {
const dec = lastComma > lastDot ? ',' : '.'
const group = dec === ',' ? '.' : ','
const [intPart, frac, ...extra] = s.split(dec)
if (extra.length || !validGroups(intPart, group)) return null
normalized = intPart.split(group).join('') + '.' + frac
} else if (lastComma >= 0 || lastDot >= 0) {
const sep = lastComma >= 0 ? ',' : '.'
const parts = s.split(sep)
if (parts.length === 2) {
normalized = parts[0] + '.' + parts[1]
} else {
if (!validGroups(s, sep)) return null
normalized = parts.join('')
}
} else {
normalized = s
}
if (!/^\d*\.?\d*$/.test(normalized) || normalized === '.') return null
const value = sign * Number(normalized)
return Number.isFinite(value) ? round(value, decimals) : null
}
/** "1.234.567" with group "." → valid; "12.34" → invalid (groups after the first must be 3 digits). */
function validGroups(text, group) {
const parts = text.split(group)
if (parts.length === 1) return true
return parts[0].length >= 1 && parts[0].length <= 3 && parts.slice(1).every(p => /^\d{3}$/.test(p))
}
function round(value, decimals) {
if (decimals == null) return value
const f = 10 ** decimals
return Math.round((value + Number.EPSILON * Math.sign(value)) * f) / f
}
+27
View File
@@ -0,0 +1,27 @@
import { useMemo } from 'react'
import { I18nextProvider, useTranslation } from 'react-i18next'
import { FormatContext } from './context.js'
import { createFormatters } from './format.js'
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE } from './locale.js'
/**
* Put translations and venue formatting into the tree. `venue` is bootstrap.venue
* ({ timezone, currency, … }); until it's loaded the defaults (Europe/Athens, EUR) apply.
* Formatters follow the current language live.
*/
export function I18nProvider({ i18n, venue, children }) {
return (
<I18nextProvider i18n={i18n}>
<Formats venue={venue}>{children}</Formats>
</I18nextProvider>
)
}
function Formats({ venue, children }) {
const { i18n } = useTranslation()
const language = i18n.resolvedLanguage || i18n.language
const timeZone = venue?.timezone || DEFAULT_TIMEZONE
const currency = venue?.currency || DEFAULT_CURRENCY
const value = useMemo(() => createFormatters({ language, timeZone, currency }), [language, timeZone, currency])
return <FormatContext.Provider value={value}>{children}</FormatContext.Provider>
}
+15
View File
@@ -0,0 +1,15 @@
// Every locale file, bundled (they're small; no loading step, no flash of keys).
// Layout (APPS_PLATFORM §8): locales/<lang>/<namespace>.json. English is the source.
// Namespaces: common (shared words, component labels), dev (sample screens). Apps add
// theirs here as they're converted: manager, waiter, terminal, modules.
import elCommon from '../locales/el/common.json'
import elDev from '../locales/el/dev.json'
import enCommon from '../locales/en/common.json'
import enDev from '../locales/en/dev.json'
export const NAMESPACES = ['common', 'dev']
export const resources = {
en: { common: enCommon, dev: enDev },
el: { common: elCommon, dev: elDev },
}
+37
View File
@@ -0,0 +1,37 @@
// The guard passes on the current code, and fails on what it's meant to catch.
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { test } from 'node:test'
import { fileURLToPath } from 'node:url'
const PKG = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const SCRIPT = path.join(PKG, 'scripts', 'check-i18n.mjs')
const run = () => spawnSync(process.execPath, [SCRIPT, '--quiet'], { encoding: 'utf8' })
test('the repo passes the i18n guard', () => {
const r = run()
assert.equal(r.status, 0, r.stdout + r.stderr)
})
test('it catches unknown keys and dates without the venue zone', () => {
const dir = path.join(PKG, 'sample', '__guard_probe__')
mkdirSync(dir, { recursive: true })
try {
writeFileSync(path.join(dir, 'Probe.jsx'), [
"import { useTranslation } from '@xenia/i18n'",
"export function Probe() { const { t } = useTranslation('dev')",
" return t('sample.doesNotExist') + t('sample.title') + t('common:actions.save') + t('actions.cancel')",
" + new Date().toLocaleTimeString() + new Intl.DateTimeFormat('el').format(new Date()) }",
].join('\n'))
const r = run()
assert.equal(r.status, 1)
assert.match(r.stdout, /key "dev:sample\.doesNotExist" is not in locales\/en/)
assert.doesNotMatch(r.stdout, /sample\.title"|actions\.save"|actions\.cancel"/)
assert.match(r.stdout, /Probe\.jsx:4: toLocale…String\(\) without timeZone/)
assert.match(r.stdout, /Probe\.jsx:4: Intl\.DateTimeFormat without timeZone/)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
+74
View File
@@ -0,0 +1,74 @@
// Formatting in the venue's zone. The test process may run in any zone: force a far one
// so a formatter that used the device zone would fail.
process.env.TZ = 'America/New_York'
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { createFormatters, toDate } from '../src/format.js'
const el = createFormatters({ language: 'el', timeZone: 'Europe/Athens', currency: 'EUR' })
const en = createFormatters({ language: 'en', timeZone: 'Europe/Athens', currency: 'EUR' })
const nbsp = s => s.replace(/[\u00a0\u202f]/g, ' ')
test('times are venue time, not device time (summer UTC+3, winter UTC+2)', () => {
assert.equal(new Date('2026-07-01T10:00:00Z').getHours(), 6, 'the process really runs in New York')
assert.equal(el.formatTime('2026-07-01T10:00:00Z'), '13:00')
assert.equal(el.formatTime('2026-01-15T10:00:00Z'), '12:00')
assert.equal(en.formatTime('2026-07-01T22:30:00Z'), '01:30')
})
test('the venue day, across midnight', () => {
assert.equal(el.formatDate('2026-07-01T22:30:00Z'), '02/07/2026')
assert.equal(el.venueDateKey('2026-07-01T22:30:00Z'), '2026-07-02')
assert.equal(el.venueDateKey('2026-07-01T20:59:00Z'), '2026-07-01')
})
test('DST changes in Athens (§7.3)', () => {
// 25 Oct 2026, 04:00 local happens twice: 00:59Z is 03:59 EEST, 01:00Z is 03:00 EET
assert.equal(el.formatTime('2026-10-25T00:59:00Z'), '03:59')
assert.equal(el.formatTime('2026-10-25T01:00:00Z'), '03:00')
// 29 Mar 2026, 03:00 local is skipped: 00:59Z is 02:59 EET, 01:00Z is 04:00 EEST
assert.equal(el.formatTime('2026-03-29T00:59:00Z'), '02:59')
assert.equal(el.formatTime('2026-03-29T01:00:00Z'), '04:00')
})
test('business dates (YYYY-MM-DD) are never shifted', () => {
const ny = createFormatters({ language: 'en', timeZone: 'America/Los_Angeles' })
assert.equal(ny.formatDate('2026-11-13'), '13/11/2026')
assert.equal(el.formatDate('2026-11-13'), '13/11/2026')
assert.match(el.formatDate('2026-11-13', 'dateLong'), /Παρασκευή.*13.*Νοεμβρίου.*2026/)
assert.match(en.formatDate('2026-11-13', 'dateLong'), /Friday.*13.*November.*2026/)
})
test('backend strings without an offset are UTC', () => {
assert.equal(toDate('2026-07-01 10:00:00.123456').toISOString(), '2026-07-01T10:00:00.123Z')
assert.equal(toDate('2026-07-01T10:00:00').toISOString(), '2026-07-01T10:00:00.000Z')
assert.equal(toDate('2026-07-01T13:00:00+03:00').toISOString(), '2026-07-01T10:00:00.000Z')
assert.equal(toDate('nonsense'), null)
assert.equal(el.formatDateTime(null), '')
})
test('date-time styles use a 24-hour clock in both languages', () => {
assert.equal(el.formatDateTime('2026-07-01T16:05:00Z'), '01/07/2026, 19:05')
assert.equal(en.formatDateTime('2026-07-01T16:05:00Z'), '01/07/2026, 19:05')
assert.equal(en.formatTime('2026-07-01T16:05:09Z', 'timeSeconds'), '19:05:09')
})
test('money and numbers per language', () => {
assert.equal(nbsp(el.formatMoney(1234.5)), '1.234,50 €')
assert.equal(en.formatMoney(1234.5), '€1,234.50')
assert.equal(nbsp(el.formatMoney(-3)), '-3,00 €')
assert.equal(el.formatMoney(null), '')
assert.equal(el.formatNumber(1234.567), '1.234,57')
assert.equal(en.formatNumber(2.5, { decimals: 2 }), '2.50')
assert.equal(nbsp(el.formatPercent(0.235)), '23,5%')
})
test('relative times', () => {
const now = Date.parse('2026-07-01T10:00:00Z')
assert.equal(en.formatRelative('2026-07-01T09:55:00Z', now), '5 minutes ago')
assert.equal(el.formatRelative('2026-07-01T09:55:00Z', now), 'πριν από 5 λεπτά')
assert.equal(en.formatRelative('2026-07-01T09:59:40Z', now), 'now')
assert.equal(en.formatRelative('2026-06-30T10:00:00Z', now), 'yesterday')
assert.equal(en.formatRelative('2026-07-01T12:00:00Z', now), 'in 2 hours')
assert.equal(en.formatRelative('2026-04-01T10:00:00Z', now), '01/04/2026')
})
+30
View File
@@ -0,0 +1,30 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { setUserLanguage } from '../src/language.js'
const fakeI18n = () => ({ language: 'en', async changeLanguage(l) { this.language = l } })
test('switches the screen, then saves to the profile', async () => {
const i18n = fakeI18n(); const saved = []
assert.equal(await setUserLanguage(i18n, 'el', { save: async l => saved.push(l) }), 'el')
assert.deepEqual(saved, ['el'])
})
test('null = inherit again: shows the fallback, saves ""', async () => {
const i18n = fakeI18n(); const saved = []
await setUserLanguage(i18n, null, { fallback: 'el', save: async l => saved.push(l) })
assert.equal(i18n.language, 'el')
assert.deepEqual(saved, [''])
})
test('a failed save keeps the new language on screen and rethrows', async () => {
const i18n = fakeI18n()
await assert.rejects(setUserLanguage(i18n, 'el', { save: async () => { throw new Error('offline') } }), /offline/)
assert.equal(i18n.language, 'el')
})
test('unsupported languages are refused before anything changes', async () => {
const i18n = fakeI18n()
await assert.rejects(setUserLanguage(i18n, 'fr'), /unsupported/)
assert.equal(i18n.language, 'en')
})
+24
View File
@@ -0,0 +1,24 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { intlLocale, normalizeLanguage, resolveLanguage } from '../src/locale.js'
test('resolution order: user → device → venue → en (D-12)', () => {
assert.equal(resolveLanguage({ user: 'el', device: 'en', venue: 'en' }), 'el')
assert.equal(resolveLanguage({ user: null, device: 'el', venue: 'en' }), 'el')
assert.equal(resolveLanguage({ user: '', device: undefined, venue: 'el' }), 'el')
assert.equal(resolveLanguage({}), 'en')
assert.equal(resolveLanguage(), 'en')
})
test('unsupported or odd values are skipped', () => {
assert.equal(resolveLanguage({ user: 'fr', venue: 'el' }), 'el')
assert.equal(resolveLanguage({ user: 'el-GR' }), 'el')
assert.equal(normalizeLanguage(' EN '), 'en')
assert.equal(normalizeLanguage(42), null)
})
test('Intl locales', () => {
assert.equal(intlLocale('el'), 'el-GR')
assert.equal(intlLocale('en'), 'en-GB')
assert.equal(intlLocale('fr'), 'en-GB')
})
+38
View File
@@ -0,0 +1,38 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { parseNumber } from '../src/number.js'
test('comma or dot as the decimal separator', () => {
for (const [input, want] of [
['3,50', 3.5], ['3.50', 3.5], [',5', 0.5], ['.5', 0.5], ['3', 3], ['3,', 3], ['0,10', 0.1],
['12', 12], ['2,500', 2.5], ['2.500', 2.5],
]) assert.equal(parseNumber(input), want, input)
})
test('thousands separators', () => {
for (const [input, want] of [
['1.234,56', 1234.56], ['1,234.56', 1234.56], ['1.234.567', 1234567], ['1,234,567', 1234567],
['12.345,6', 12345.6], ['1.234.567,89', 1234567.89],
]) assert.equal(parseNumber(input), want, input)
})
test('signs, spaces, euro, percent', () => {
for (const [input, want] of [
[' -2,5 ', -2.5], ['+4', 4], ['€ 12,00', 12], ['12,00 €', 12], ['1\u00a0234,5', 1234.5], ['15%', 15],
]) assert.equal(parseNumber(input), want, input)
assert.equal(parseNumber('-3', { allowNegative: false }), null)
})
test('not numbers', () => {
for (const input of ['', ' ', 'abc', '1,2,3', '12.34.5', '1.23,4.5', '.', ',', '-', '3,5x', '1e5', null, undefined, {}]) {
assert.equal(parseNumber(input), null, String(input))
}
})
test('numbers pass through; decimals rounds', () => {
assert.equal(parseNumber(4.25), 4.25)
assert.equal(parseNumber(Number.NaN), null)
assert.equal(parseNumber('2,345', { decimals: 2 }), 2.35)
assert.equal(parseNumber('1,005', { decimals: 2 }), 1.01)
assert.equal(parseNumber('-1,005', { decimals: 2 }), -1.01)
})
+1 -1
View File
@@ -62,7 +62,7 @@ function Demo() {
}, [theme, venue])
const checkPin = pin => new Promise((resolve, reject) => setTimeout(() => {
if (pin === '1234') { setPinError(''); setUnlocked(`Unlocked at ${new Date().toLocaleTimeString()}`); resolve() }
if (pin === '1234') { setPinError(''); setUnlocked(n => `Unlocked (${n ? Number(n.slice(10, -1)) + 1 : 1})`); resolve() }
else { setPinError('Wrong PIN'); reject(new Error('wrong')) }
}, 500))
+1 -1
View File
@@ -12,7 +12,7 @@ import { ModalFrame } from '../internal/ModalFrame.jsx'
*
* Escape, the backdrop and the × close it; focus moves in, is trapped, and returns
* to where it was. dismissible={false} for steps that must be finished (no ×, no Escape).
* size: 'sm' (400px) | 'md' (520px) | 'lg' (720px). closeLabel: the × text (translate it).
* size: 'sm' (400px) | 'md' (520px) | 'lg' (720px). closeLabel overrides the × text (default: UiLabelsProvider's).
* initialFocus: a ref to focus first (default: the first field or button in the body).
*/
export function Dialog({ size = 'md', className, ...props }) {
+5 -3
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
import { cx } from '../internal/cx.js'
import { Portal } from '../internal/Portal.jsx'
import { useLabels } from './labels.js'
const GAP = 8
const MARGIN = 8
@@ -12,9 +13,10 @@ const MARGIN = 8
*
* <label>Alert after failures <InfoTip>How many failed print attempts before managers are notified. 0 turns it off.</InfoTip></label>
*
* label: the button's accessible name (translate it). side: 'top' | 'bottom' (preferred side).
* label overrides the button's accessible name (default: UiLabelsProvider's "moreInfo"). side: 'top' | 'bottom'.
*/
export function InfoTip({ children, label = 'More info', side = 'top', className }) {
export function InfoTip({ children, label, side = 'top', className }) {
const labels = useLabels()
const [open, setOpen] = useState(false)
const [pos, setPos] = useState(null)
const button = useRef(null)
@@ -61,7 +63,7 @@ export function InfoTip({ children, label = 'More info', side = 'top', className
ref={button}
type="button"
className={cx('x-infotip', open && 'x-infotip--open', className)}
aria-label={label}
aria-label={label ?? labels.moreInfo}
aria-expanded={open}
aria-describedby={open ? id : undefined}
onClick={() => setOpen(o => !o)}
+8 -6
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react
import { cx } from '../internal/cx.js'
import { Spinner } from './Spinner.jsx'
import { nextPin, pinAction } from './pin.js'
import { useLabels } from './labels.js'
const KEYS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', null, '0', 'Backspace']
@@ -17,14 +18,15 @@ const KEYS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', null, '0', 'Backspace
* error: text under the dots (e.g. "Wrong PIN"); a change of it also shakes the pad.
* captureKeyboard (default true): digits/Backspace typed anywhere go to the pad,
* except while the user is typing in a field.
* Labels for translation: backspaceLabel, progressLabel(n, length).
* backspaceLabel / progressLabel(n, length) override the UiLabelsProvider texts.
*/
export function PinPad({
length = 4, onComplete, onChange, disabled = false, error, title,
captureKeyboard = true, backspaceLabel = 'Delete',
progressLabel = (n, total) => `${n} of ${total} digits entered`,
className,
captureKeyboard = true, backspaceLabel, progressLabel, className,
}) {
const labels = useLabels()
const backspaceText = backspaceLabel ?? labels.backspace
const progress = progressLabel ?? labels.pinProgress
const [value, setValue] = useState('')
const [busy, setBusy] = useState(false)
const [shake, setShake] = useState(0)
@@ -87,7 +89,7 @@ export function PinPad({
<span key={i} className={cx('x-pinpad__dot', i < value.length && 'x-pinpad__dot--filled', error && 'x-pinpad__dot--error')} />
))}
</div>
<div className="x-visually-hidden" aria-live="polite">{progressLabel(value.length, length)}</div>
<div className="x-visually-hidden" aria-live="polite">{progress(value.length, length)}</div>
<div className="x-pinpad__status">
{busy ? <Spinner size="sm" /> : error ? <span className="x-pinpad__error" role="alert">{error}</span> : null}
</div>
@@ -101,7 +103,7 @@ export function PinPad({
className={cx('x-pinpad__key', k === 'Backspace' && 'x-pinpad__key--backspace')}
onClick={() => press(k)}
disabled={disabled || busy}
aria-label={k === 'Backspace' ? backspaceLabel : undefined}
aria-label={k === 'Backspace' ? backspaceText : undefined}
>
{k === 'Backspace'
? (
+8 -5
View File
@@ -1,23 +1,26 @@
import { cx } from '../internal/cx.js'
import { useLabels } from './labels.js'
/**
* Loading indicator. With a `label` (default "Loading") it is announced to screen
* Loading indicator. With a `label` (default: the "loading" label) it is announced to screen
* readers; pass label={null} when the surrounding element already says it (a busy button).
* size: 'sm' (16px) | 'md' (24px) | 'lg' (40px)
*/
export function Spinner({ size = 'md', label = 'Loading', className, ...rest }) {
export function Spinner({ size = 'md', label, className, ...rest }) {
const labels = useLabels()
const text = label === undefined ? labels.loading : label
return (
<span
className={cx('x-spinner', `x-spinner--${size}`, className)}
role={label ? 'status' : undefined}
aria-hidden={label ? undefined : true}
role={text ? 'status' : undefined}
aria-hidden={text ? undefined : true}
{...rest}
>
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity="0.25" strokeWidth="3" />
<path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
</svg>
{label && <span className="x-visually-hidden">{label}</span>}
{text && <span className="x-visually-hidden">{text}</span>}
</span>
)
}
+6 -4
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { cx } from '../internal/cx.js'
import { Portal } from '../internal/Portal.jsx'
import { ToastContext } from './toastContext.js'
import { useLabels } from './labels.js'
let nextId = 1
@@ -14,10 +15,11 @@ let nextId = 1
* tone: 'neutral' | 'success' | 'warning' | 'danger' | 'info'. duration in ms (0 = stays until closed).
* Danger toasts are announced assertively (role="alert"), the rest politely.
* The timer pauses while the pointer is over a toast.
* placement: 'top-right' | 'top-center' | 'bottom-center'. closeLabel: the × text (translate it).
* placement: 'top-right' | 'top-center' | 'bottom-center'. closeLabel overrides the × text.
*/
export function ToastProvider({ children, placement = 'top-right', max = 4, closeLabel = 'Dismiss' }) {
export function ToastProvider({ children, placement = 'top-right', max = 4, closeLabel }) {
const [toasts, setToasts] = useState([])
const labels = useLabels()
const dismiss = useCallback(id => setToasts(list => list.filter(t => t.id !== id)), [])
const show = useCallback(opts => {
@@ -37,8 +39,8 @@ export function ToastProvider({ children, placement = 'top-right', max = 4, clos
<ToastContext.Provider value={api}>
{children}
<Portal>
<div className={cx('x-toasts', `x-toasts--${placement}`)} role="region" aria-label="Notifications">
{toasts.map(t => <ToastItem key={t.id} toast={t} onDismiss={dismiss} closeLabel={closeLabel} />)}
<div className={cx('x-toasts', `x-toasts--${placement}`)} role="region" aria-label={labels.notifications}>
{toasts.map(t => <ToastItem key={t.id} toast={t} onDismiss={dismiss} closeLabel={closeLabel ?? labels.dismiss} />)}
</div>
</Portal>
</ToastContext.Provider>
+27
View File
@@ -0,0 +1,27 @@
import { createContext, createElement, useContext } from 'react'
// The components' own visible/announced texts. English defaults; an app translates
// them once at the root:
// <UiLabelsProvider labels={useUiLabels()}> (useUiLabels from @xenia/i18n: translated labels)
// A prop on a component (closeLabel, label…) still wins over the context.
export const DEFAULT_LABELS = {
close: 'Close',
dismiss: 'Dismiss',
loading: 'Loading',
moreInfo: 'More info',
notifications: 'Notifications',
backspace: 'Delete',
pinProgress: (n, total) => `${n} of ${total} digits entered`,
}
const LabelsContext = createContext(DEFAULT_LABELS)
export function UiLabelsProvider({ labels, children }) {
return createElement(LabelsContext.Provider, { value: { ...DEFAULT_LABELS, ...labels } }, children)
}
/** The labels in effect (internal to the components). */
export function useLabels() {
return useContext(LabelsContext)
}
+3 -2
View File
@@ -6,8 +6,8 @@
// import '@xenia/ui/styles.css' tokens + the components' styles (.x-* classes)
// Tailwind apps also add the preset: import xenia from '@xenia/ui/tailwind-preset'.
//
// Components ship English default labels (Close, Loading, Delete…); pass translated
// ones as props until @xenia/i18n exists (2.4).
// Components' own texts (Close, Loading, Delete…) come from <UiLabelsProvider> (English
// defaults); @xenia/i18n's useUiLabels() gives the translated set. Props still override.
export { Button, IconButton } from './components/Button.jsx'
export { Dialog } from './components/Dialog.jsx'
@@ -20,4 +20,5 @@ export { EmptyState } from './components/EmptyState.jsx'
export { Spinner } from './components/Spinner.jsx'
export { Field, Input, Textarea, Select } from './components/Field.jsx'
export { Switch } from './components/Switch.jsx'
export { UiLabelsProvider, DEFAULT_LABELS } from './components/labels.js'
export { cx } from './internal/cx.js'
+4 -2
View File
@@ -3,6 +3,7 @@ import { cx } from './cx.js'
import { Portal } from './Portal.jsx'
import { useModal } from './useModal.js'
import { IconButton } from '../components/Button.jsx'
import { useLabels } from '../components/labels.js'
const CloseIcon = () => (
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
@@ -13,10 +14,11 @@ const CloseIcon = () => (
/** The shared body of Dialog and Sheet: backdrop, panel, header with ×, body, footer. */
export function ModalFrame({
open, onClose, title, description, children, footer,
dismissible = true, closeLabel = 'Close', initialFocus,
dismissible = true, closeLabel, initialFocus,
overlayClass, panelClass, grip = false, bodyClass,
}) {
const panel = useRef(null)
const labels = useLabels()
const titleId = useId()
const descId = useId()
useModal(open, panel, { onClose, dismissible, initialFocus })
@@ -46,7 +48,7 @@ export function ModalFrame({
{description && <p id={descId} className="x-modal__description">{description}</p>}
</div>
{showClose && (
<IconButton label={closeLabel} size="sm" className="x-modal__close" onClick={onClose} data-x-autofocus-skip="">
<IconButton label={closeLabel ?? labels.close} size="sm" className="x-modal__close" onClick={onClose} data-x-autofocus-skip="">
<CloseIcon />
</IconButton>
)}
+2 -1
View File
@@ -17,6 +17,7 @@ npm test # server rediscovery scan
cd ..
npm test -w @xenia/ui # PIN rules + WCAG contrast of every token pair (light/dark × venue themes)
npm test -w @xenia/i18n # venue-time formatting (DST), money/numbers, comma-or-dot parsing, language order, check-i18n guard
```
**DB tests** (`local_backend/tests/conftest.py`) run the real FastAPI app against a throwaway SQLite database in a temp folder (never your dev or venue DB). Fixtures: `db` (session, rolled back after each test even if the code commits), `client` (TestClient with `get_db` overridden, license check open, no lifespan), `make_user(role=..., perms=...)` (password `password`, PIN `1234`), `login(user)` (auth headers). A test that uses any of them is marked `db` automatically.
@@ -36,7 +37,7 @@ Or run one suite at a time:
|---|---|---|---|
| `node install.mjs` | `install.sh`: VPN-safe `HOST_IP` detection (simulated WireGuard/WiFi hosts); fresh install, upgrade, re-run; proxy config identical to `nginx-proxy/nginx.conf` | Docker | ~1 min |
| `python license_e2e.py` | Offline licensing with a real cloud + site process: 400 days offline, tampered file, clock set back, expiry deferred to workday close, renewal, remote lock | Python deps of both backends | ~2 min |
| `node ui.mjs` | `@xenia/ui` components on the dev-only gallery (`/ui-gallery`, manager Vite :5185): dialog focus/Escape/backdrop, sheet, toasts, field wiring, switch, InfoTip, PinPad, themes | Edge | ~30 s |
| `node ui.mjs` | `@xenia/ui` components on the dev-only gallery (`/ui-gallery`, manager Vite :5185): dialog focus/Escape/backdrop, sheet, toasts, field wiring, switch, InfoTip, PinPad, themes; `@xenia/i18n` on `/i18n-sample` with the browser in New York: venue time, live language switch, el/en money and numbers, price input, translated component labels | Edge | ~40 s |
| `node browser.mjs` | Waiter web modes (same-origin, plain HTTP by LAN IP, venue mode), install dialog + drawer entry (Android / iPhone / desktop / no APK) | Docker, Edge | ~2 min |
| `node android.mjs basics` | Pairing, wrong address / other venue's QR, login + live WS, back button, restart, two venues, camera permission | Android emulator | ~5 min |
| `node android.mjs rediscovery` | Server IP change (logged in / out), server down + manual search, cold start while offline | Android emulator | ~4 min |
+2 -1
View File
@@ -9,10 +9,11 @@ const suites = [
['unit: local_backend (pytest)', PYTHON, ['-m', 'pytest', 'tests', '-q'], BACKEND],
['unit: waiter_pwa (node --test)', 'npm', ['test', '--silent'], WAITER],
['unit: packages/ui (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/ui'], CS],
['unit: packages/i18n (node --test + guard)', 'npm', ['test', '--silent', '-w', '@xenia/i18n'], CS],
['install.sh', 'node', ['install.mjs'], E2E],
['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E],
['browser', 'node', ['browser.mjs'], E2E],
['ui (@xenia/ui gallery)', 'node', ['ui.mjs'], E2E],
['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E],
]
if (!process.argv.includes('--no-android')) suites.push(['android (emulator)', 'node', ['android.mjs'], E2E])
+54 -5
View File
@@ -1,6 +1,9 @@
// @xenia/ui suite (Playwright + Edge): the shared components' behaviour on the
// gallery page (plan step 2.3). Starts the manager's Vite dev server (:5185), which
// serves /ui-gallery in dev builds only. No backend needed.
// Shared frontend packages (Playwright + Edge), on their dev-only pages served by the
// manager's Vite dev server (:5185). No backend needed.
// - @xenia/ui components on /ui-gallery (plan step 2.3)
// - @xenia/i18n on /i18n-sample (2.4): live language switch, venue time on a device
// in another zone (the browser runs in America/New_York), money/number formats,
// comma-or-dot price input, translated component labels
// node ui.mjs
import { spawn } from 'node:child_process'
import { openSync } from 'node:fs'
@@ -17,7 +20,8 @@ const vite = spawn('npx', ['vite', '--port', String(PORT), '--strictPort'], {
stdio: ['ignore', log, log],
})
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
const r = reporter('ui: @xenia/ui components (gallery)')
let r = reporter('ui: @xenia/ui components (gallery)')
let failures = 0
try {
await waitHttp(`http://localhost:${PORT}/`)
@@ -122,8 +126,53 @@ try {
r.check('theme: leaving the gallery restores <html>', await p.evaluate(() => !document.documentElement.hasAttribute('data-theme') && !document.documentElement.hasAttribute('data-venue-theme')))
r.check('no page or console errors', errs.length === 0, errs.slice(0, 3).join(' | '))
failures += r.done()
// ── @xenia/i18n ──────────────────────────────────────────────────────────
r = reporter('ui: @xenia/i18n (sample, device in New York)')
const ctx = await browser.newContext({ timezoneId: 'America/New_York', locale: 'en-US', viewport: { width: 1100, height: 1000 } })
const q = await ctx.newPage()
const qerrs = []
q.on('pageerror', e => qerrs.push('pageerror: ' + e.message))
q.on('console', m => { if (m.type() !== 'error' && m.type() !== 'warning') return; if (!/Failed to load resource/i.test(m.text())) qerrs.push(m.text().slice(0, 200)) })
const text = id => q.getByTestId(id).textContent()
await q.goto(`http://localhost:${PORT}/i18n-sample`)
await q.waitForSelector('[data-testid="title"]', { timeout: 60_000 })
r.check('device really is in New York', (await text('device-zone')) === 'America/New_York', await text('device-zone'))
r.check('venue zone = Athens (bootstrap default)', (await text('venue-zone')).startsWith('Europe/Athens'))
r.check('10:00 UTC in July shows 13:00 venue time (NY would be 06:00)', (await text('fixed-time')) === '01/07/2026, 13:00', await text('fixed-time'))
r.check('business date is not shifted', /Friday.*13.*November.*2026/.test(await text('business-date')), await text('business-date'))
r.check('en: money €1,234.50', (await text('money')) === '€1,234.50', await text('money'))
r.check('en: plural', (await text('plural')) === '3 items in the order')
r.check('en: relative time', (await text('relative')) === '5 minutes ago', await text('relative'))
await q.evaluate(() => { window.__noReload = true })
await q.getByLabel('Language').selectOption('el')
await q.waitForFunction(() => document.querySelector('[data-testid="title"]').textContent === 'Γλώσσες και μορφές', null, { timeout: 5000 }).catch(() => {})
r.check('switch to Ελληνικά: texts change live, no reload',
(await text('title')) === 'Γλώσσες και μορφές' && await q.evaluate(() => window.__noReload === true))
r.check('<html lang> follows', await q.evaluate(() => document.documentElement.lang) === 'el')
r.check('el: interpolation', (await text('greeting')) === 'Γεια σου, Maria!')
r.check('el: money 1.234,50 €', (await text('money')).replace(/[\u00a0\u202f]/g, ' ') === '1.234,50 €', await text('money'))
r.check('el: number 1.234,57', (await text('number')) === '1.234,57')
r.check('el: relative time', (await text('relative')) === 'πριν από 5 λεπτά', await text('relative'))
r.check('el: same venue time', (await text('fixed-time')) === '01/07/2026, 13:00')
const input = q.getByTestId('price-input')
for (const [typed, want] of [['3,50', '3,50 €'], ['3.50', '3,50 €'], ['1.234,5', '1.234,50 €'], ['abc', 'δεν είναι αριθμός']]) {
await input.fill(typed)
const hint = (await q.locator('.x-field__hint').textContent()).replace(/[\u00a0\u202f]/g, ' ')
r.check(`price input "${typed}" → ${want}`, hint.endsWith(want), hint)
}
await q.getByRole('button', { name: 'Άνοιγμα παραθύρου' }).click()
r.check('ui labels translated (dialog ×, (i), spinner)',
await q.getByRole('dialog').getByRole('button', { name: 'Κλείσιμο' }).count() === 1
&& await q.getByRole('button', { name: 'Περισσότερες πληροφορίες' }).count() === 1
&& (await q.locator('.x-spinner .x-visually-hidden').textContent()) === 'Φόρτωση')
await q.screenshot({ path: path.join(OUT, 'i18n-sample-el.png'), fullPage: true })
r.check('no page errors or missing-key warnings', qerrs.length === 0, qerrs.slice(0, 3).join(' | '))
failures += r.done()
await ctx.close()
} finally {
await browser.close()
killTree(vite)
}
process.exit(r.done() ? 1 : 0)
process.exit(failures ? 1 : 0)