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,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 },
|
||||
}
|
||||
Reference in New Issue
Block a user