Skip to content

Commit

Permalink
🔧 chore: Update i18n
Browse files Browse the repository at this point in the history
  • Loading branch information
canisminor1990 authored and arvinxx committed Sep 11, 2023
1 parent 1d465d6 commit 3c0117e
Show file tree
Hide file tree
Showing 32 changed files with 253 additions and 311 deletions.
3 changes: 2 additions & 1 deletion locales/en_US/market.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"search": {
"placeholder": "Search assistant..."
}
},
"submitAgent": "Submit Assistant"
}
10 changes: 9 additions & 1 deletion locales/en_US/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,5 +114,13 @@
"title": "Weather Data for the Next 7 Days ({{city}})",
"updateAt": "Last Updated"
},
"responseData": "Response Data"
"responseData": "Response Data",
"settings": {
"indexUrl": {
"title": "Marketplace Index",
"tooltip": "Editing is not supported at the moment"
},
"modalDesc": "After configuring the address of the plugin marketplace, you can use a custom plugin marketplace",
"title": "Configure Plugin Marketplace"
}
}
3 changes: 2 additions & 1 deletion locales/en_US/setting.json
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@
"add": "Add",
"addTooltip": "Add custom plugin",
"config": "{{id}} Plugin Configuration",
"clearDeprecated": "Remove invalid plugins"
"clearDeprecated": "Remove invalid plugins",
"settings": "Plugin Market Settings"
},
"settingSystem": {
"accessCode": {
Expand Down
3 changes: 2 additions & 1 deletion locales/ru_RU/market.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"search": {
"placeholder": "Поиск помощника..."
}
},
"submitAgent": "Отправить агента"
}
107 changes: 106 additions & 1 deletion locales/ru_RU/plugin.json
Original file line number Diff line number Diff line change
@@ -1 +1,106 @@
{}
{
"debug": {
"arguments": "Аргументы вызова",
"function_call": "Вызов функции",
"response": "Ответ"
},
"dev": {
"confirmDeleteDevPlugin": "Вы собираетесь удалить этот локальный плагин. После удаления его будет невозможно восстановить. Вы уверены, что хотите удалить этот плагин?",
"deleteSuccess": "Плагин успешно удален",
"manifest": {
"identifier": {
"desc": "Уникальный идентификатор плагина",
"label": "Идентификатор"
},
"mode": {
"local": "Визуальная настройка",
"local-tooltip": "Визуальная настройка временно недоступна",
"url": "Онлайн-ссылка"
},
"name": {
"desc": "Заголовок плагина",
"label": "Заголовок",
"placeholder": "Поиск в поисковой системе"
}
},
"meta": {
"author": {
"desc": "Автор плагина",
"label": "Автор"
},
"avatar": {
"desc": "Иконка плагина, можно использовать Emoji или URL",
"label": "Иконка"
},
"description": {
"desc": "Описание плагина",
"label": "Описание",
"placeholder": "Получение информации из поисковой системы"
},
"formFieldRequired": "Это обязательное поле",
"homepage": {
"desc": "Домашняя страница плагина",
"label": "Домашняя страница"
},
"identifier": {
"desc": "Уникальный идентификатор плагина, будет автоматически определен из манифеста",
"errorDuplicate": "Идентификатор уже используется другим плагином. Пожалуйста, измените идентификатор",
"label": "Идентификатор",
"pattenErrorMessage": "Можно вводить только латинские буквы, цифры, - и _"
},
"manifest": {
"desc": "LobeChat будет устанавливать плагин по этой ссылке",
"jsonInvalid": "Манифест не соответствует стандарту. Результат проверки: \n\n {{error}}",
"label": "URL-адрес описания плагина",
"preview": "Предварительный просмотр манифеста",
"refresh": "Обновить",
"requestError": "Не удалось получить данные по этой ссылке. Пожалуйста, введите действительную ссылку и проверьте, разрешен ли кросс-доменный доступ",
"urlError": "Ссылка не возвращает данные в формате JSON. Пожалуйста, введите действительную ссылку"
},
"title": {
"desc": "Заголовок плагина",
"label": "Заголовок",
"placeholder": "Поиск в поисковой системе"
}
},
"metaConfig": "Настройка метаданных плагина",
"modalDesc": "После добавления пользовательского плагина его можно использовать для проверки разработки плагинов или непосредственно в сеансе. См. документацию по разработке плагинов",
"preview": {
"card": "Предварительный просмотр плагина",
"desc": "Предварительный просмотр описания плагина",
"title": "Предварительный просмотр имени плагина"
},
"save": "Сохранить",
"saveSuccess": "Настройки плагина успешно сохранены",
"tabs": {
"manifest": "Описание функций (Манифест)",
"meta": "Метаданные плагина"
},
"title": "Добавить пользовательский плагин",
"update": "Обновить",
"updateSuccess": "Настройки плагина успешно обновлены"
},
"list": {
"item": {
"deprecated.title": "Удалено",
"local.config": "Настройка",
"local.title": "Пользовательский"
}
},
"loading": {
"content": "Получение данных...",
"plugin": "Выполнение плагина..."
},
"pluginList": "Список плагинов",
"plugins": {
"unknown": "Проверка плагинов..."
},
"settings": {
"indexUrl": {
"title": "Индекс рынка",
"tooltip": "Редактирование в настоящее время недоступно"
},
"modalDesc": "После настройки адреса рынка плагинов можно использовать пользовательский рынок плагинов",
"title": "Настройки рынка плагинов"
}
}
3 changes: 2 additions & 1 deletion locales/ru_RU/setting.json
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@
"add": "Добавить",
"addTooltip": "Добавить кастомный плагин",
"config": "{{id}} Конфигурация плагина",
"clearDeprecated": "Удалить недействительные плагины"
"clearDeprecated": "Удалить недействительные плагины",
"settings": "Настройки плагинов"
},
"settingSystem": {
"accessCode": {
Expand Down
2 changes: 1 addition & 1 deletion locales/zh_CN/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"import": "导入配置",
"inbox": {
"defaultMessage": "你好,我是你的智能助手,你可以问我任何问题,我会尽力回答你。如果需要获得更加专业或定制的助手,可以点击<kbd>+</kbd>创建自定义助手",
"desc": "开启大脑集群,激发思维火花。你的智能助理,就在这里与你交流一切",
"desc": "开启大脑集群,激发思维火花。你的智能助理,在这里与你交流一切",
"title": "随便聊聊"
},
"message": {
Expand Down
3 changes: 2 additions & 1 deletion locales/zh_CN/market.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"search": {
"placeholder": "搜索助手..."
}
},
"submitAgent": "提交助手"
}
8 changes: 8 additions & 0 deletions locales/zh_CN/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,13 @@
"pluginList": "插件列表",
"plugins": {
"unknown": "插件检测中..."
},
"settings": {
"indexUrl": {
"title": "市场索引",
"tooltip": "暂不支持编辑"
},
"modalDesc": "配置插件市场的地址后,可以使用自定义的插件市场",
"title": "设置插件市场"
}
}
1 change: 1 addition & 0 deletions locales/zh_CN/setting.json
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
"addTooltip": "添加自定义插件",
"clearDeprecated": "移除无效插件",
"config": "{{id}} 插件配置",
"settings": "配置插件市场",
"title": "插件列表"
},
"settingSystem": {
Expand Down
17 changes: 17 additions & 0 deletions scripts/const.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { readdirSync } from 'node:fs';
import { resolve } from 'node:path';

import i18nConfig from '../.i18nrc';

export const root = resolve(__dirname, '..');
export const localesDir = resolve(root, i18nConfig.output);
export const localeDir = (locale: string) => resolve(localesDir, locale);
export const localeDirJsonList = (locale: string) =>
readdirSync(localeDir(locale)).filter((name) => name.includes('.json'));
export const srcLocalesDir = resolve(root, './src/locales');
export const entryLocaleJsonFilepath = (file: string) =>
resolve(localesDir, i18nConfig.entryLocale, file);
export const outputLocaleJsonFilepath = (locale: string, file: string) =>
resolve(localesDir, locale, file);
export const srcLocalesResources = resolve(root, srcLocalesDir, 'resources');
export const localesResourcesFilepath = (locale: string) => resolve(srcLocalesResources, locale);
14 changes: 8 additions & 6 deletions scripts/genDefaultLocale.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { consola } from 'consola';
import { colors } from 'consola/utils';
import fs from 'node:fs';
import { resolve } from 'node:path';

import i18nConfig from '../.i18nrc';
import { entryLocaleJsonFilepath, localesResourcesFilepath } from './const';
import { writeJSON } from './utils';

export const genDefaultLocale = (input: string) => {
export const genDefaultLocale = () => {
consola.info(`Default locale is ${i18nConfig.entryLocale}...`);
const resources = require(`../${input}/${i18nConfig.entryLocale}`);

const resources = require(localesResourcesFilepath(i18nConfig.entryLocale));
const data = Object.entries(resources.default);
consola.start(`Generate default locale json, found ${data.length} namespaces...`);

for (const [ns, value] of data) {
const filepath = resolve(i18nConfig.output, i18nConfig.entryLocale, `${ns}.json`);
fs.writeFileSync(filepath, JSON.stringify(value, null, 2));
const filepath = entryLocaleJsonFilepath(`${ns}.json`);
writeJSON(filepath, value);
consola.success(colors.bgWhiteBright(colors.black(` ${ns} `)), colors.gray(filepath));
}
};
Empty file added scripts/genDiff.ts
Empty file.
48 changes: 12 additions & 36 deletions scripts/genResources.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,27 @@
import { consola } from 'consola';
import { colors } from 'consola/utils';
import { tocForResources } from 'i18next-resources-for-ts';
import fs from 'node:fs';
import { resolve } from 'node:path';

import i18nConfig from '../.i18nrc.js';
import { localeDirJsonList, localesResourcesFilepath } from './const';
import { genResourcesContent, genToc } from './utils';

const locales = [i18nConfig.entryLocale, ...i18nConfig.outputLocales];
export const genResources = (output: string) => {
let index = '';
let indexObj = '';

export const genResources = () => {
consola.start(`Generate locale resources and types, found ${locales.length} locales...`);

for (const locale of locales) {
const files = fs
.readdirSync(resolve(i18nConfig.output, locale))
.filter((name) => name.includes('.json'));
index += `import ${locale} from "./${locale}";\n`;
indexObj += ` "${locale.replace('_', '-')}": ${locale},\n`;
const ns = [];
for (const file of files) {
ns.push({
name: file.replace('.json', ''),
path: resolve(i18nConfig.output, locale, file),
});
}
let toc = tocForResources(ns, resolve(output)).replaceAll('\\', '/');
if (locale === i18nConfig.entryLocale) {
toc = toc.replaceAll('.json', '').replaceAll('../../../locales/zh_CN', '../default');
}
const filepath = resolve(output, `${locale}.ts`);
const files = localeDirJsonList(locale);
const toc = genToc(files, locale);

const filepath = localesResourcesFilepath(`${locale}.ts`);
fs.writeFileSync(filepath, toc);
consola.success(colors.bgBlue(colors.black(` ${locale} `)), colors.gray(filepath));
}
const indexFilepath = resolve(output, `index.ts`);
fs.writeFileSync(
indexFilepath,
`${index}
const resources = {
${indexObj}} as const;
export default resources;
export const defaultResources = ${i18nConfig.entryLocale};
export type Resources = typeof resources;
export type DefaultResources = typeof defaultResources;
export type Namespaces = keyof DefaultResources;
export type Locales = keyof Resources;
`,
);

const indexFilepath = localesResourcesFilepath(`index.ts`);
fs.writeFileSync(indexFilepath, genResourcesContent(locales));

consola.success(colors.bgGreen(colors.black(` INDEX `)), colors.gray(indexFilepath));
};
6 changes: 2 additions & 4 deletions scripts/toc.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { genDefaultLocale } from './genDefaultLocale';
import { genResources } from './genResources';

const RES_OUTPUT = 'src/locales/resources';

genDefaultLocale(RES_OUTPUT);
genResources(RES_OUTPUT);
genDefaultLocale();
genResources();
53 changes: 53 additions & 0 deletions scripts/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { tocForResources } from 'i18next-resources-for-ts';
import { readFileSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';

import i18nConfig from '../.i18nrc';
import { srcLocalesResources } from './const';

export const readJSON = (filePath: string) => {
const data = readFileSync(filePath, 'utf8');
return JSON.parse(data);
};

export const writeJSON = (filePath: string, data: any) => {
const jsonStr = JSON.stringify(data, null, 2);
writeFileSync(filePath, jsonStr, 'utf8');
};

export const genResourcesContent = (locales: string[]) => {
let index = '';
let indexObj = '';

for (const locale of locales) {
index += `import ${locale} from "./${locale}";\n`;
indexObj += ` "${locale.replace('_', '-')}": ${locale},\n`;
}

return `${index}
const resources = {
${indexObj}} as const;
export default resources;
export const defaultResources = ${i18nConfig.entryLocale};
export type Resources = typeof resources;
export type DefaultResources = typeof defaultResources;
export type Namespaces = keyof DefaultResources;
export type Locales = keyof Resources;
`;
};

export const genNamespaceList = (files: string[], locale: string) => {
return files.map((file) => ({
name: file.replace('.json', ''),
path: resolve(i18nConfig.output, locale, file),
}));
};

export const genToc = (files: string[], locale: string) => {
const ns = genNamespaceList(files, locale);
let toc = tocForResources(ns, srcLocalesResources).replaceAll('\\', '/');
if (locale === i18nConfig.entryLocale) {
toc = toc.replaceAll('.json', '').replaceAll('../../../locales/zh_CN', '../default');
}
return toc;
};
Loading

0 comments on commit 3c0117e

Please sign in to comment.