@ooopenlab/quiz-shared
Version:
Shared utilities and components for SuperQuiz modules
52 lines (43 loc) • 1.29 kB
text/typescript
// i18n support for quiz libs
export interface I18nConfig {
locale: string;
messages: Record<string, any>;
}
export interface TranslationFunction {
(key: string, variables?: Record<string, any>): string;
}
// Simple translation function that can work with next-intl messages
export function createTranslator(config: I18nConfig): TranslationFunction {
return (key: string, variables?: Record<string, any>) => {
const keys = key.split('.');
let value: any = config.messages;
for (const k of keys) {
if (value && typeof value === 'object' && k in value) {
value = value[k];
} else {
// Return key if translation not found
return key;
}
}
if (typeof value !== 'string') {
return key;
}
// Simple variable replacement
if (variables) {
return value.replace(/\{(\w+)\}/g, (match: string, varName: string) => {
return variables[varName] || match;
});
}
return value;
};
}
// Context for providing i18n to modules
export interface ModuleI18nContext {
locale: string;
t: TranslationFunction;
}
// Default context (fallback)
export const defaultI18nContext: ModuleI18nContext = {
locale: 'zh',
t: (key: string) => key
};