dify/web/context/i18n.ts

53 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

import type { Locale } from '@/i18n-config/language'
import type { DocPathWithoutLang } from '@/types/doc-paths'
import { useTranslation } from '#i18n'
2026-01-30 09:30:24 +00:00
import { useCallback } from 'react'
import { getDocLanguage, getLanguage, getPricingPageLanguage } from '@/i18n-config/language'
import { apiReferencePathTranslations } from '@/types/doc-paths'
2023-05-15 00:51:32 +00:00
export const useLocale = () => {
const { i18n } = useTranslation()
return i18n.language as Locale
2023-05-15 00:51:32 +00:00
}
export const useGetLanguage = () => {
const locale = useLocale()
return getLanguage(locale)
}
export const useGetPricingPageLanguage = () => {
const locale = useLocale()
return getPricingPageLanguage(locale)
}
export const defaultDocBaseUrl = 'https://docs.dify.ai'
export type DocPathMap = Partial<Record<Locale, DocPathWithoutLang>>
export const useDocLink = (baseUrl?: string): ((path?: DocPathWithoutLang, pathMap?: DocPathMap) => string) => {
let baseDocUrl = baseUrl || defaultDocBaseUrl
baseDocUrl = (baseDocUrl.endsWith('/')) ? baseDocUrl.slice(0, -1) : baseDocUrl
const locale = useLocale()
2026-01-30 09:30:24 +00:00
return useCallback(
(path?: DocPathWithoutLang, pathMap?: DocPathMap): string => {
const docLanguage = getDocLanguage(locale)
const pathUrl = path || ''
let targetPath = (pathMap) ? pathMap[locale] || pathUrl : pathUrl
let languagePrefix = `/${docLanguage}`
if (targetPath.startsWith('/api-reference/')) {
languagePrefix = ''
if (docLanguage !== 'en') {
const translatedPath = apiReferencePathTranslations[targetPath]?.[docLanguage]
if (translatedPath) {
targetPath = translatedPath
}
2026-01-30 09:30:24 +00:00
}
}
2026-01-30 09:30:24 +00:00
return `${baseDocUrl}${languagePrefix}${targetPath}`
},
[baseDocUrl, locale],
)
}