createStringsResource: support merged imports

This commit is contained in:
thislight 2024-09-26 19:36:46 +08:00
parent b4fa751345
commit c49ae6fe0a
No known key found for this signature in database
GPG key ID: A50F9451AC56A63E
6 changed files with 58 additions and 32 deletions

View file

@ -35,7 +35,7 @@ export function autoMatchLangTag() {
return match(Array.from(navigator.languages), SUPPORTED_LANGS, DEFAULT_LANG);
}
const DateFnLocaleCx = createContext<Accessor<Locale>>(() => enGB);
const DateFnLocaleCx = /* __@PURE__ */createContext<Accessor<Locale>>(() => enGB);
const cachedDateFnLocale: Record<string, Locale> = {
enGB,
@ -149,11 +149,20 @@ export function useLanguage() {
return () => settings().language || autoMatchLangTag();
}
type ImportFn<T> = (name: string) => Promise<{default: T}>
type ImportedModule<F> = F extends ImportFn<infer T> ? T: never
type MergedImportedModule<T> =
T extends [] ? {} :
T extends [infer I] ? ImportedModule<I> :
T extends [infer I, ...infer J] ? ImportedModule<I> & MergedImportedModule<J> : never
export function createStringResource<
M extends Record<string, string | Template<any>>,
>(importFn: (code: string) => Promise<{ default: M }>) {
T extends ImportFn<Record<string, string | Template<any> | undefined>>[],
>(...importFns: T) {
const language = useLanguage();
const cache: Record<string, M | undefined> = {};
const cache: Record<string, MergedImportedModule<T>> = {};
return createResource(
() => [language()] as const,
@ -162,9 +171,13 @@ export function createStringResource<
return cache[nlang];
}
const { default: dict } = await importFn(`${nlang}`);
const results = await Promise.all(importFns.map(x => x(nlang).then(v => v.default)))
return dict;
const merged: MergedImportedModule<T> = Object.assign({}, ...results)
cache[nlang] = merged;
return merged;
},
);
}