|
| 1 | +import React from 'react' |
| 2 | + |
| 3 | +type TranslationDictionary = Record<string, unknown> |
| 4 | +type Replacements = Record<string, string | number | React.ReactNode> |
| 5 | + |
| 6 | +interface I18nTranslator { |
| 7 | + translate(key: string, replacements?: Replacements): React.ReactNode |
| 8 | +} |
| 9 | + |
| 10 | +function getNestedValue(obj: TranslationDictionary, key: string): string | undefined { |
| 11 | + const result = key.split('.').reduce<unknown>((current, segment) => { |
| 12 | + if (current != null && typeof current === 'object') { |
| 13 | + return (current as TranslationDictionary)[segment] |
| 14 | + } |
| 15 | + return undefined |
| 16 | + }, obj) |
| 17 | + return typeof result === 'string' ? result : undefined |
| 18 | +} |
| 19 | + |
| 20 | +function interpolate(template: string, replacements?: Replacements): React.ReactNode { |
| 21 | + if (!replacements) return template |
| 22 | + |
| 23 | + const hasReactNodes = Object.values(replacements).some((value) => React.isValidElement(value)) |
| 24 | + |
| 25 | + if (!hasReactNodes) { |
| 26 | + return template.replace(/\{(\w+)\}/g, (match, key: string) => |
| 27 | + key in replacements ? String(replacements[key]) : match, |
| 28 | + ) |
| 29 | + } |
| 30 | + |
| 31 | + const parts: React.ReactNode[] = [] |
| 32 | + const regex = /\{(\w+)\}/g |
| 33 | + let lastIndex = 0 |
| 34 | + let match: RegExpExecArray | null |
| 35 | + |
| 36 | + while ((match = regex.exec(template)) !== null) { |
| 37 | + if (match.index > lastIndex) { |
| 38 | + parts.push(template.slice(lastIndex, match.index)) |
| 39 | + } |
| 40 | + const key = match[1] |
| 41 | + parts.push(key in replacements ? replacements[key] : match[0]) |
| 42 | + lastIndex = regex.lastIndex |
| 43 | + } |
| 44 | + |
| 45 | + if (lastIndex < template.length) { |
| 46 | + parts.push(template.slice(lastIndex)) |
| 47 | + } |
| 48 | + |
| 49 | + return React.createElement(React.Fragment, null, ...parts) |
| 50 | +} |
| 51 | + |
| 52 | +export function useI18n({fallback}: {id: string; fallback: TranslationDictionary}): [I18nTranslator] { |
| 53 | + return [ |
| 54 | + { |
| 55 | + translate(key: string, replacements?: Replacements) { |
| 56 | + const template = getNestedValue(fallback, key) |
| 57 | + if (template == null) return key |
| 58 | + return interpolate(template, replacements) |
| 59 | + }, |
| 60 | + }, |
| 61 | + ] |
| 62 | +} |
0 commit comments