|
1 | 1 | import { getCollection, type CollectionEntry, type DataCollectionKey } from 'astro:content';
|
2 | 2 | import config from 'virtual:starlight/user-config';
|
| 3 | +import project from 'virtual:starlight/project-context'; |
3 | 4 | import pluginTranslations from 'virtual:starlight/plugin-translations';
|
4 | 5 | import type { i18nSchemaOutput } from '../schemas/i18n';
|
5 | 6 | import { createTranslationSystem } from './createTranslationSystem';
|
6 | 7 | import type { RemoveIndexSignature } from './types';
|
| 8 | +import { getCollectionPathFromRoot } from './collection'; |
| 9 | +import { stripExtension, stripLeadingSlash } from './path'; |
7 | 10 |
|
8 | 11 | // @ts-ignore - This may be a type error in projects without an i18n collection and running
|
9 | 12 | // `tsc --noEmit` in their project. Note that it is not possible to inline this type in
|
10 | 13 | // `UserI18nSchema` because this would break types for users having multiple data collections.
|
11 | 14 | type i18nCollection = CollectionEntry<'i18n'>;
|
12 | 15 |
|
| 16 | +const i18nCollectionPathFromRoot = getCollectionPathFromRoot('i18n', project); |
| 17 | + |
13 | 18 | export type UserI18nSchema = 'i18n' extends DataCollectionKey
|
14 | 19 | ? i18nCollection extends { data: infer T }
|
15 | 20 | ? i18nSchemaOutput & T
|
16 | 21 | : i18nSchemaOutput
|
17 | 22 | : i18nSchemaOutput;
|
18 | 23 | export type UserI18nKeys = keyof RemoveIndexSignature<UserI18nSchema>;
|
19 | 24 |
|
20 |
| -/** Get all translation data from the i18n collection, keyed by `id`, which matches locale. */ |
| 25 | +/** Get all translation data from the i18n collection, keyed by `lang`, which are BCP-47 language tags. */ |
21 | 26 | async function loadTranslations() {
|
22 | 27 | // Briefly override `console.warn()` to silence logging when a project has no i18n collection.
|
23 | 28 | const warn = console.warn;
|
24 | 29 | console.warn = () => {};
|
25 | 30 | const userTranslations: Record<string, UserI18nSchema> = Object.fromEntries(
|
26 | 31 | // @ts-ignore — may be a type error in projects without an i18n collection
|
27 |
| - (await getCollection('i18n')).map(({ id, data }) => [id, data] as const) |
| 32 | + (await getCollection('i18n')).map(({ id, data, filePath }) => { |
| 33 | + const lang = |
| 34 | + project.legacyCollections || !filePath |
| 35 | + ? id |
| 36 | + : stripExtension(stripLeadingSlash(filePath.replace(i18nCollectionPathFromRoot, ''))); |
| 37 | + return [lang, data] as const; |
| 38 | + }) |
28 | 39 | );
|
29 | 40 | // Restore the original warn implementation.
|
30 | 41 | console.warn = warn;
|
|
0 commit comments