Sfoglia il codice sorgente

fix(i18n): localize encoded exact links

pku-xht 3 settimane fa
parent
commit
2c94ec6cd3
2 ha cambiato i file con 30 aggiunte e 2 eliminazioni
  1. 16 0
      scripts/translation-links.spec.ts
  2. 14 2
      scripts/translation-links.ts

+ 16 - 0
scripts/translation-links.spec.ts

@@ -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
scripts/translation-links.ts

@@ -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,
   }
 }