diff --git a/docs/README.md b/docs/README.md index ac425f5..d901817 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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//.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 ``. 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/.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 `` 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 `, 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`). diff --git a/manager_dashboard/package.json b/manager_dashboard/package.json index 71279e4..a49b74e 100644 --- a/manager_dashboard/package.json +++ b/manager_dashboard/package.json @@ -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", diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index 43d721f..5a35dbc 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -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() { } /> {UiGallery && } />} + {I18nSample && } />} } /> } /> diff --git a/package-lock.json b/package-lock.json index 88a7893..9a84ad5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/packages/i18n/locales/el/common.json b/packages/i18n/locales/el/common.json new file mode 100644 index 0000000..abef203 --- /dev/null +++ b/packages/i18n/locales/el/common.json @@ -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}} ψηφία" + } +} diff --git a/packages/i18n/locales/el/dev.json b/packages/i18n/locales/el/dev.json new file mode 100644 index 0000000..0273af8 --- /dev/null +++ b/packages/i18n/locales/el/dev.json @@ -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) χρησιμοποιούν τις μεταφρασμένες ετικέτες." + } +} diff --git a/packages/i18n/locales/en/common.json b/packages/i18n/locales/en/common.json new file mode 100644 index 0000000..82a1837 --- /dev/null +++ b/packages/i18n/locales/en/common.json @@ -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" + } +} diff --git a/packages/i18n/locales/en/dev.json b/packages/i18n/locales/en/dev.json new file mode 100644 index 0000000..ded0ce2 --- /dev/null +++ b/packages/i18n/locales/en/dev.json @@ -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." + } +} diff --git a/packages/i18n/package.json b/packages/i18n/package.json index 2af0c72..5813acc 100644 --- a/packages/i18n/package.json +++ b/packages/i18n/package.json @@ -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" } } diff --git a/packages/i18n/sample/Sample.jsx b/packages/i18n/sample/Sample.jsx new file mode 100644 index 0000000..d03f020 --- /dev/null +++ b/packages/i18n/sample/Sample.jsx @@ -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
{label}{children}
+} + +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 ( +
+
+
+

{t('sample.title')}

+ setTyped(e.target.value)} inputMode="decimal" data-testid="price-input" /> + +
+ + {t('sample.dialogBody')} + +
+ setOpen(false)} title={t('sample.dialogTitle')} + footer={}> + {t('sample.dialogBody')} + +
+
+ ) +} + +function Labels({ children }) { + return {children} +} + +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 ( + + + + ) +} diff --git a/packages/i18n/scripts/check-i18n.mjs b/packages/i18n/scripts/check-i18n.mjs new file mode 100644 index 0000000..478623c --- /dev/null +++ b/packages/i18n/scripts/check-i18n.mjs @@ -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) diff --git a/packages/i18n/src/context.js b/packages/i18n/src/context.js new file mode 100644 index 0000000..a8c1a76 --- /dev/null +++ b/packages/i18n/src/context.js @@ -0,0 +1,4 @@ +import { createContext } from 'react' + +/** The venue formatters for the current language (filled by , read by useFormat()). */ +export const FormatContext = createContext(null) diff --git a/packages/i18n/src/format.js b/packages/i18n/src/format.js new file mode 100644 index 0000000..6efd642 --- /dev/null +++ b/packages/i18n/src/format.js @@ -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, + } +} diff --git a/packages/i18n/src/hooks.js b/packages/i18n/src/hooks.js new file mode 100644 index 0000000..5b434d7 --- /dev/null +++ b/packages/i18n/src/hooks.js @@ -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 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: + * + */ +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 +} diff --git a/packages/i18n/src/i18n.js b/packages/i18n/src/i18n.js new file mode 100644 index 0000000..58f30a8 --- /dev/null +++ b/packages/i18n/src/i18n.js @@ -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' }) }) + * … + * + * 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 +} diff --git a/packages/i18n/src/index.js b/packages/i18n/src/index.js index 9d91682..d541069 100644 --- a/packages/i18n/src/index.js +++ b/packages/i18n/src/index.js @@ -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 }) }) +// +// … (@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' diff --git a/packages/i18n/src/language.js b/packages/i18n/src/language.js new file mode 100644 index 0000000..9c58551 --- /dev/null +++ b/packages/i18n/src/language.js @@ -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 +} diff --git a/packages/i18n/src/locale.js b/packages/i18n/src/locale.js new file mode 100644 index 0000000..aef555e --- /dev/null +++ b/packages/i18n/src/locale.js @@ -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 +} diff --git a/packages/i18n/src/number.js b/packages/i18n/src/number.js new file mode 100644 index 0000000..5fe79b9 --- /dev/null +++ b/packages/i18n/src/number.js @@ -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 +} diff --git a/packages/i18n/src/provider.jsx b/packages/i18n/src/provider.jsx new file mode 100644 index 0000000..26e79d4 --- /dev/null +++ b/packages/i18n/src/provider.jsx @@ -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 ( + + {children} + + ) +} + +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 {children} +} diff --git a/packages/i18n/src/resources.js b/packages/i18n/src/resources.js new file mode 100644 index 0000000..671b135 --- /dev/null +++ b/packages/i18n/src/resources.js @@ -0,0 +1,15 @@ +// Every locale file, bundled (they're small; no loading step, no flash of keys). +// Layout (APPS_PLATFORM §8): locales//.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 }, +} diff --git a/packages/i18n/tests/check.test.mjs b/packages/i18n/tests/check.test.mjs new file mode 100644 index 0000000..fb3b54a --- /dev/null +++ b/packages/i18n/tests/check.test.mjs @@ -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 }) + } +}) diff --git a/packages/i18n/tests/format.test.mjs b/packages/i18n/tests/format.test.mjs new file mode 100644 index 0000000..088fde2 --- /dev/null +++ b/packages/i18n/tests/format.test.mjs @@ -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') +}) diff --git a/packages/i18n/tests/language.test.mjs b/packages/i18n/tests/language.test.mjs new file mode 100644 index 0000000..53c7164 --- /dev/null +++ b/packages/i18n/tests/language.test.mjs @@ -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') +}) diff --git a/packages/i18n/tests/locale.test.mjs b/packages/i18n/tests/locale.test.mjs new file mode 100644 index 0000000..1e24754 --- /dev/null +++ b/packages/i18n/tests/locale.test.mjs @@ -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') +}) diff --git a/packages/i18n/tests/number.test.mjs b/packages/i18n/tests/number.test.mjs new file mode 100644 index 0000000..c2b50b5 --- /dev/null +++ b/packages/i18n/tests/number.test.mjs @@ -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) +}) diff --git a/packages/ui/gallery/Gallery.jsx b/packages/ui/gallery/Gallery.jsx index 8c411a2..d0fea5e 100644 --- a/packages/ui/gallery/Gallery.jsx +++ b/packages/ui/gallery/Gallery.jsx @@ -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)) diff --git a/packages/ui/src/components/Dialog.jsx b/packages/ui/src/components/Dialog.jsx index 88c8aa2..8625959 100644 --- a/packages/ui/src/components/Dialog.jsx +++ b/packages/ui/src/components/Dialog.jsx @@ -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 }) { diff --git a/packages/ui/src/components/InfoTip.jsx b/packages/ui/src/components/InfoTip.jsx index 4a66fd2..e3e513c 100644 --- a/packages/ui/src/components/InfoTip.jsx +++ b/packages/ui/src/components/InfoTip.jsx @@ -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: 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)} diff --git a/packages/ui/src/components/PinPad.jsx b/packages/ui/src/components/PinPad.jsx index 041e65f..fbedaa6 100644 --- a/packages/ui/src/components/PinPad.jsx +++ b/packages/ui/src/components/PinPad.jsx @@ -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({ ))}
-
{progressLabel(value.length, length)}
+
{progress(value.length, length)}
{busy ? : error ? {error} : null}
@@ -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' ? ( diff --git a/packages/ui/src/components/Spinner.jsx b/packages/ui/src/components/Spinner.jsx index b38fcfb..f1a2df5 100644 --- a/packages/ui/src/components/Spinner.jsx +++ b/packages/ui/src/components/Spinner.jsx @@ -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 ( - {label && {label}} + {text && {text}} ) } diff --git a/packages/ui/src/components/Toast.jsx b/packages/ui/src/components/Toast.jsx index b291f2f..8a8c396 100644 --- a/packages/ui/src/components/Toast.jsx +++ b/packages/ui/src/components/Toast.jsx @@ -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 {children} -
- {toasts.map(t => )} +
+ {toasts.map(t => )}
diff --git a/packages/ui/src/components/labels.js b/packages/ui/src/components/labels.js new file mode 100644 index 0000000..19122ac --- /dev/null +++ b/packages/ui/src/components/labels.js @@ -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: +// (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) +} diff --git a/packages/ui/src/index.js b/packages/ui/src/index.js index 699aeff..0a65ddc 100644 --- a/packages/ui/src/index.js +++ b/packages/ui/src/index.js @@ -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 (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' diff --git a/packages/ui/src/internal/ModalFrame.jsx b/packages/ui/src/internal/ModalFrame.jsx index e5ca840..4a9995e 100644 --- a/packages/ui/src/internal/ModalFrame.jsx +++ b/packages/ui/src/internal/ModalFrame.jsx @@ -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 = () => (

{description}

}
{showClose && ( - + )} diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 1cc52d2..56638a5 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -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 | diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs index a9deceb..d36f590 100644 --- a/tests/e2e/run-all.mjs +++ b/tests/e2e/run-all.mjs @@ -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]) diff --git a/tests/e2e/ui.mjs b/tests/e2e/ui.mjs index 968da33..a1b1a50 100644 --- a/tests/e2e/ui.mjs +++ b/tests/e2e/ui.mjs @@ -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 ', 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(' 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)