docs/.vitepress/theme/composables/search/translation.ts

ba4f23d3bab9e2bb3b8efdb22317c8cc8f353ec5
wotaku/docs/.vitepress/theme/composables/search/translation.ts history · blame · raw

60 lines · 1899 bytes

2 symbols in this file
 1import { useData } from './use-data'
 2
 3/**
 4 * @param themeObject Can be an object with `translations` and `locales` properties
 5 */
 6export function createSearchTranslate(
 7  defaultTranslations: Record<string, any>
 8): (key: string) => string {
 9  const { localeIndex, theme } = useData()
10
11  function translate(key: string): string {
12    const keyPath = key.split('.')
13    const themeObject = theme.value.search?.options
14
15    const isObject = themeObject && typeof themeObject === 'object'
16    const locales =
17      (isObject && themeObject.locales?.[localeIndex.value]?.translations) ||
18      null
19    const translations = (isObject && themeObject.translations) || null
20
21    let localeResult: Record<string, any> | null = locales
22    let translationResult: Record<string, any> | null = translations
23    let defaultResult: Record<string, any> | null = defaultTranslations
24
25    const lastKey = keyPath.pop()!
26    for (const k of keyPath) {
27      let fallbackResult: Record<string, any> | null = null
28      const foundInFallback: any = defaultResult?.[k]
29      if (foundInFallback) {
30        fallbackResult = defaultResult = foundInFallback
31      }
32      const foundInTranslation: any = translationResult?.[k]
33      if (foundInTranslation) {
34        fallbackResult = translationResult = foundInTranslation
35      }
36      const foundInLocale: any = localeResult?.[k]
37      if (foundInLocale) {
38        fallbackResult = localeResult = foundInLocale
39      }
40      // Put fallback into unresolved results
41      if (!foundInFallback) {
42        defaultResult = fallbackResult
43      }
44      if (!foundInTranslation) {
45        translationResult = fallbackResult
46      }
47      if (!foundInLocale) {
48        localeResult = fallbackResult
49      }
50    }
51    return (
52      localeResult?.[lastKey] ??
53        translationResult?.[lastKey] ??
54        defaultResult?.[lastKey] ??
55        ''
56    )
57  }
58
59  return translate
60}