24 lines
847 B
TypeScript
24 lines
847 B
TypeScript
type Messages = Record<string, Record<string, string>>
|
|
|
|
export function createI18n({ defaultLocale, messages }: { defaultLocale: string; messages: Messages }) {
|
|
function format(template: string, params?: Record<string, string | number>) {
|
|
if (!params) return template
|
|
return template.replace(/\{(\w+)\}/g, (_, k) => (params[k] !== undefined ? String(params[k]) : `{${k}}`))
|
|
}
|
|
|
|
function getMessage(locale: string, key: string): string | undefined {
|
|
const m = messages[locale] || {}
|
|
if (m[key] !== undefined) return m[key]
|
|
const base = messages[defaultLocale] || {}
|
|
return base[key]
|
|
}
|
|
|
|
function t(locale: string, key: string, params?: Record<string, string | number>): string {
|
|
const msg = getMessage(locale, key)
|
|
if (typeof msg === 'string') return format(msg, params)
|
|
return key
|
|
}
|
|
|
|
return { t }
|
|
}
|