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:
@@ -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}} ψηφία"
|
||||
}
|
||||
}
|
||||
@@ -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) χρησιμοποιούν τις μεταφρασμένες ετικέτες."
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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>
|
||||
}
|
||||
@@ -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 },
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
@@ -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)
|
||||
})
|
||||
Reference in New Issue
Block a user