Files
website/node_modules/@astrojs/starlight/utils/translations.ts
2024-05-06 17:15:30 -04:00

36 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { getCollection, type CollectionEntry, type DataCollectionKey } from 'astro:content';
import config from 'virtual:starlight/user-config';
import type { i18nSchemaOutput } from '../schemas/i18n';
import { createTranslationSystem } from './createTranslationSystem';
type UserI18nSchema = 'i18n' extends DataCollectionKey
? CollectionEntry<'i18n'>['data']
: i18nSchemaOutput;
/** Get all translation data from the i18n collection, keyed by `id`, which matches locale. */
async function loadTranslations() {
let userTranslations: Record<string, UserI18nSchema> = {};
// Briefly override `console.warn()` to silence logging when a project has no i18n collection.
const warn = console.warn;
console.warn = () => {};
try {
// Load the users i18n collection and ignore the error if it doesnt exist.
userTranslations = Object.fromEntries(
// @ts-ignore — may be an error in projects without an i18n collection
(await getCollection('i18n')).map(({ id, data }) => [id, data] as const)
);
} catch {}
// Restore the original warn implementation.
console.warn = warn;
return userTranslations;
}
/**
* Generate a utility function that returns UI strings for the given `locale`.
* @param {string | undefined} [locale]
* @example
* const t = useTranslations('en');
* const label = t('search.label'); // => 'Search'
*/
export const useTranslations = createTranslationSystem(await loadTranslations(), config);