Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v2): Add i18n default code translation bundles #4215

Merged
merged 2 commits into from
Feb 12, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/docusaurus-theme-classic/codeTranslations/fr.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"theme.NotFound.title": "Page introuvable",
"theme.NotFound.p1": "Nous n'avons pas trouvé ce que vous recherchez.",
"theme.NotFound.p2": "Veuillez contacter le propriétaire du site qui vous a lié à l'URL d'origine et leur faire savoir que leur lien est cassé.",
"theme.BlogListPaginator.newerEntries": "Nouvelles entrées",
"theme.BlogListPaginator.olderEntries": "Anciennes entrées",
"theme.BlogPostItem.readMore": "Lire plus",
"theme.BlogPostPaginator.newerPost": "Article plus récent",
"theme.BlogPostPaginator.olderPost": "Article plus ancien",
"theme.CodeBlock.copied": "Copié",
"theme.CodeBlock.copy": "Copier",
"theme.DocPaginator.previous": "Précédent",
"theme.DocPaginator.next": "Suivant",
"theme.EditThisPage.editThisPage": "Éditer cette page",
"theme.SkipToContent.skipToMainContent": "Aller au contenu principal",
"theme.Playground.liveEditor": "Éditeur en direct",
"theme.Playground.result": "Résultat"
}
8 changes: 8 additions & 0 deletions packages/docusaurus-theme-classic/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import path from 'path';
import Module from 'module';
import postcss from 'postcss';
import rtlcss from 'rtlcss';
import {readDefaultCodeTranslationMessages} from '@docusaurus/utils';

const createRequire = Module.createRequire || Module.createRequireFromPath;
const requireFromDocusaurusCore = createRequire(
Expand Down Expand Up @@ -103,6 +104,13 @@ export default function docusaurusThemeClassic(
getTranslationFiles: async () => getTranslationFiles({themeConfig}),
translateThemeConfig,

getDefaultCodeTranslationMessages: () => {
return readDefaultCodeTranslationMessages({
dirPath: path.resolve(__dirname, '..', 'codeTranslations'),
locale: currentLocale,
});
},

getClientModules() {
const modules = [
require.resolve(getInfimaCSSFile(direction)),
Expand Down
6 changes: 6 additions & 0 deletions packages/docusaurus-types/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,12 @@ export interface Plugin<T, U = unknown> {

// translations
getTranslationFiles?(): Promise<TranslationFiles>;
getDefaultCodeTranslationMessages?(): Promise<
Record<
string, // id
string // message
>
>;
translateContent?({
content,
translationFiles,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"id1": "message 1 en",
"id2": "message 2 en"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"id1": "message 1 fr",
"id2": "message 2 fr"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"id1": "message 1 fr_FR",
"id2": "message 2 fr_FR",
"id3": "message 3 fr_FR"
}
88 changes: 88 additions & 0 deletions packages/docusaurus-utils/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import path from 'path';
import fs from 'fs-extra';
import {
fileToPath,
simpleHash,
Expand Down Expand Up @@ -33,6 +34,7 @@ import {
findFolderContainingFile,
getFolderContainingFile,
updateTranslationFileMessages,
readDefaultCodeTranslationMessages,
} from '../index';
import {sum} from 'lodash';

Expand Down Expand Up @@ -718,3 +720,89 @@ describe('updateTranslationFileMessages', () => {
});
});
});

describe('readDefaultCodeTranslationMessages', () => {
const dirPath = path.resolve(
__dirname,
'__fixtures__',
'defaultCodeTranslations',
);

async function readAsJSON(filename: string) {
return JSON.parse(
await fs.readFile(path.resolve(dirPath, filename), 'utf8'),
);
}

test('for empty locale', async () => {
await expect(
readDefaultCodeTranslationMessages({
locale: '',
dirPath,
}),
).resolves.toEqual({});
});

test('for unexisting locale', async () => {
await expect(
readDefaultCodeTranslationMessages({
locale: 'es',
dirPath,
}),
).resolves.toEqual({});
});

test('for fr but bad folder', async () => {
await expect(
readDefaultCodeTranslationMessages({
locale: '',
dirPath: __dirname,
}),
).resolves.toEqual({});
});

test('for fr', async () => {
await expect(
readDefaultCodeTranslationMessages({
locale: 'fr',
dirPath,
}),
).resolves.toEqual(await readAsJSON('fr.json'));
});

test('for fr_FR', async () => {
await expect(
readDefaultCodeTranslationMessages({
locale: 'fr_FR',
dirPath,
}),
).resolves.toEqual(await readAsJSON('fr_FR.json'));
});

test('for en', async () => {
await expect(
readDefaultCodeTranslationMessages({
locale: 'en',
dirPath,
}),
).resolves.toEqual(await readAsJSON('en.json'));
});

test('for en_US', async () => {
await expect(
readDefaultCodeTranslationMessages({
locale: 'en_US',
dirPath,
}),
).resolves.toEqual(await readAsJSON('en.json'));
});

test('for en_WHATEVER', async () => {
await expect(
readDefaultCodeTranslationMessages({
locale: 'en_WHATEVER',
dirPath,
}),
).resolves.toEqual(await readAsJSON('en.json'));
});
});
32 changes: 32 additions & 0 deletions packages/docusaurus-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -602,3 +602,35 @@ export function updateTranslationFileMessages(
})),
};
}

export async function readDefaultCodeTranslationMessages({
dirPath,
locale,
}: {
dirPath: string;
locale: string;
}): Promise<Record<string, string>> {
const fileNamesToTry = [locale];

if (locale.includes('_')) {
const language = locale.split('_')[0];
if (language) {
fileNamesToTry.push(language);
}
}

// Return the content of the first file that match
// fr_FR.json => fr.json => nothing
for (const fileName of fileNamesToTry) {
const filePath = path.resolve(dirPath, `${fileName}.json`);

// eslint-disable-next-line no-await-in-loop
if (await fs.pathExists(filePath)) {
// eslint-disable-next-line no-await-in-loop
const fileContent = await fs.readFile(filePath, 'utf8');
return JSON.parse(fileContent);
}
}

return {};
}
15 changes: 13 additions & 2 deletions packages/docusaurus/src/commands/writeTranslations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
writePluginTranslations,
writeCodeTranslations,
WriteTranslationsOptions,
getPluginsDefaultCodeTranslationMessages,
applyDefaultCodeTranslations,
} from '../server/translations/translations';
import {extractPluginsSourceCodeTranslations} from '../server/translations/translationsExtractor';
import {getCustomBabelConfigFilePath, getBabelOptions} from '../webpack/utils';
Expand Down Expand Up @@ -47,7 +49,7 @@ export default async function writeTranslations(
siteDir: string,
options: WriteTranslationsOptions & {locale?: string},
): Promise<void> {
const context = await loadContext(siteDir);
const context = await loadContext(siteDir, {locale: options.locale});
const pluginConfigs = loadPluginConfigs(context);
const plugins = initPlugins({
pluginConfigs,
Expand All @@ -68,10 +70,19 @@ Available locales=[${context.i18n.locales.join(',')}]`,
isServer: true,
babelOptions: getCustomBabelConfigFilePath(siteDir),
});
const codeTranslations = await extractPluginsSourceCodeTranslations(
const extractedCodeTranslations = await extractPluginsSourceCodeTranslations(
plugins,
babelOptions,
);
const defaultCodeMessages = await getPluginsDefaultCodeTranslationMessages(
plugins,
);

const codeTranslations = applyDefaultCodeTranslations({
extractedCodeTranslations,
defaultCodeMessages,
});

await writeCodeTranslations({siteDir, locale}, codeTranslations, options);

await Promise.all(
Expand Down
12 changes: 10 additions & 2 deletions packages/docusaurus/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ import {loadHtmlTags} from './html-tags';
import {getPackageJsonVersion} from './versions';
import {handleDuplicateRoutes} from './duplicateRoutes';
import {loadI18n, localizePath} from './i18n';
import {readCodeTranslationFileContent} from './translations/translations';
import {
readCodeTranslationFileContent,
getPluginsDefaultCodeTranslationMessages,
} from './translations/translations';
import {mapValues} from 'lodash';

type LoadContextOptions = {
Expand Down Expand Up @@ -267,10 +270,15 @@ ${Object.keys(registry)
JSON.stringify(i18n, null, 2),
);

const codeTranslationsWithFallbacks: Record<string, string> = {
...(await getPluginsDefaultCodeTranslationMessages(plugins)),
...codeTranslations,
};

const genCodeTranslations = generate(
generatedFilesDir,
'codeTranslations.json',
JSON.stringify(codeTranslations, null, 2),
JSON.stringify(codeTranslationsWithFallbacks, null, 2),
);

// Version metadata.
Expand Down
Loading