@alauda/doom 1.1.2 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,22 +3,21 @@ import { Language } from '../shared/index.js';
3
3
  import type { TranslateOptions } from '../types.js';
4
4
  export interface I18nFrontmatter {
5
5
  i18n?: {
6
- title?: Record<string, string>;
7
6
  additionalPrompts?: string;
8
7
  disableAutoTranslation?: boolean;
9
8
  };
10
9
  sourceSHA?: string;
11
10
  title?: string;
11
+ description?: string;
12
12
  }
13
13
  export declare const TERMS_SUPPORTED_LANGUAGES: Language[];
14
14
  export interface InternalTranslateOptions extends TranslateOptions {
15
15
  source: Language;
16
16
  sourceContent: string;
17
17
  target: Language;
18
- targetContent?: string;
19
18
  additionalPrompts?: string;
20
19
  }
21
- export declare const translate: ({ source, sourceContent, target, targetContent, systemPrompt, userPrompt, additionalPrompts, }: InternalTranslateOptions) => Promise<string>;
20
+ export declare const translate: ({ source, sourceContent, target, systemPrompt, userPrompt, additionalPrompts, }: InternalTranslateOptions) => Promise<string>;
22
21
  export interface TranslateCommandOptions {
23
22
  source: Language;
24
23
  target: Language;
@@ -7,74 +7,147 @@ import { removeLeadingSlash } from '@rspress/shared';
7
7
  import { logger } from '@rspress/shared/logger';
8
8
  import { Command } from 'commander';
9
9
  import { render } from 'ejs';
10
- import { merge } from 'es-toolkit/compat';
11
10
  import matter from 'gray-matter';
12
11
  import { AzureOpenAI, RateLimitError } from 'openai';
13
12
  import { pRateLimit } from 'p-ratelimit';
14
13
  import { glob } from 'tinyglobby';
15
14
  import { cyan, red } from 'yoctocolors';
16
15
  import { mdProcessor, mdxProcessor, normalizeImgSrc, } from '../plugins/index.js';
17
- import { Language, SUPPORTED_LANGUAGES } from '../shared/index.js';
16
+ import { Language, SUPPORTED_LANGUAGES, TITLE_TRANSLATION_MAP, } from '../shared/index.js';
18
17
  import { pathExists } from '../utils/index.js';
19
18
  import { escapeMarkdownHeadingIds, getMatchedDocFilePaths, parseBoolean, parseTerms, } from './helpers.js';
20
19
  import { loadConfig } from './load-config.js';
21
- export const TERMS_SUPPORTED_LANGUAGES = ['en', 'zh'];
20
+ export const TERMS_SUPPORTED_LANGUAGES = ['en', 'zh', 'ru'];
21
+ // Directories that should be copied instead of translated
22
+ const COPY_ONLY_DIRECTORIES = [
23
+ 'apis/advanced_apis/**',
24
+ 'apis/kubernetes_apis/**',
25
+ ];
22
26
  const DEFAULT_SYSTEM_PROMPT = `
23
- ## 角色
24
- 你是一位专业的技术文档工程师,擅长写作高质量的<%= targetLang %>技术分档。请你帮我准确地将以下<%= sourceLang %>翻译成<%= targetLang %>,风格与<%= targetLang %>技术文档保持一致。
27
+ You are a professional technical documentation engineer, skilled in writing high-quality technical documentation in <%= targetLang %>. Please accurately translate the following text from <%= sourceLang %> to <%= targetLang %>, maintaining the style consistent with technical documentation in <%= sourceLang %>.
25
28
 
26
- ## 规则
27
- - 第一条消息为需要翻译的最新<%= sourceLang %>文档,第二条消息为之前翻译过的但内容可能过期的<%= targetLang %>文档,如果没有翻译过则为空
28
- - 输入格式为 MDX 格式,输出格式也必须保留原始 MDX 格式,不要翻译其中的 jsx 组件名称,如 <Overview />,且不要额外包装在不必要的代码块中
29
- - 文档中的资源链接不要翻译和替换
30
- - MDX 组件中包含的内容需要翻译,MDX 组件名和参数值不需要翻译,但特殊的 MDX 组件参数值需要翻译,示例:
31
- - <Overview /> 中的 Overview 是组件名,不用翻译
32
- - <Tab label="value">组件包含的内容</Tab>,label 是 key 不用翻译,"value" 是参数值需要翻译
33
- <%= terms %>
34
- - 如果存在下列注释,请保留不用翻译,更不要修改注释内容
29
+ ## Baseline Requirements
30
+ - Sentences should be fluent and conform to the expression habits of the <%= targetLang %> language.
31
+ - Input format is MDX; output format must also retain the original MDX format. Do not translate the names of jsx components such as <Overview />, and do not wrap output in unnecessary code blocks.
32
+ - **CRITICAL**: Do not translate or modify ANY link content in the document. This includes:
33
+ - URLs in markdown links: [text](URL) - keep URL exactly as is
34
+ - Reference-style links: [text][ref] and [ref]: URL - keep both ref and URL unchanged
35
+ - Inline URLs: https://example.com - keep completely unchanged
36
+ - Image links: ![alt](src) - keep src unchanged, but alt text can be translated
37
+ - Anchor links: [text](#anchor) - keep #anchor unchanged
38
+ - Any href attributes in HTML tags - keep unchanged
39
+ - Do not translate professional technical terms and proper nouns, including but not limited to: Kubernetes, Docker, CLI, API, REST, GraphQL, JSON, YAML, Git, GitHub, GitLab, AWS, Azure, GCP, Linux, Windows, macOS, Node.js, React, Vue, Angular, TypeScript, JavaScript, Python, Java, Go, Rust, etc. Keep these terms in their original form.
40
+ - The title field and description field in frontmatter should be translated, other frontmatter fields should retain and do not translate.
41
+ - Content within MDX components needs to be translated, whereas MDX component names and parameter keys do not.
42
+ - Do not modify or translate any placeholders in the format of __ANCHOR_N__ (where N is a number). These placeholders must be kept exactly as they appear in the source text.
43
+ - Keep original escape characters like backslash, angle brackets, etc. unchanged during translation.
44
+ - Do not add any escape characters to special characters like [], (), {}, etc. unless they were explicitly present in the source text. For example:
45
+ - If source has "Architecture [Optional]", keep it as "Architecture [Optional]" (not "Architecture \\[Optional]")
46
+ - If source has "Function (param)", keep it as "Function (param)" (not "Function \\(param)")
47
+ - Only add escape characters if they were present in the original text
48
+ - Preserve and do not translate the following comments, nor modify their content:
35
49
  - {/* release-notes-for-bugs */}
36
50
  - <!-- release-notes-for-bugs -->
37
- - 如果存在下列注释,请整体移除不要保留
51
+ - Remove and do not retain the following comments:
38
52
  - {/* reference-start */}
39
53
  - {/* reference-end */}
40
54
  - <!-- reference-start -->
41
55
  - <!-- reference-end -->
42
- - 翻译过程中务必保留原文中的 \\< 和 \\{ 转义字符不要做任何转义变更
43
- - 翻译过程中不要破坏原有的 Markdown 格式,如 frontmatter, 代码块、列表、表格等,其中 frontmatter.ii8n 的内容不用做任何翻译,只需要原样返回即可
56
+ - Ensure the original Markdown format remains intact during translation, such as frontmatter, code blocks, lists, tables, etc.
57
+ - Do not translate the content of the code block.
58
+ <% if (titleTranslationPrompt) { %>
59
+ <%- titleTranslationPrompt %>
60
+ <% } %>
61
+ <% if (terms) { %>
62
+ <%- terms %>
63
+ <% } %>
44
64
 
45
- ## 策略
46
- 分四步进行翻译工作:
47
- 1. 根据<%= sourceLang %>文档直译成<%= targetLang %>,保持原有格式,不要遗漏任何信息
48
- 2. 根据第一步直译的结果,指出其中存在的具体问题,要准确描述,不宜笼统的表示,也不要增加原文不存在的内容或格式,包括不仅限于
49
- - 不符合<%= targetLang %>表达习惯,明确指出不符合的地方
50
- - 语句不通顺,指出位置,不需要给出修改意见,意译时修复
51
- - 晦涩难懂,模棱两可,不易理解,可以尝试给出解释
52
- 3. 根据第一步直译的结果和第二步指出的问题,重新进行意译,保证内容的原意的基础上,使其更易于理解,更符合<%= targetLang %>技术文档的表达习惯,同时保持原有的格式不变
53
- 4. 当存在之前翻译过的<%= targetLang %>文档时,将第三步的结果分段与之前的<%= targetLang %>文档细致地比较,不要遗漏任何新的分段(包括文本、代码块、图片、超链接等等),如果分段内翻译结果意思相近,仅仅表达方式不同的,且没有新增任何内容时,则该分段只需要保持之前翻译过的内容即可,不需要重复翻译
65
+ <% if (userPrompt || additionalPrompts) { %>
66
+ ## Additional Requirements
67
+ These are additional requirements for the translation. They should be met along with the baseline requirements, and in case of any conflict, the baseline requirements should take precedence.
54
68
 
55
- 最终只需要完整输出最后一步的结果,不需要输出任何提及提示词或之前步骤的内容,也不要只返回新增的内容。
69
+ The text for translation is provided below, within triple quotes:
70
+ """
71
+ <% if (userPrompt) { %>
72
+ <%- userPrompt %>
73
+ <% } %>
56
74
 
57
- <%= userPrompt %>
58
-
59
- <%= additionalPrompts %>
75
+ <% if (additionalPrompts) { %>
76
+ <%- additionalPrompts %>
77
+ <% } %>
78
+ """
79
+ <% } %>
60
80
  `.trim();
61
81
  let openai;
62
- const resolveTerms_ = async () => {
82
+ const resolveTerms = async (sourceLang, targetLang, sourceContent) => {
63
83
  const parsedTerms = await parseTerms();
64
- return ('- 以下是常见的相关术语词汇对应表(English <-> 中文)\n' +
65
- parsedTerms.map(({ en, zh = en }) => ` * ${en} <-> ${zh}`).join('\n'));
66
- };
67
- let termsCache;
68
- const resolveTerms = async () => {
69
- if (termsCache) {
70
- return termsCache;
84
+ // Filter terms that exist in source content and have translations for both source and target languages
85
+ const relevantTerms = parsedTerms.filter((term) => {
86
+ // Check if term has both source and target language translations
87
+ const sourceTranslation = term[sourceLang];
88
+ const targetTranslation = term[targetLang];
89
+ if (!sourceTranslation || !targetTranslation) {
90
+ return false;
91
+ }
92
+ // Check if the source translation appears in the source content (case-insensitive)
93
+ const sourceTermRegex = new RegExp(`\\b${sourceTranslation.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'i');
94
+ return sourceTermRegex.test(sourceContent);
95
+ });
96
+ if (relevantTerms.length === 0) {
97
+ logger.debug('No relevant terms found for translation');
98
+ return '';
71
99
  }
72
- return (termsCache = resolveTerms_().then((terms) => {
73
- logger.debug('Resolved terms:', terms);
74
- return terms;
75
- }));
100
+ const sourceLangName = Language[sourceLang];
101
+ const targetLangName = Language[targetLang];
102
+ const terms = `- The following is a common related terminology vocabulary table (${sourceLangName} <=> ${targetLangName}), you should use it to translate the matched text.\n` +
103
+ relevantTerms
104
+ .map((term) => ` * ${term[sourceLang]} <=> ${term[targetLang]}`)
105
+ .join('\n');
106
+ logger.debug('Resolved terms:', terms);
107
+ return terms;
76
108
  };
77
- export const translate = async ({ source, sourceContent, target, targetContent = '', systemPrompt, userPrompt = '', additionalPrompts = '', }) => {
109
+ const ANCHOR_REGEX = /(\\\\?)\{#([a-zA-Z0-9_-]+)\}/g;
110
+ function replaceAnchorsWithPlaceholders(content) {
111
+ // Handle escaped underscores in anchor IDs (e.g., \{#independent\_doc\_site} -> \{#independent_doc_site})
112
+ // This is necessary because MDX processor automatically escapes underscores in heading IDs
113
+ // to ensure proper Markdown parsing, but we need the original unescaped form for anchor matching
114
+ const unescapedContent = content.replace(/\\_/g, '_');
115
+ const anchors = [];
116
+ const contentWithPlaceholders = unescapedContent.replace(ANCHOR_REGEX, (match) => {
117
+ anchors.push(match);
118
+ return `__ANCHOR_${anchors.length - 1}__`;
119
+ });
120
+ return { content: contentWithPlaceholders, anchors };
121
+ }
122
+ function restoreAnchors(content, anchors) {
123
+ return content.replace(/__ANCHOR_(\d+)__/g, (_, index) => {
124
+ const numIndex = parseInt(index, 10);
125
+ if (isNaN(numIndex) || numIndex < 0 || numIndex >= anchors.length) {
126
+ throw new Error(`Invalid anchor index: ${index}`);
127
+ }
128
+ const anchor = anchors[numIndex];
129
+ return anchor;
130
+ });
131
+ }
132
+ function extractFirstLevelHeading(content) {
133
+ const lines = content.split('\n');
134
+ for (const line of lines) {
135
+ const trimmed = line.trim();
136
+ if (trimmed.startsWith('# ')) {
137
+ return trimmed.substring(2).trim();
138
+ }
139
+ }
140
+ return null;
141
+ }
142
+ function getTitleTranslation(title, sourceLang, targetLang) {
143
+ for (const translations of TITLE_TRANSLATION_MAP) {
144
+ if (translations[sourceLang] === title && translations[targetLang]) {
145
+ return translations[targetLang];
146
+ }
147
+ }
148
+ return null;
149
+ }
150
+ export const translate = async ({ source, sourceContent, target, systemPrompt, userPrompt = '', additionalPrompts = '', }) => {
78
151
  if (!openai) {
79
152
  openai = new AzureOpenAI({
80
153
  endpoint: process.env.AZURE_OPENAI_ENDPOINT ||
@@ -87,9 +160,26 @@ export const translate = async ({ source, sourceContent, target, targetContent =
87
160
  const targetLang = Language[target];
88
161
  let terms = '';
89
162
  if ([source, target].every((lang) => TERMS_SUPPORTED_LANGUAGES.includes(lang))) {
90
- terms = await resolveTerms();
163
+ terms = await resolveTerms(source, target, sourceContent);
91
164
  }
92
- const finalSystemPrompt = await render(systemPrompt?.trim() || DEFAULT_SYSTEM_PROMPT, { sourceLang, targetLang, userPrompt, additionalPrompts, terms }, { async: true });
165
+ const firstLevelHeading = extractFirstLevelHeading(sourceContent);
166
+ let titleTranslationPrompt = '';
167
+ if (firstLevelHeading) {
168
+ const titleTranslation = getTitleTranslation(firstLevelHeading, source, target);
169
+ if (titleTranslation) {
170
+ titleTranslationPrompt = `- The heading "${firstLevelHeading}" should be translated as "${titleTranslation}".`;
171
+ }
172
+ }
173
+ const { content: contentWithPlaceholders, anchors } = replaceAnchorsWithPlaceholders(sourceContent);
174
+ const finalSystemPrompt = await render(systemPrompt?.trim() || DEFAULT_SYSTEM_PROMPT, {
175
+ sourceLang,
176
+ targetLang,
177
+ userPrompt,
178
+ additionalPrompts: additionalPrompts,
179
+ terms,
180
+ titleTranslationPrompt,
181
+ }, { async: true });
182
+ logger.debug('Final system prompt:\n', finalSystemPrompt);
93
183
  const { choices } = await openai.chat.completions.parse({
94
184
  messages: [
95
185
  {
@@ -98,21 +188,17 @@ export const translate = async ({ source, sourceContent, target, targetContent =
98
188
  },
99
189
  {
100
190
  role: 'user',
101
- content: sourceContent,
102
- },
103
- {
104
- role: 'user',
105
- content: targetContent,
191
+ content: contentWithPlaceholders,
106
192
  },
107
193
  ],
108
- model: 'gpt-4o-mini',
194
+ model: 'gpt-4.1-mini',
109
195
  temperature: 0.2,
110
196
  });
111
197
  const { content, refusal } = choices[0].message;
112
198
  if (refusal) {
113
199
  throw new Error(refusal);
114
200
  }
115
- return content;
201
+ return restoreAnchors(content, anchors);
116
202
  };
117
203
  const limit = pRateLimit({
118
204
  interval: 60_000, // 1min
@@ -159,6 +245,12 @@ export const translateCommand = new Command('translate')
159
245
  for (const internalFilePath of internalFilePaths) {
160
246
  allSourceFilePaths.delete(internalFilePath);
161
247
  }
248
+ // Get copy-only files using glob patterns
249
+ const copyOnlyFilePaths = await glob(COPY_ONLY_DIRECTORIES, {
250
+ absolute: true,
251
+ cwd: sourceDir,
252
+ });
253
+ const copyOnlyFilePathsSet = new Set(copyOnlyFilePaths);
162
254
  if (allSourceFilePaths.size === 0) {
163
255
  logger.error(`No files matched by the glob patterns: ${globs.map((g) => `\`${cyan(g)}\``).join(', ')}`);
164
256
  process.exitCode = 1;
@@ -208,52 +300,75 @@ export const translateCommand = new Command('translate')
208
300
  if (await pathExists(targetFilePath, 'file')) {
209
301
  targetContent = await fs.readFile(targetFilePath, 'utf-8');
210
302
  targetFrontmatter = matter(targetContent).data;
211
- if (targetFrontmatter.i18n?.disableAutoTranslation ||
212
- (!force && targetFrontmatter.sourceSHA === sourceSHA)) {
303
+ if (!force && targetFrontmatter.sourceSHA === sourceSHA) {
213
304
  allSourceFilePaths.delete(sourceFilePath);
214
305
  return;
215
306
  }
216
307
  }
308
+ const shouldCopyOnly = copyOnlyFilePathsSet.has(sourceFilePath);
217
309
  await limit(async () => {
218
310
  const sourceRelativePath = path.relative(docsDir, sourceFilePath);
219
311
  const targetRelativePath = path.relative(docsDir, targetFilePath);
220
- logger.info(`Translating ${cyan(sourceRelativePath)} to ${cyan(targetRelativePath)}`);
221
- const isMdx = sourceFilePath.endsWith('.mdx');
222
- const processor = isMdx ? mdxProcessor : mdProcessor;
223
- const ast = processor.parse(escapeMarkdownHeadingIds(sourceContent));
224
- const targetBase = path.dirname(targetFilePath);
225
- const normalizeImgSrcOptions = {
226
- localPublicBase: path.resolve(docsDir, 'public'),
227
- sourceBase: path.dirname(sourceFilePath),
228
- targetBase,
229
- translating: { source, target, copy },
230
- };
231
- const normalizedSourceContent = processor.stringify({
232
- ...ast,
233
- children: ast.children.map((it) => normalizeImgSrc(it, normalizeImgSrcOptions)),
234
- });
235
- targetContent = await translate({
236
- ...config.translate,
237
- source,
238
- sourceContent: normalizedSourceContent,
239
- target,
240
- targetContent: force ? '' : targetContent,
241
- additionalPrompts: targetFrontmatter?.i18n?.additionalPrompts ??
242
- sourceFrontmatter.i18n?.additionalPrompts,
243
- });
244
- const { data, content } = matter(targetContent);
245
- const newFrontmatter = merge({}, sourceFrontmatter, targetFrontmatter, data);
246
- newFrontmatter.sourceSHA = sourceSHA;
247
- if (sourceFrontmatter.i18n?.title?.[target]) {
248
- newFrontmatter.title = sourceFrontmatter.i18n.title[target];
312
+ if (shouldCopyOnly) {
313
+ logger.info(`Copying ${cyan(sourceRelativePath)} to ${cyan(targetRelativePath)}`);
314
+ // For copy-only files, we still update the sourceSHA but don't translate
315
+ const newFrontmatter = { ...sourceFrontmatter, sourceSHA };
316
+ delete newFrontmatter.i18n;
317
+ const { content } = matter(sourceContent);
318
+ targetContent = matter.stringify(content.startsWith('\n') ? content : '\n' + content, newFrontmatter);
319
+ const targetBase = path.dirname(targetFilePath);
320
+ await fs.mkdir(targetBase, { recursive: true });
321
+ await fs.writeFile(targetFilePath, targetContent);
322
+ logger.info(`${cyan(sourceRelativePath)} copied to ${cyan(targetRelativePath)}`);
249
323
  }
250
- if (typeof newFrontmatter.title !== 'string') {
251
- delete newFrontmatter.title;
324
+ else {
325
+ logger.info(`Translating ${cyan(sourceRelativePath)} to ${cyan(targetRelativePath)}`);
326
+ const isMdx = sourceFilePath.endsWith('.mdx');
327
+ const processor = isMdx ? mdxProcessor : mdProcessor;
328
+ const ast = processor.parse(escapeMarkdownHeadingIds(sourceContent));
329
+ const targetBase = path.dirname(targetFilePath);
330
+ const normalizeImgSrcOptions = {
331
+ localPublicBase: path.resolve(docsDir, 'public'),
332
+ sourceBase: path.dirname(sourceFilePath),
333
+ targetBase,
334
+ translating: { source, target, copy },
335
+ };
336
+ const normalizedSourceContent = processor.stringify({
337
+ ...ast,
338
+ children: ast.children.map((it) => normalizeImgSrc(it, normalizeImgSrcOptions)),
339
+ });
340
+ targetContent = await translate({
341
+ ...config.translate,
342
+ source,
343
+ sourceContent: normalizedSourceContent,
344
+ target,
345
+ additionalPrompts: sourceFrontmatter.i18n?.additionalPrompts,
346
+ });
347
+ const newFrontmatter = { ...sourceFrontmatter, sourceSHA };
348
+ delete newFrontmatter.i18n;
349
+ const { data, content } = matter(targetContent);
350
+ const typedData = data;
351
+ if (typedData.title && typeof typedData.title === 'string') {
352
+ newFrontmatter.title = typedData.title;
353
+ }
354
+ if (typedData.description &&
355
+ typeof typedData.description === 'string') {
356
+ newFrontmatter.description = typedData.description;
357
+ }
358
+ if (sourceFrontmatter.title) {
359
+ const titleTranslation = getTitleTranslation(sourceFrontmatter.title, source, target);
360
+ if (titleTranslation) {
361
+ newFrontmatter.title = titleTranslation;
362
+ }
363
+ }
364
+ if (typeof newFrontmatter.title !== 'string') {
365
+ delete newFrontmatter.title;
366
+ }
367
+ targetContent = matter.stringify(content.startsWith('\n') ? content : '\n' + content, newFrontmatter);
368
+ await fs.mkdir(targetBase, { recursive: true });
369
+ await fs.writeFile(targetFilePath, targetContent);
370
+ logger.info(`${cyan(sourceRelativePath)} translated to ${cyan(targetRelativePath)}`);
252
371
  }
253
- targetContent = matter.stringify(content.startsWith('\n') ? content : '\n' + content, newFrontmatter);
254
- await fs.mkdir(targetBase, { recursive: true });
255
- await fs.writeFile(targetFilePath, targetContent);
256
- logger.info(`${cyan(sourceRelativePath)} translated to ${cyan(targetRelativePath)}`);
257
372
  allSourceFilePaths.delete(sourceFilePath);
258
373
  });
259
374
  }));
@@ -1 +1 @@
1
- export declare const SvgDown: () => import("react/jsx-runtime").JSX.Element;
1
+ export declare const Down: () => import("react/jsx-runtime").JSX.Element;
@@ -1,2 +1,2 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- export const SvgDown = () => (_jsx("svg", { width: "1em", height: "1em", viewBox: "0 0 32 32", children: _jsx("path", { fill: "currentColor", d: "M16 22L6 12l1.4-1.4l8.6 8.6l8.6-8.6L26 12z" }) }));
2
+ export const Down = () => (_jsx("svg", { width: "1em", height: "1em", viewBox: "0 0 32 32", children: _jsx("path", { fill: "currentColor", d: "M16 22L6 12l1.4-1.4l8.6 8.6l8.6-8.6L26 12z" }) }));
@@ -1,52 +1,66 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { Tag } from '@rspress/core/theme';
3
- import { isExternalUrl, withoutBase, } from '@rspress/shared';
4
- import { useCallback, useState } from 'react';
5
- import { SvgDown } from './Down.js';
3
+ import { isExternalUrl, matchNavbar, } from '@rspress/shared';
4
+ import { useRef, useState } from 'react';
5
+ import { Down } from './Down.js';
6
6
  import { NavMenuSingleItem, } from './NavMenuSingleItem.js';
7
7
  import { SvgWrapper } from './SvgWrapper.js';
8
8
  function ActiveGroupItem({ item }) {
9
- return (_jsxs("div", { className: "rounded-2xl my-1 flex", style: {
9
+ return (_jsxs("div", { className: "rp-rounded-2xl rp-my-1 rp-flex", style: {
10
10
  padding: '0.4rem 1.5rem 0.4rem 0.75rem',
11
- }, children: [item.tag && _jsx(Tag, { tag: item.tag }), _jsx("span", { className: "text-brand", children: item.text })] }, item.link));
11
+ }, children: [item.tag && _jsx(Tag, { tag: item.tag }), _jsx("span", { className: "rp-text-brand", children: item.text })] }, item.link));
12
12
  }
13
13
  function NormalGroupItem({ item }) {
14
- return (_jsx("div", { className: "font-medium my-1", children: _jsx("a", { href: item.link, target: isExternalUrl(item.link) ? '_blank' : undefined, rel: "noopener noreferrer", children: _jsx("div", { className: "rounded-2xl hover:bg-mute", style: {
14
+ return (_jsx("div", { className: "rp-font-medium rp-my-1", children: _jsx("a", { href: item.link, target: isExternalUrl(item.link) ? '_blank' : undefined, rel: "noopener noreferrer", children: _jsx("div", { className: "rp-rounded-2xl hover:rp-bg-mute", style: {
15
15
  padding: '0.4rem 1.5rem 0.4rem 0.75rem',
16
- }, children: _jsxs("div", { className: "flex", children: [item.tag && _jsx(Tag, { tag: item.tag }), _jsx("span", { children: item.text })] }) }) }) }, item.link));
16
+ }, children: _jsxs("div", { className: "rp-flex", children: [item.tag && _jsx(Tag, { tag: item.tag }), _jsx("span", { children: item.text })] }) }) }) }, item.link));
17
17
  }
18
18
  export function NavMenuGroup(item) {
19
- const { activeValue, items: groupItems, base = '', pathname = '' } = item;
19
+ const { activeValue, items: groupItems, base = '', link = '', pathname = '', } = item;
20
20
  const [isOpen, setIsOpen] = useState(false);
21
- const onOpen = useCallback(() => {
21
+ const closeTimerRef = useRef(null);
22
+ const clearCloseTimer = () => {
23
+ if (closeTimerRef.current) {
24
+ clearTimeout(closeTimerRef.current);
25
+ closeTimerRef.current = null;
26
+ }
27
+ };
28
+ /**
29
+ * Handle mouse leave event for the dropdown menu
30
+ * Closes the menu after a 150ms delay to allow diagonal mouse movement
31
+ * to the dropdown content area
32
+ */
33
+ const handleMouseLeave = () => {
34
+ closeTimerRef.current = window.setTimeout(() => {
35
+ setIsOpen(false);
36
+ }, 150);
37
+ };
38
+ const handleMouseEnter = () => {
39
+ clearCloseTimer();
22
40
  setIsOpen(true);
23
- }, []);
24
- const onClose = useCallback(() => {
25
- setIsOpen(false);
26
- }, []);
41
+ };
27
42
  const renderLinkItem = (item) => {
28
- const isLinkActive = new RegExp(item.activeMatch || item.link).test(withoutBase(pathname, base));
43
+ const isLinkActive = matchNavbar(item, pathname, base);
29
44
  if (activeValue === item.text || (!activeValue && isLinkActive)) {
30
45
  return _jsx(ActiveGroupItem, { item: item }, item.link);
31
46
  }
32
47
  return _jsx(NormalGroupItem, { item: item }, item.link);
33
48
  };
34
49
  const renderGroup = (item) => {
35
- return (_jsxs("div", { children: ['link' in item ? (renderLinkItem(item)) : (_jsx("p", { className: "font-bold text-gray-400 my-1 not:first:border", children: item.text })), item.items.map(renderLinkItem)] }));
50
+ return (_jsxs("div", { children: ['link' in item ? (renderLinkItem(item)) : (_jsx("p", { className: "rp-font-bold rp-text-gray-400 rp-my-1 not:first:rp-border", children: item.text })), item.items.map(renderLinkItem)] }));
36
51
  };
37
- const hasMultiItems = groupItems.length > 1;
38
- const Content = hasMultiItems || item.link ? 'button' : 'span';
39
- const content = (_jsx(Content, { onMouseEnter: hasMultiItems ? onOpen : undefined, className: `${Content === 'button' ? 'rspress-nav-menu-group-button ' : ''}flex-center items-center font-medium text-sm text-text-1${hasMultiItems ? ' hover:text-text-2 transition-colors duration-200' : ''}`, children: item.link ? (_jsx(NavMenuSingleItem, { ...item, rightIcon: _jsx(SvgWrapper, { icon: SvgDown }) })) : (_jsxs(_Fragment, { children: [_jsxs("span", { className: "text-sm font-medium flex", style: hasMultiItems ? { marginRight: '2px' } : undefined, children: [_jsx(Tag, { tag: item.tag }), item.text] }), hasMultiItems && _jsx(SvgWrapper, { icon: SvgDown })] })) }));
40
- return hasMultiItems ? (_jsxs("div", { className: "relative flex-center h-14", onMouseLeave: onClose, children: [content, _jsx("div", { className: "rspress-nav-menu-group-content absolute mx-0.8 transition-opacity duration-300", style: {
52
+ return (_jsxs("div", { className: "rp-relative rp-flex rp-items-center rp-justify-center rp-h-14", onMouseLeave: handleMouseLeave, children: [_jsx("div", { onMouseEnter: handleMouseEnter, className: "rspress-nav-menu-group-button rp-flex rp-justify-center rp-items-center rp-font-medium rp-text-sm rp-text-text-1 hover:rp-text-text-2 rp-transition-colors rp-duration-200 rp-cursor-pointer", children: link ? (_jsx(NavMenuSingleItem, { ...item, rightIcon: _jsx(SvgWrapper, { icon: Down }) })) : (_jsxs(_Fragment, { children: [_jsxs("span", { className: "rp-text-sm rp-font-medium rp-flex", style: {
53
+ marginRight: '2px',
54
+ }, children: [_jsx(Tag, { tag: item.tag }), item.text] }), _jsx(SvgWrapper, { icon: Down })] })) }), _jsx("div", { className: "rspress-nav-menu-group-content rp-absolute rp-mx-0.8 rp-transition-opacity rp-duration-300", style: {
41
55
  opacity: isOpen ? 1 : 0,
42
56
  visibility: isOpen ? 'visible' : 'hidden',
43
57
  right: 0,
44
58
  top: '52px',
45
- }, children: _jsx("div", { className: "p-3 pr-2 w-full h-full max-h-100vh whitespace-nowrap", style: {
59
+ }, onMouseEnter: clearCloseTimer, children: _jsx("div", { className: "rp-p-3 rp-pr-2 rp-w-full rp-h-full rp-max-h-100vh rp-whitespace-nowrap", style: {
46
60
  boxShadow: 'var(--rp-shadow-3)',
47
61
  zIndex: 100,
48
62
  border: '1px solid var(--rp-c-divider-light)',
49
63
  borderRadius: 'var(--rp-radius-large)',
50
64
  background: 'var(--rp-c-bg)',
51
- }, children: groupItems.map((item) => (_jsx("div", { children: 'items' in item ? renderGroup(item) : renderLinkItem(item) }, item.text))) }) })] })) : (content);
65
+ }, children: groupItems.map((item) => (_jsx("div", { children: 'items' in item ? renderGroup(item) : renderLinkItem(item) }, item.text))) }) })] }));
52
66
  }
@@ -7,5 +7,5 @@ export function NavMenuSingleItem({ activeMatch, base, compact, download, link,
7
7
  const isActive = useMemo(() => !!base &&
8
8
  !!pathname &&
9
9
  new RegExp(activeMatch || link).test(withoutBase(pathname, base)), [activeMatch, base, link, pathname]);
10
- return (_jsx("a", { href: link, download: download, target: isExternalUrl(link) ? '_blank' : undefined, rel: "noopener noreferrer", children: _jsxs("div", { className: `rspress-nav-menu-item ${styles.singleItem} ${isActive ? styles.activeItem : ''} text-sm font-medium ${compact ? 'mx-0.5' : 'mx-1.5'} px-3 py-2 flex items-center`, children: [_jsx(Tag, { tag: tag }), text, rightIcon] }) }, link));
10
+ return (_jsx("a", { href: link, download: download, target: isExternalUrl(link) ? '_blank' : undefined, rel: "noopener noreferrer", children: _jsxs("div", { className: `rspress-nav-menu-item ${styles.singleItem} ${isActive ? `${styles.activeItem} rspress-nav-menu-item-active` : ''} rp-text-sm rp-font-medium ${compact ? 'rp-mx-0.5' : 'rp-mx-1.5'} rp-px-3 rp-py-2 rp-flex rp-items-center`, children: [_jsx(Tag, { tag: tag }), text, rightIcon] }) }, link));
11
11
  }
@@ -17,7 +17,7 @@ export declare const X: {
17
17
  blockquote: (props: import("react").ComponentProps<"blockquote">) => import("react/jsx-runtime").JSX.Element;
18
18
  strong: (props: import("react").ComponentProps<"strong">) => import("react/jsx-runtime").JSX.Element;
19
19
  a: (props: import("react").ComponentProps<"a">) => import("react/jsx-runtime").JSX.Element;
20
- code: typeof import("@rspress/theme-default").Code;
21
- pre: typeof import("@rspress/theme-default").PreWithCodeButtonGroup;
20
+ code: (props: import("react").HTMLProps<HTMLElement>) => import("react/jsx-runtime").JSX.Element;
21
+ pre: ({ containerElementClassName, children, className, title, codeButtonGroupProps, ...otherProps }: import("@rspress/theme-default").PreWithCodeButtonGroupProps) => import("react/jsx-runtime").JSX.Element | null;
22
22
  img: (props: import("react").ComponentProps<"img">) => import("react/jsx-runtime").JSX.Element;
23
23
  };
@@ -4,11 +4,12 @@ export declare const TRUTHY_VALUES: Set<string>;
4
4
  export declare const JS_STR_FALSY_VALUES: Set<string | null | undefined>;
5
5
  export declare const APIS_ROUTES: Set<string>;
6
6
  export declare const Language: {
7
- readonly en: "英文";
8
- readonly zh: "中文";
9
- readonly ru: "俄文";
7
+ readonly en: "English";
8
+ readonly zh: "Chinese";
9
+ readonly ru: "Russian";
10
10
  };
11
11
  export type Language = keyof typeof Language;
12
12
  export declare const SUPPORTED_LANGUAGES: Language[];
13
+ export declare const TITLE_TRANSLATION_MAP: Array<Partial<Record<Language, string>>>;
13
14
  export declare const UNVERSIONED = "unversioned";
14
15
  export declare const UNVERSIONED_PREFIX = "unversioned-";
@@ -22,10 +22,82 @@ export const JS_STR_FALSY_VALUES = new Set([
22
22
  ]);
23
23
  export const APIS_ROUTES = new Set(['apis/**', '*/apis/**']);
24
24
  export const Language = {
25
- en: '英文',
26
- zh: '中文',
27
- ru: '俄文',
25
+ en: 'English',
26
+ zh: 'Chinese',
27
+ ru: 'Russian',
28
28
  };
29
29
  export const SUPPORTED_LANGUAGES = Object.keys(Language);
30
+ export const TITLE_TRANSLATION_MAP = [
31
+ {
32
+ en: 'Navigation',
33
+ zh: '导航',
34
+ ru: 'Навигация',
35
+ },
36
+ {
37
+ en: 'Overview',
38
+ zh: '概览',
39
+ ru: 'Обзор',
40
+ },
41
+ {
42
+ en: 'Introduction',
43
+ zh: '介绍',
44
+ ru: 'Введение',
45
+ },
46
+ {
47
+ en: 'Architecture',
48
+ zh: '架构',
49
+ ru: 'Архитектура',
50
+ },
51
+ {
52
+ en: 'Install',
53
+ zh: '安装',
54
+ ru: 'Установка',
55
+ },
56
+ {
57
+ en: 'Upgrade',
58
+ zh: '升级',
59
+ ru: 'Обновление',
60
+ },
61
+ {
62
+ en: 'Quick Start',
63
+ zh: '快速开始',
64
+ ru: 'Быстрый старт',
65
+ },
66
+ {
67
+ en: 'Concepts',
68
+ zh: '核心概念',
69
+ ru: 'Основные понятия',
70
+ },
71
+ {
72
+ en: 'Guides',
73
+ zh: '操作指南',
74
+ ru: 'Руководства',
75
+ },
76
+ {
77
+ en: 'How To',
78
+ zh: '实用指南',
79
+ ru: 'Как сделать',
80
+ },
81
+ {
82
+ en: 'Release Notes',
83
+ zh: '发版日志',
84
+ ru: 'Примечания к выпуску',
85
+ },
86
+ {
87
+ en: 'API Reference',
88
+ zh: 'API 参考',
89
+ ru: 'Справочник API',
90
+ },
91
+ {
92
+ en: 'FAQ',
93
+ zh: '常见问题',
94
+ ru: 'Часто задаваемые вопросы',
95
+ },
96
+ {
97
+ en: 'Trouble Shooting',
98
+ zh: '故障排除',
99
+ ru: 'Устранение неполадок',
100
+ },
101
+ ];
30
102
  export const UNVERSIONED = 'unversioned';
31
103
  export const UNVERSIONED_PREFIX = `${UNVERSIONED}-`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alauda/doom",
3
- "version": "1.1.2",
3
+ "version": "1.2.1",
4
4
  "type": "module",
5
5
  "description": "Doctor Doom making docs.",
6
6
  "repository": "git+https://github.com/alauda/doom.git",
@@ -35,7 +35,7 @@
35
35
  ],
36
36
  "dependencies": {
37
37
  "@cspell/eslint-plugin": "^8.19.4 || ^9.0.2",
38
- "@eslint-react/eslint-plugin": "^1.51.2",
38
+ "@eslint-react/eslint-plugin": "^1.51.3",
39
39
  "@inquirer/prompts": "^7.5.3",
40
40
  "@openapi-contrib/openapi-schema-to-json-schema": "^5.1.0",
41
41
  "@playwright/browser-chromium": "^1.52.0",
@@ -43,9 +43,9 @@
43
43
  "@rsbuild/plugin-sass": "^1.3.2",
44
44
  "@rsbuild/plugin-svgr": "^1.2.0",
45
45
  "@rsbuild/plugin-yaml": "^1.0.2",
46
- "@rspress/core": "2.0.0-beta.11",
47
- "@rspress/plugin-algolia": "2.0.0-beta.11",
48
- "@rspress/plugin-llms": "^2.0.0-beta.11",
46
+ "@rspress/core": "https://pkg.pr.new/@rspress/core@6b02230",
47
+ "@rspress/plugin-algolia": "https://pkg.pr.new/@rspress/plugin-algolia@6b02230",
48
+ "@rspress/plugin-llms": "https://pkg.pr.new/@rspress/plugin-llms@6b02230",
49
49
  "@shikijs/transformers": "^3.6.0",
50
50
  "@total-typescript/ts-reset": "^0.6.1",
51
51
  "chokidar": "^4.0.3",
@@ -60,7 +60,7 @@
60
60
  "mdast-util-mdx": "^3.0.0",
61
61
  "mdast-util-mdx-jsx": "^3.2.0",
62
62
  "mermaid": "^11.6.0",
63
- "openai": "^5.1.1",
63
+ "openai": "^5.3.0",
64
64
  "openapi-types": "^12.1.3",
65
65
  "p-ratelimit": "^1.0.1",
66
66
  "pdf-lib": "^1.17.1",
@@ -79,7 +79,7 @@
79
79
  "tinyglobby": "^0.2.14",
80
80
  "type-fest": "^4.41.0",
81
81
  "typescript": "^5.8.3",
82
- "typescript-eslint": "^8.33.1",
82
+ "typescript-eslint": "^8.34.0",
83
83
  "x-fetch": "^0.2.6",
84
84
  "yaml": "^2.8.0",
85
85
  "yoctocolors": "^2.1.1"