dify/web/context/i18n.ts

47 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

import {
createContext,
useContext,
} from 'use-context-selector'
2023-05-15 08:51:32 +08:00
import type { Locale } from '@/i18n'
import { getDocLanguage, getLanguage, getPricingPageLanguage } from '@/i18n/language'
import { noop } from 'lodash-es'
2023-05-15 08:51:32 +08:00
type II18NContext = {
locale: Locale
i18n: Record<string, any>
setLocaleOnClient: (_lang: Locale, _reloadPage?: boolean) => void
2023-05-15 08:51:32 +08:00
}
const I18NContext = createContext<II18NContext>({
2024-02-23 14:31:06 +08:00
locale: 'en-US',
2023-05-15 08:51:32 +08:00
i18n: {},
setLocaleOnClient: noop,
2023-05-15 08:51:32 +08:00
})
export const useI18N = () => useContext(I18NContext)
export const useGetLanguage = () => {
const { locale } = useI18N()
return getLanguage(locale)
}
export const useGetPricingPageLanguage = () => {
const { locale } = useI18N()
return getPricingPageLanguage(locale)
}
const defaultDocBaseUrl = 'https://docs.dify.ai'
export const useDocLink = (baseUrl?: string): ((path?: string, pathMap?: { [index: string]: string }) => string) => {
let baseDocUrl = baseUrl || defaultDocBaseUrl
baseDocUrl = (baseDocUrl.endsWith('/')) ? baseDocUrl.slice(0, -1) : baseDocUrl
const { locale } = useI18N()
const docLanguage = getDocLanguage(locale)
return (path?: string, pathMap?: { [index: string]: string }): string => {
const pathUrl = path || ''
let targetPath = (pathMap) ? pathMap[locale] || pathUrl : pathUrl
targetPath = (targetPath.startsWith('/')) ? targetPath.slice(1) : targetPath
return `${baseDocUrl}/${docLanguage}/${targetPath}`
}
}
2023-05-15 08:51:32 +08:00
export default I18NContext