fix(i18n): localize encoded exact links

This commit is contained in:
pku-xht
2026-08-19 03:09:49 +08:00
parent b7e195a7e6
commit 2c94ec6cd3
2 changed files with 30 additions and 2 deletions
+16
View File
@@ -69,6 +69,22 @@ describe('translation link locale validation', () => {
}])
})
it('rewrites an encoded exact filename without changing its query or fragment suffix', () => {
const root = fixture()
const input = '[概览](reference%2Emd?view=full&mode=all#overview)\n'
expect(translationLinkLocaleViolations(
input,
linkContext(root, 'docs/guide.zh.md'),
)[0]).toMatchObject({
url: 'reference%2Emd?view=full&mode=all#overview',
expectedUrl: 'reference.zh.md?view=full&mode=all#overview',
})
expect(rewriteTranslationLinkLocales(input, linkContext(root, 'docs/guide.zh.md'))).toEqual({
content: '[概览](reference.zh.md?view=full&mode=all#overview)\n',
rewritten: 1,
})
})
it('accepts the target-locale sibling and an out-of-scope target with its own sibling', () => {
const root = fixture()
expect(translationLinkLocaleViolations(
+14 -2
View File
@@ -143,15 +143,27 @@ function translationPairTarget(targetPath: string, context: TranslationLinkConte
return { source, zh }
}
function relativeExpectedPath(
context: TranslationLinkContext,
expectedPath: string,
rawPath: string,
): string {
const relative = posix.relative(posix.dirname(context.sourcePath), expectedPath)
const encoded = encodeURI(relative)
return rawPath.startsWith('./') && !encoded.startsWith('.') ? `./${encoded}` : encoded
}
function expectedLocalePath(
rawPath: string,
locale: 'en' | 'zh',
context: TranslationLinkContext,
expectedPath: string,
): string {
if (locale === 'zh' && rawPath.endsWith('.md') && !rawPath.endsWith('.zh.md')) {
return rawPath.replace(/\.md$/, '.zh.md')
}
if (locale === 'en' && rawPath.endsWith('.zh.md')) return rawPath.replace(/\.zh\.md$/, '.md')
return rawPath
return relativeExpectedPath(context, expectedPath, rawPath)
}
function resolveTranslationLink(
@@ -174,7 +186,7 @@ function resolveTranslationLink(
targetPath,
suffix: authored.suffix,
expectedPath,
expectedUrl: `${expectedLocalePath(authored.path, locale)}${authored.suffix}`,
expectedUrl: `${expectedLocalePath(authored.path, locale, context, expectedPath)}${authored.suffix}`,
locale,
}
}