You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
1.8 KiB
78 lines
1.8 KiB
import { createLang, type LangNode, type SupportedLocale, type LangInstance } from './lib';
|
|
|
|
export type { LangNode, SupportedLocale, LangInstance };
|
|
|
|
/**
|
|
* Reactive wrapper around lang for Svelte 5.
|
|
*
|
|
* Mirrors the lang instance but overrides `getLocale` and `t` to touch
|
|
* a `$state` variable, so any `$derived` / `$effect` that calls them
|
|
* re-evaluates when the locale changes.
|
|
*/
|
|
export function createLangs<S extends LangNode>(
|
|
schema: S,
|
|
defaultLocale?: SupportedLocale,
|
|
fallbackChain?: SupportedLocale[]
|
|
) {
|
|
const lang = createLang(schema, defaultLocale, fallbackChain);
|
|
|
|
let _locale = $state<SupportedLocale>(lang.getLocale());
|
|
let _schemaVersion = $state(0);
|
|
|
|
lang.onLocaleChange((locale) => {
|
|
_locale = locale;
|
|
});
|
|
|
|
lang.onSchemaChange(() => {
|
|
_schemaVersion++;
|
|
});
|
|
|
|
return {
|
|
t(path: string, params?: Record<string, any>, locale?: SupportedLocale): string {
|
|
void _locale;
|
|
void _schemaVersion;
|
|
return lang.t(path, params, locale);
|
|
},
|
|
|
|
ts(value: any, locale?: SupportedLocale): string {
|
|
void _locale;
|
|
void _schemaVersion;
|
|
return lang.ts(value, locale);
|
|
},
|
|
|
|
getLocale(): SupportedLocale {
|
|
return _locale;
|
|
},
|
|
|
|
setLocale(locale: SupportedLocale): void {
|
|
lang.setLocale(locale);
|
|
},
|
|
|
|
extend(namespace: string, module: LangNode): void {
|
|
lang.extend(namespace, module);
|
|
},
|
|
|
|
register<NS extends string, M extends LangNode>(namespace: NS, module: M) {
|
|
return lang.register(namespace, module);
|
|
},
|
|
|
|
onLocaleChange(fn: (locale: SupportedLocale) => void): () => void {
|
|
return lang.onLocaleChange(fn);
|
|
},
|
|
|
|
onSchemaChange(fn: () => void): () => void {
|
|
return lang.onSchemaChange(fn);
|
|
},
|
|
|
|
setLogger(logger: any): void {
|
|
lang.setLogger(logger);
|
|
},
|
|
|
|
dispose(): void {
|
|
lang.dispose();
|
|
},
|
|
|
|
__dispose: lang.__dispose
|
|
} as unknown as LangInstance<S>;
|
|
}
|