wuchale
Version:
Protobuf-like i18n from plain code
61 lines (60 loc) • 1.93 kB
JavaScript
import toRuntime, {} from '../runtime.js';
export function defaultCollection(store) {
return {
get: loadID => store[loadID],
set: (loadID, rt) => {
store[loadID] = rt;
}
};
}
/** Global catalog states registry */
const states = {};
const emptyRuntime = toRuntime();
/**
* - `key` is a unique identifier for the group
* - `loadIDs` and `load` MUST be imported from the loader virtual modules or proxies.
*/
export function registerLoaders(key, load, loadIDs, collection) {
states[key] = { load, loadIDs, collection: collection ?? defaultCollection({}) };
for (const id of loadIDs) {
states[key].collection.set(id, emptyRuntime);
}
return loadID => states[key].collection.get(loadID);
}
function statesToLoad(key) {
if (key) {
return [states[key]];
}
return Object.values(states);
}
/**
* Loads catalogs using registered async loaders.
* Can be called anywhere you want to set the locale.
*/
export async function loadLocale(locale, key) {
const promises = [];
const statesArr = [];
for (const state of statesToLoad(key)) {
for (const loadID of state.loadIDs) {
promises.push(state.load(loadID, locale));
statesArr.push([loadID, state]);
}
}
for (const [i, loaded] of (await Promise.all(promises)).entries()) {
const [loadID, state] = statesArr[i];
state.collection.set(loadID, toRuntime(loaded, locale));
}
}
/**
* Loads catalogs using registered sync loaders.
* Can be called anywhere you want to set the locale.
* The loadCatalog function should be from a sync proxy.
*/
export function loadLocaleSync(locale, key) {
for (const state of statesToLoad(key)) {
for (const loadID of state.loadIDs) {
const loaded = state.load(loadID, locale);
state.collection.set(loadID, toRuntime(loaded, locale));
}
}
}