refactor(web): remove useMixedTranslation, better resource loading (#30630)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Stephen Zhou 2026-01-07 13:20:09 +08:00 committed by GitHub
parent 357548ca07
commit e335cd0ef4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
58 changed files with 230 additions and 548 deletions

View File

@ -14,6 +14,14 @@ import { fetchAppList } from '@/service/apps'
import { postMarketplace } from '@/service/base'
import { fetchDatasets } from '@/service/datasets'
// Mock react-i18next before importing modules that use it
vi.mock('react-i18next', () => ({
getI18n: () => ({
t: (key: string) => key,
language: 'en',
}),
}))
// Mock API functions
vi.mock('@/service/base', () => ({
postMarketplace: vi.fn(),

View File

@ -1,14 +1,12 @@
import Marketplace from '@/app/components/plugins/marketplace'
import PluginPage from '@/app/components/plugins/plugin-page'
import PluginsPanel from '@/app/components/plugins/plugin-page/plugins-panel'
import { getLocaleOnServer } from '@/i18n-config/server'
const PluginList = async () => {
const locale = await getLocaleOnServer()
return (
<PluginPage
plugins={<PluginsPanel />}
marketplace={<Marketplace locale={locale} pluginTypeSwitchClassName="top-[60px]" showSearchParams={false} />}
marketplace={<Marketplace pluginTypeSwitchClassName="top-[60px]" showSearchParams={false} />}
/>
)
}

View File

@ -17,7 +17,7 @@ vi.mock('@/hooks/use-app-favicon', () => ({
useAppFavicon: vi.fn(),
}))
vi.mock('@/i18n-config/i18next-config', () => ({
vi.mock('@/i18n-config/client', () => ({
changeLanguage: vi.fn().mockResolvedValue(undefined),
}))

View File

@ -25,7 +25,7 @@ import { useToastContext } from '@/app/components/base/toast'
import { InputVarType } from '@/app/components/workflow/types'
import { useWebAppStore } from '@/context/web-app-context'
import { useAppFavicon } from '@/hooks/use-app-favicon'
import { changeLanguage } from '@/i18n-config/i18next-config'
import { changeLanguage } from '@/i18n-config/client'
import {
delConversation,
pinConversation,

View File

@ -13,7 +13,7 @@ import { shareQueryKeys } from '@/service/use-share'
import { CONVERSATION_ID_INFO } from '../constants'
import { useEmbeddedChatbot } from './hooks'
vi.mock('@/i18n-config/i18next-config', () => ({
vi.mock('@/i18n-config/client', () => ({
changeLanguage: vi.fn().mockResolvedValue(undefined),
}))

View File

@ -23,7 +23,7 @@ import { useToastContext } from '@/app/components/base/toast'
import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
import { InputVarType } from '@/app/components/workflow/types'
import { useWebAppStore } from '@/context/web-app-context'
import { changeLanguage } from '@/i18n-config/i18next-config'
import { changeLanguage } from '@/i18n-config/client'
import { updateFeedback } from '@/service/share'
import {
useInvalidateShareConversations,

View File

@ -1,7 +1,7 @@
import type { SlashCommandHandler } from './types'
import { RiUser3Line } from '@remixicon/react'
import * as React from 'react'
import i18n from '@/i18n-config/i18next-config'
import { getI18n } from 'react-i18next'
import { registerCommands, unregisterCommands } from './command-bus'
// Account command dependency types - no external dependencies needed
@ -21,6 +21,7 @@ export const accountCommand: SlashCommandHandler<AccountDeps> = {
},
async search(args: string, locale: string = 'en') {
const i18n = getI18n()
return [{
id: 'account',
title: i18n.t('account.account', { ns: 'common', lng: locale }),

View File

@ -1,7 +1,7 @@
import type { SlashCommandHandler } from './types'
import { RiDiscordLine } from '@remixicon/react'
import * as React from 'react'
import i18n from '@/i18n-config/i18next-config'
import { getI18n } from 'react-i18next'
import { registerCommands, unregisterCommands } from './command-bus'
// Community command dependency types
@ -22,6 +22,7 @@ export const communityCommand: SlashCommandHandler<CommunityDeps> = {
},
async search(args: string, locale: string = 'en') {
const i18n = getI18n()
return [{
id: 'community',
title: i18n.t('userProfile.community', { ns: 'common', lng: locale }),

View File

@ -1,8 +1,8 @@
import type { SlashCommandHandler } from './types'
import { RiBookOpenLine } from '@remixicon/react'
import * as React from 'react'
import { getI18n } from 'react-i18next'
import { defaultDocBaseUrl } from '@/context/i18n'
import i18n from '@/i18n-config/i18next-config'
import { getDocLanguage } from '@/i18n-config/language'
import { registerCommands, unregisterCommands } from './command-bus'
@ -19,6 +19,7 @@ export const docsCommand: SlashCommandHandler<DocDeps> = {
// Direct execution function
execute: () => {
const i18n = getI18n()
const currentLocale = i18n.language
const docLanguage = getDocLanguage(currentLocale)
const url = `${defaultDocBaseUrl}/${docLanguage}`
@ -26,6 +27,7 @@ export const docsCommand: SlashCommandHandler<DocDeps> = {
},
async search(args: string, locale: string = 'en') {
const i18n = getI18n()
return [{
id: 'doc',
title: i18n.t('userProfile.helpCenter', { ns: 'common', lng: locale }),
@ -41,6 +43,7 @@ export const docsCommand: SlashCommandHandler<DocDeps> = {
},
register(_deps: DocDeps) {
const i18n = getI18n()
registerCommands({
'navigation.doc': async (_args) => {
// Get the current language from i18n

View File

@ -1,7 +1,7 @@
import type { SlashCommandHandler } from './types'
import { RiFeedbackLine } from '@remixicon/react'
import * as React from 'react'
import i18n from '@/i18n-config/i18next-config'
import { getI18n } from 'react-i18next'
import { registerCommands, unregisterCommands } from './command-bus'
// Forum command dependency types
@ -22,6 +22,7 @@ export const forumCommand: SlashCommandHandler<ForumDeps> = {
},
async search(args: string, locale: string = 'en') {
const i18n = getI18n()
return [{
id: 'forum',
title: i18n.t('userProfile.forum', { ns: 'common', lng: locale }),

View File

@ -1,6 +1,6 @@
import type { CommandSearchResult } from '../types'
import type { SlashCommandHandler } from './types'
import i18n from '@/i18n-config/i18next-config'
import { getI18n } from 'react-i18next'
import { languages } from '@/i18n-config/language'
import { registerCommands, unregisterCommands } from './command-bus'
@ -14,6 +14,7 @@ const buildLanguageCommands = (query: string): CommandSearchResult[] => {
const list = languages.filter(item => item.supported && (
!q || item.name.toLowerCase().includes(q) || String(item.value).toLowerCase().includes(q)
))
const i18n = getI18n()
return list.map(item => ({
id: `lang-${item.value}`,
title: item.name,

View File

@ -2,8 +2,8 @@
import type { ActionItem } from '../types'
import { useTheme } from 'next-themes'
import { useEffect } from 'react'
import { getI18n } from 'react-i18next'
import { setLocaleOnClient } from '@/i18n-config'
import i18n from '@/i18n-config/i18next-config'
import { accountCommand } from './account'
import { executeCommand } from './command-bus'
import { communityCommand } from './community'
@ -14,6 +14,8 @@ import { slashCommandRegistry } from './registry'
import { themeCommand } from './theme'
import { zenCommand } from './zen'
const i18n = getI18n()
export const slashAction: ActionItem = {
key: '/',
shortcut: '/',

View File

@ -2,7 +2,7 @@ import type { CommandSearchResult } from '../types'
import type { SlashCommandHandler } from './types'
import { RiComputerLine, RiMoonLine, RiSunLine } from '@remixicon/react'
import * as React from 'react'
import i18n from '@/i18n-config/i18next-config'
import { getI18n } from 'react-i18next'
import { registerCommands, unregisterCommands } from './command-bus'
// Theme dependency types
@ -32,6 +32,7 @@ const THEME_ITEMS = [
] as const
const buildThemeCommands = (query: string, locale?: string): CommandSearchResult[] => {
const i18n = getI18n()
const q = query.toLowerCase()
const list = THEME_ITEMS.filter(item =>
!q

View File

@ -1,8 +1,8 @@
import type { SlashCommandHandler } from './types'
import { RiFullscreenLine } from '@remixicon/react'
import * as React from 'react'
import { getI18n } from 'react-i18next'
import { isInWorkflowPage } from '@/app/components/workflow/constants'
import i18n from '@/i18n-config/i18next-config'
import { registerCommands, unregisterCommands } from './command-bus'
// Zen command dependency types - no external dependencies needed
@ -32,6 +32,7 @@ export const zenCommand: SlashCommandHandler<ZenDeps> = {
execute: toggleZenMode,
async search(_args: string, locale: string = 'en') {
const i18n = getI18n()
return [{
id: 'zen',
title: i18n.t('gotoAnything.actions.zenTitle', { ns: 'app', lng: locale }) || 'Zen Mode',

View File

@ -15,7 +15,6 @@ import Divider from '@/app/components/base/divider'
import Loading from '@/app/components/base/loading'
import List from '@/app/components/plugins/marketplace/list'
import ProviderCard from '@/app/components/plugins/provider-card'
import { getLocaleOnClient } from '@/i18n-config'
import { cn } from '@/utils/classnames'
import { getMarketplaceUrl } from '@/utils/var'
import {
@ -33,7 +32,6 @@ const InstallFromMarketplace = ({
const { t } = useTranslation()
const { theme } = useTheme()
const [collapse, setCollapse] = useState(false)
const locale = getLocaleOnClient()
const {
plugins: allPlugins,
isLoading: isAllPluginsLoading,
@ -70,7 +68,6 @@ const InstallFromMarketplace = ({
marketplaceCollectionPluginsMap={{}}
plugins={allPlugins}
showInstallButton
locale={locale}
cardContainerClassName="grid grid-cols-2 gap-2"
cardRender={cardRender}
emptyClassName="h-auto"

View File

@ -2,13 +2,13 @@
import type { Item } from '@/app/components/base/select'
import type { Locale } from '@/i18n-config'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import { SimpleSelect } from '@/app/components/base/select'
import { ToastContext } from '@/app/components/base/toast'
import { useAppContext } from '@/context/app-context'
import { useLocale } from '@/context/i18n'
import { setLocaleOnClient } from '@/i18n-config'
import { languages } from '@/i18n-config/language'
@ -25,6 +25,7 @@ export default function LanguagePage() {
const { notify } = useContext(ToastContext)
const [editing, setEditing] = useState(false)
const { t } = useTranslation()
const router = useRouter()
const handleSelectLanguage = async (item: Item) => {
const url = '/account/interface-language'
@ -35,7 +36,8 @@ export default function LanguagePage() {
await updateUserProfile({ url, body: { [bodyKey]: item.value } })
notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })
setLocaleOnClient(item.value.toString() as Locale)
setLocaleOnClient(item.value.toString() as Locale, false)
router.refresh()
}
catch (e) {
notify({ type: 'error', message: (e as Error).message })

View File

@ -14,7 +14,6 @@ import Divider from '@/app/components/base/divider'
import Loading from '@/app/components/base/loading'
import List from '@/app/components/plugins/marketplace/list'
import ProviderCard from '@/app/components/plugins/provider-card'
import { getLocaleOnClient } from '@/i18n-config'
import { cn } from '@/utils/classnames'
import { getMarketplaceUrl } from '@/utils/var'
import {
@ -32,7 +31,6 @@ const InstallFromMarketplace = ({
const { t } = useTranslation()
const { theme } = useTheme()
const [collapse, setCollapse] = useState(false)
const locale = getLocaleOnClient()
const {
plugins: allPlugins,
isLoading: isAllPluginsLoading,
@ -69,7 +67,6 @@ const InstallFromMarketplace = ({
marketplaceCollectionPluginsMap={{}}
plugins={allPlugins}
showInstallButton
locale={locale}
cardContainerClassName="grid grid-cols-2 gap-2"
cardRender={cardRender}
emptyClassName="h-auto"

View File

@ -1,22 +0,0 @@
import * as React from 'react'
import { getLocaleOnServer } from '@/i18n-config/server'
import { ToastProvider } from './base/toast'
import I18N from './i18n'
export type II18NServerProps = {
children: React.ReactNode
}
const I18NServer = async ({
children,
}: II18NServerProps) => {
const locale = await getLocaleOnServer()
return (
<I18N {...{ locale }}>
<ToastProvider>{children}</ToastProvider>
</I18N>
)
}
export default I18NServer

View File

@ -1,45 +0,0 @@
'use client'
import type { FC } from 'react'
import type { Locale } from '@/i18n-config'
import { usePrefetchQuery } from '@tanstack/react-query'
import { useHydrateAtoms } from 'jotai/utils'
import * as React from 'react'
import { useEffect, useState } from 'react'
import { localeAtom } from '@/context/i18n'
import { setLocaleOnClient } from '@/i18n-config'
import { getSystemFeatures } from '@/service/common'
import Loading from './base/loading'
export type II18nProps = {
locale: Locale
children: React.ReactNode
}
const I18n: FC<II18nProps> = ({
locale,
children,
}) => {
useHydrateAtoms([[localeAtom, locale]])
const [loading, setLoading] = useState(true)
usePrefetchQuery({
queryKey: ['systemFeatures'],
queryFn: getSystemFeatures,
})
useEffect(() => {
setLocaleOnClient(locale, false).then(() => {
setLoading(false)
})
}, [locale])
if (loading)
return <div className="flex h-screen w-screen items-center justify-center"><Loading type="app" /></div>
return (
<>
{children}
</>
)
}
export default React.memo(I18n)

View File

@ -1,4 +1,5 @@
import type { FC } from 'react'
import { useTranslation } from '#i18n'
import { RiAlertFill } from '@remixicon/react'
import { camelCase } from 'es-toolkit/string'
import Link from 'next/link'
@ -6,14 +7,12 @@ import * as React from 'react'
import { useMemo } from 'react'
import { Trans } from 'react-i18next'
import { cn } from '@/utils/classnames'
import { useMixedTranslation } from '../marketplace/hooks'
type DeprecationNoticeProps = {
status: 'deleted' | 'active'
deprecatedReason: string
alternativePluginId: string
alternativePluginURL: string
locale?: string
className?: string
innerWrapperClassName?: string
iconWrapperClassName?: string
@ -34,13 +33,12 @@ const DeprecationNotice: FC<DeprecationNoticeProps> = ({
deprecatedReason,
alternativePluginId,
alternativePluginURL,
locale,
className,
innerWrapperClassName,
iconWrapperClassName,
textClassName,
}) => {
const { t } = useMixedTranslation(locale)
const { t } = useTranslation()
const deprecatedReasonKey = useMemo(() => {
if (!deprecatedReason)

View File

@ -502,31 +502,6 @@ describe('Card', () => {
})
})
// ================================
// Locale Tests
// ================================
describe('Locale', () => {
it('should use locale from props when provided', () => {
const plugin = createMockPlugin({
label: { 'en-US': 'English Title', 'zh-Hans': '中文标题' },
})
render(<Card payload={plugin} locale="zh-Hans" />)
expect(screen.getByText('中文标题')).toBeInTheDocument()
})
it('should fallback to default locale when prop locale not found', () => {
const plugin = createMockPlugin({
label: { 'en-US': 'English Title' },
})
render(<Card payload={plugin} locale="fr-FR" />)
expect(screen.getByText('English Title')).toBeInTheDocument()
})
})
// ================================
// Memoization Tests
// ================================

View File

@ -1,15 +1,13 @@
'use client'
import type { Plugin } from '../types'
import type { Locale } from '@/i18n-config'
import { useTranslation } from '#i18n'
import { RiAlertFill } from '@remixicon/react'
import * as React from 'react'
import { useMixedTranslation } from '@/app/components/plugins/marketplace/hooks'
import { useGetLanguage } from '@/context/i18n'
import useTheme from '@/hooks/use-theme'
import {
renderI18nObject,
} from '@/i18n-config'
import { getLanguage } from '@/i18n-config/language'
import { Theme } from '@/types/app'
import { cn } from '@/utils/classnames'
import Partner from '../base/badges/partner'
@ -33,7 +31,6 @@ export type Props = {
footer?: React.ReactNode
isLoading?: boolean
loadingFileName?: string
locale?: Locale
limitedInstall?: boolean
}
@ -48,13 +45,11 @@ const Card = ({
footer,
isLoading = false,
loadingFileName,
locale: localeFromProps,
limitedInstall = false,
}: Props) => {
const defaultLocale = useGetLanguage()
const locale = localeFromProps ? getLanguage(localeFromProps) : defaultLocale
const { t } = useMixedTranslation(localeFromProps)
const { categoriesMap } = useCategories(t, true)
const locale = useGetLanguage()
const { t } = useTranslation()
const { categoriesMap } = useCategories(true)
const { category, type, name, org, label, brief, icon, icon_dark, verified, badges = [] } = payload
const { theme } = useTheme()
const iconSrc = theme === Theme.dark && icon_dark ? icon_dark : icon

View File

@ -1,4 +1,3 @@
import type { TFunction } from 'i18next'
import type { CategoryKey, TagKey } from './constants'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
@ -13,9 +12,8 @@ export type Tag = {
label: string
}
export const useTags = (translateFromOut?: TFunction) => {
const { t: translation } = useTranslation()
const t = translateFromOut || translation
export const useTags = () => {
const { t } = useTranslation()
const tags = useMemo(() => {
return tagKeys.map((tag) => {
@ -53,9 +51,8 @@ type Category = {
label: string
}
export const useCategories = (translateFromOut?: TFunction, isSingle?: boolean) => {
const { t: translation } = useTranslation()
const t = translateFromOut || translation
export const useCategories = (isSingle?: boolean) => {
const { t } = useTranslation()
const categories = useMemo(() => {
return categoryKeys.map((category) => {

View File

@ -7,9 +7,9 @@ import Line from './line'
// Mock external dependencies only
// ================================
// Mock useMixedTranslation hook
vi.mock('../hooks', () => ({
useMixedTranslation: (_locale?: string) => ({
// Mock i18n translation hook
vi.mock('#i18n', () => ({
useTranslation: () => ({
t: (key: string, options?: { ns?: string }) => {
// Build full key with namespace prefix if provided
const fullKey = options?.ns ? `${options.ns}.${key}` : key
@ -471,36 +471,6 @@ describe('Empty', () => {
})
})
// ================================
// Locale Prop Tests
// ================================
describe('Locale Prop', () => {
it('should pass locale to useMixedTranslation', () => {
render(<Empty locale="zh-CN" />)
// Translation should still work
expect(screen.getByText('No plugin found')).toBeInTheDocument()
})
it('should handle undefined locale', () => {
render(<Empty locale={undefined} />)
expect(screen.getByText('No plugin found')).toBeInTheDocument()
})
it('should handle en-US locale', () => {
render(<Empty locale="en-US" />)
expect(screen.getByText('No plugin found')).toBeInTheDocument()
})
it('should handle ja-JP locale', () => {
render(<Empty locale="ja-JP" />)
expect(screen.getByText('No plugin found')).toBeInTheDocument()
})
})
// ================================
// Placeholder Cards Layout Tests
// ================================
@ -634,7 +604,6 @@ describe('Empty', () => {
text="Custom message"
lightCard
className="custom-wrapper"
locale="en-US"
/>,
)
@ -695,12 +664,6 @@ describe('Empty', () => {
expect(container.querySelector('.only-class')).toBeInTheDocument()
})
it('should render with only locale prop', () => {
render(<Empty locale="zh-CN" />)
expect(screen.getByText('No plugin found')).toBeInTheDocument()
})
it('should handle text with unicode characters', () => {
render(<Empty text="没有找到插件 🔍" />)
@ -813,7 +776,7 @@ describe('Empty and Line Integration', () => {
})
it('should render complete Empty component structure', () => {
const { container } = render(<Empty text="Test" lightCard className="test" locale="en-US" />)
const { container } = render(<Empty text="Test" lightCard className="test" />)
// Container
expect(container.querySelector('.test')).toBeInTheDocument()

View File

@ -1,6 +1,6 @@
'use client'
import { useTranslation } from '#i18n'
import { Group } from '@/app/components/base/icons/src/vender/other'
import { useMixedTranslation } from '@/app/components/plugins/marketplace/hooks'
import { cn } from '@/utils/classnames'
import Line from './line'
@ -8,16 +8,14 @@ type Props = {
text?: string
lightCard?: boolean
className?: string
locale?: string
}
const Empty = ({
text,
lightCard,
className,
locale,
}: Props) => {
const { t } = useMixedTranslation(locale)
const { t } = useTranslation()
return (
<div

View File

@ -18,8 +18,6 @@ import {
useEffect,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import i18n from '@/i18n-config/i18next-config'
import { postMarketplace } from '@/service/base'
import { SCROLL_BOTTOM_THRESHOLD } from './constants'
import {
@ -218,21 +216,6 @@ export const useMarketplacePlugins = () => {
}
}
/**
* ! Support zh-Hans, pt-BR, ja-JP and en-US for Marketplace page
* ! For other languages, use en-US as fallback
*/
export const useMixedTranslation = (localeFromOuter?: string) => {
let t = useTranslation().t
if (localeFromOuter)
t = i18n.getFixedT(localeFromOuter)
return {
t,
}
}
export const useMarketplaceContainerScroll = (
callback: () => void,
scrollContainerId = 'marketplace-container',

View File

@ -11,7 +11,6 @@ import { PluginCategoryEnum } from '@/app/components/plugins/types'
// Note: Import after mocks are set up
import { DEFAULT_SORT, SCROLL_BOTTOM_THRESHOLD } from './constants'
import { MarketplaceContext, MarketplaceContextProvider, useMarketplaceContext } from './context'
import { useMixedTranslation } from './hooks'
import PluginTypeSwitch, { PLUGIN_TYPE_SEARCH_MAP } from './plugin-type-switch'
import StickySearchAndSwitchWrapper from './sticky-search-and-switch-wrapper'
import {
@ -602,48 +601,6 @@ describe('utils', () => {
})
})
// ================================
// Hooks Tests
// ================================
describe('hooks', () => {
describe('useMixedTranslation', () => {
it('should return translation function', () => {
const { result } = renderHook(() => useMixedTranslation())
expect(result.current.t).toBeDefined()
expect(typeof result.current.t).toBe('function')
})
it('should return translation key when no translation found', () => {
const { result } = renderHook(() => useMixedTranslation())
// The global mock returns key with namespace prefix
expect(result.current.t('category.all', { ns: 'plugin' })).toBe('plugin.category.all')
})
it('should use locale from outer when provided', () => {
const { result } = renderHook(() => useMixedTranslation('zh-Hans'))
expect(result.current.t).toBeDefined()
})
it('should handle different locale values', () => {
const locales = ['en-US', 'zh-Hans', 'ja-JP', 'pt-BR']
locales.forEach((locale) => {
const { result } = renderHook(() => useMixedTranslation(locale))
expect(result.current.t).toBeDefined()
expect(typeof result.current.t).toBe('function')
})
})
it('should use getFixedT when localeFromOuter is provided', () => {
const { result } = renderHook(() => useMixedTranslation('fr-FR'))
// The global mock returns key with namespace prefix
expect(result.current.t('search', { ns: 'plugin' })).toBe('plugin.search')
})
})
})
// ================================
// useMarketplaceCollectionsAndPlugins Tests
// ================================
@ -2088,17 +2045,6 @@ describe('StickySearchAndSwitchWrapper', () => {
})
describe('Props', () => {
it('should accept locale prop', () => {
render(
<MarketplaceContextProvider>
<StickySearchAndSwitchWrapper locale="zh-Hans" />
</MarketplaceContextProvider>,
)
// Component should render without errors
expect(screen.getByTestId('portal-elem')).toBeInTheDocument()
})
it('should accept showSearchParams prop', () => {
render(
<MarketplaceContextProvider>

View File

@ -1,6 +1,5 @@
import type { MarketplaceCollection, SearchParams } from './types'
import type { Plugin } from '@/app/components/plugins/types'
import type { Locale } from '@/i18n-config'
import { TanstackQueryInitializer } from '@/context/query-client'
import { MarketplaceContextProvider } from './context'
import Description from './description'
@ -9,7 +8,6 @@ import StickySearchAndSwitchWrapper from './sticky-search-and-switch-wrapper'
import { getMarketplaceCollectionsAndPlugins } from './utils'
type MarketplaceProps = {
locale: Locale
showInstallButton?: boolean
shouldExclude?: boolean
searchParams?: SearchParams
@ -18,7 +16,6 @@ type MarketplaceProps = {
showSearchParams?: boolean
}
const Marketplace = async ({
locale,
showInstallButton = true,
shouldExclude,
searchParams,
@ -44,12 +41,10 @@ const Marketplace = async ({
>
<Description />
<StickySearchAndSwitchWrapper
locale={locale}
pluginTypeSwitchClassName={pluginTypeSwitchClassName}
showSearchParams={showSearchParams}
/>
<ListWrapper
locale={locale}
marketplaceCollections={marketplaceCollections}
marketplaceCollectionPluginsMap={marketplaceCollectionPluginsMap}
showInstallButton={showInstallButton}

View File

@ -1,6 +1,6 @@
'use client'
import type { Plugin } from '@/app/components/plugins/types'
import type { Locale } from '@/i18n-config'
import { useLocale, useTranslation } from '#i18n'
import { RiArrowRightUpLine } from '@remixicon/react'
import { useBoolean } from 'ahooks'
import { useTheme } from 'next-themes'
@ -11,34 +11,30 @@ import Card from '@/app/components/plugins/card'
import CardMoreInfo from '@/app/components/plugins/card/card-more-info'
import { useTags } from '@/app/components/plugins/hooks'
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
import { useMixedTranslation } from '@/app/components/plugins/marketplace/hooks'
import { useLocale } from '@/context/i18n'
import { getPluginDetailLinkInMarketplace, getPluginLinkInMarketplace } from '../utils'
type CardWrapperProps = {
plugin: Plugin
showInstallButton?: boolean
locale?: Locale
}
const CardWrapperComponent = ({
plugin,
showInstallButton,
locale,
}: CardWrapperProps) => {
const { t } = useMixedTranslation(locale)
const { t } = useTranslation()
const { theme } = useTheme()
const [isShowInstallFromMarketplace, {
setTrue: showInstallFromMarketplace,
setFalse: hideInstallFromMarketplace,
}] = useBoolean(false)
const localeFromLocale = useLocale()
const { getTagLabel } = useTags(t)
const locale = useLocale()
const { getTagLabel } = useTags()
// Memoize marketplace link params to prevent unnecessary re-renders
const marketplaceLinkParams = useMemo(() => ({
language: localeFromLocale,
language: locale,
theme,
}), [localeFromLocale, theme])
}), [locale, theme])
// Memoize tag labels to prevent recreating array on every render
const tagLabels = useMemo(() =>
@ -52,7 +48,6 @@ const CardWrapperComponent = ({
<Card
key={plugin.name}
payload={plugin}
locale={locale}
footer={(
<CardMoreInfo
downloadCount={plugin.install_count}
@ -99,7 +94,6 @@ const CardWrapperComponent = ({
<Card
key={plugin.name}
payload={plugin}
locale={locale}
footer={(
<CardMoreInfo
downloadCount={plugin.install_count}

View File

@ -1,6 +1,5 @@
import type { MarketplaceCollection, SearchParamsFromCollection } from '../types'
import type { Plugin } from '@/app/components/plugins/types'
import type { Locale } from '@/i18n-config'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
@ -12,9 +11,9 @@ import ListWrapper from './list-wrapper'
// Mock External Dependencies Only
// ================================
// Mock useMixedTranslation hook
vi.mock('../hooks', () => ({
useMixedTranslation: (_locale?: string) => ({
// Mock i18n translation hook
vi.mock('#i18n', () => ({
useTranslation: () => ({
t: (key: string, options?: { ns?: string, num?: number }) => {
// Build full key with namespace prefix if provided
const fullKey = options?.ns ? `${options.ns}.${key}` : key
@ -28,6 +27,7 @@ vi.mock('../hooks', () => ({
return translations[fullKey] || key
},
}),
useLocale: () => 'en-US',
}))
// Mock useMarketplaceContext with controllable values
@ -148,15 +148,15 @@ vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () =
// Mock SortDropdown component
vi.mock('../sort-dropdown', () => ({
default: ({ locale }: { locale: Locale }) => (
<div data-testid="sort-dropdown" data-locale={locale}>Sort</div>
default: () => (
<div data-testid="sort-dropdown">Sort</div>
),
}))
// Mock Empty component
vi.mock('../empty', () => ({
default: ({ className, locale }: { className?: string, locale?: string }) => (
<div data-testid="empty-component" className={className} data-locale={locale}>
default: ({ className }: { className?: string }) => (
<div data-testid="empty-component" className={className}>
No plugins found
</div>
),
@ -233,7 +233,6 @@ describe('List', () => {
marketplaceCollectionPluginsMap: {} as Record<string, Plugin[]>,
plugins: undefined,
showInstallButton: false,
locale: 'en-US' as Locale,
cardContainerClassName: '',
cardRender: undefined,
onMoreClick: undefined,
@ -351,18 +350,6 @@ describe('List', () => {
expect(screen.getByTestId('empty-component')).toHaveClass('custom-empty-class')
})
it('should pass locale to Empty component', () => {
render(
<List
{...defaultProps}
plugins={[]}
locale={'zh-CN' as Locale}
/>,
)
expect(screen.getByTestId('empty-component')).toHaveAttribute('data-locale', 'zh-CN')
})
it('should pass showInstallButton to CardWrapper', () => {
const plugins = createMockPluginList(1)
@ -508,7 +495,6 @@ describe('ListWithCollection', () => {
marketplaceCollections: [] as MarketplaceCollection[],
marketplaceCollectionPluginsMap: {} as Record<string, Plugin[]>,
showInstallButton: false,
locale: 'en-US' as Locale,
cardContainerClassName: '',
cardRender: undefined,
onMoreClick: undefined,
@ -820,7 +806,6 @@ describe('ListWrapper', () => {
marketplaceCollections: [] as MarketplaceCollection[],
marketplaceCollectionPluginsMap: {} as Record<string, Plugin[]>,
showInstallButton: false,
locale: 'en-US' as Locale,
}
beforeEach(() => {
@ -901,14 +886,6 @@ describe('ListWrapper', () => {
expect(screen.queryByTestId('sort-dropdown')).not.toBeInTheDocument()
})
it('should pass locale to SortDropdown', () => {
mockContextValues.plugins = createMockPluginList(1)
render(<ListWrapper {...defaultProps} locale={'zh-CN' as Locale} />)
expect(screen.getByTestId('sort-dropdown')).toHaveAttribute('data-locale', 'zh-CN')
})
})
// ================================
@ -1169,7 +1146,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
locale="en-US"
/>,
)
@ -1188,7 +1164,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
locale="en-US"
/>,
)
@ -1209,7 +1184,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={plugins}
locale="en-US"
/>,
)
@ -1231,7 +1205,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
locale="en-US"
/>,
)
@ -1252,7 +1225,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
locale="en-US"
/>,
)
@ -1274,7 +1246,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
locale="en-US"
/>,
)
@ -1293,7 +1264,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
locale="en-US"
/>,
)
@ -1310,7 +1280,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
locale="en-US"
/>,
)
@ -1327,7 +1296,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={true}
locale="en-US"
/>,
)
@ -1354,7 +1322,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={false}
locale="en-US"
/>,
)
@ -1375,7 +1342,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
showInstallButton={false}
locale="en-US"
/>,
)
@ -1390,7 +1356,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
locale="en-US"
/>,
)
@ -1414,7 +1379,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
locale="en-US"
/>,
)
@ -1432,7 +1396,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
locale="en-US"
/>,
)
@ -1450,7 +1413,6 @@ describe('CardWrapper (via List integration)', () => {
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={[plugin]}
locale="en-US"
/>,
)
@ -1482,7 +1444,6 @@ describe('Combined Workflows', () => {
<ListWrapper
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
locale="en-US"
/>,
)
@ -1501,7 +1462,6 @@ describe('Combined Workflows', () => {
<ListWrapper
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
locale="en-US"
/>,
)
@ -1521,7 +1481,6 @@ describe('Combined Workflows', () => {
<ListWrapper
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
locale="en-US"
/>,
)
@ -1535,7 +1494,6 @@ describe('Combined Workflows', () => {
<ListWrapper
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
locale="en-US"
/>,
)
@ -1551,7 +1509,6 @@ describe('Combined Workflows', () => {
<ListWrapper
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
locale="en-US"
/>,
)
@ -1569,7 +1526,6 @@ describe('Combined Workflows', () => {
<ListWrapper
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
locale="en-US"
/>,
)
@ -1601,7 +1557,6 @@ describe('Accessibility', () => {
<ListWithCollection
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
locale="en-US"
/>,
)
@ -1625,7 +1580,6 @@ describe('Accessibility', () => {
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
onMoreClick={onMoreClick}
locale="en-US"
/>,
)
@ -1642,7 +1596,6 @@ describe('Accessibility', () => {
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={plugins}
locale="en-US"
/>,
)
@ -1668,7 +1621,6 @@ describe('Performance', () => {
marketplaceCollections={[]}
marketplaceCollectionPluginsMap={{}}
plugins={plugins}
locale="en-US"
/>,
)
const endTime = performance.now()
@ -1689,7 +1641,6 @@ describe('Performance', () => {
<ListWithCollection
marketplaceCollections={collections}
marketplaceCollectionPluginsMap={pluginsMap}
locale="en-US"
/>,
)
const endTime = performance.now()

View File

@ -1,7 +1,6 @@
'use client'
import type { Plugin } from '../../types'
import type { MarketplaceCollection } from '../types'
import type { Locale } from '@/i18n-config'
import { cn } from '@/utils/classnames'
import Empty from '../empty'
import CardWrapper from './card-wrapper'
@ -12,7 +11,6 @@ type ListProps = {
marketplaceCollectionPluginsMap: Record<string, Plugin[]>
plugins?: Plugin[]
showInstallButton?: boolean
locale: Locale
cardContainerClassName?: string
cardRender?: (plugin: Plugin) => React.JSX.Element | null
onMoreClick?: () => void
@ -23,7 +21,6 @@ const List = ({
marketplaceCollectionPluginsMap,
plugins,
showInstallButton,
locale,
cardContainerClassName,
cardRender,
onMoreClick,
@ -37,7 +34,6 @@ const List = ({
marketplaceCollections={marketplaceCollections}
marketplaceCollectionPluginsMap={marketplaceCollectionPluginsMap}
showInstallButton={showInstallButton}
locale={locale}
cardContainerClassName={cardContainerClassName}
cardRender={cardRender}
onMoreClick={onMoreClick}
@ -61,7 +57,6 @@ const List = ({
key={`${plugin.org}/${plugin.name}`}
plugin={plugin}
showInstallButton={showInstallButton}
locale={locale}
/>
)
})
@ -71,7 +66,7 @@ const List = ({
}
{
plugins && !plugins.length && (
<Empty className={emptyClassName} locale={locale} />
<Empty className={emptyClassName} />
)
}
</>

View File

@ -3,9 +3,8 @@
import type { MarketplaceCollection } from '../types'
import type { SearchParamsFromCollection } from '@/app/components/plugins/marketplace/types'
import type { Plugin } from '@/app/components/plugins/types'
import type { Locale } from '@/i18n-config'
import { useLocale, useTranslation } from '#i18n'
import { RiArrowRightSLine } from '@remixicon/react'
import { useMixedTranslation } from '@/app/components/plugins/marketplace/hooks'
import { getLanguage } from '@/i18n-config/language'
import { cn } from '@/utils/classnames'
import CardWrapper from './card-wrapper'
@ -14,7 +13,6 @@ type ListWithCollectionProps = {
marketplaceCollections: MarketplaceCollection[]
marketplaceCollectionPluginsMap: Record<string, Plugin[]>
showInstallButton?: boolean
locale: Locale
cardContainerClassName?: string
cardRender?: (plugin: Plugin) => React.JSX.Element | null
onMoreClick?: (searchParams?: SearchParamsFromCollection) => void
@ -23,12 +21,12 @@ const ListWithCollection = ({
marketplaceCollections,
marketplaceCollectionPluginsMap,
showInstallButton,
locale,
cardContainerClassName,
cardRender,
onMoreClick,
}: ListWithCollectionProps) => {
const { t } = useMixedTranslation(locale)
const { t } = useTranslation()
const locale = useLocale()
return (
<>
@ -72,7 +70,6 @@ const ListWithCollection = ({
key={plugin.plugin_id}
plugin={plugin}
showInstallButton={showInstallButton}
locale={locale}
/>
)
})

View File

@ -1,10 +1,9 @@
'use client'
import type { Plugin } from '../../types'
import type { MarketplaceCollection } from '../types'
import type { Locale } from '@/i18n-config'
import { useTranslation } from '#i18n'
import { useEffect } from 'react'
import Loading from '@/app/components/base/loading'
import { useMixedTranslation } from '@/app/components/plugins/marketplace/hooks'
import { useMarketplaceContext } from '../context'
import SortDropdown from '../sort-dropdown'
import List from './index'
@ -13,15 +12,13 @@ type ListWrapperProps = {
marketplaceCollections: MarketplaceCollection[]
marketplaceCollectionPluginsMap: Record<string, Plugin[]>
showInstallButton?: boolean
locale: Locale
}
const ListWrapper = ({
marketplaceCollections,
marketplaceCollectionPluginsMap,
showInstallButton,
locale,
}: ListWrapperProps) => {
const { t } = useMixedTranslation(locale)
const { t } = useTranslation()
const plugins = useMarketplaceContext(v => v.plugins)
const pluginsTotal = useMarketplaceContext(v => v.pluginsTotal)
const marketplaceCollectionsFromClient = useMarketplaceContext(v => v.marketplaceCollectionsFromClient)
@ -55,7 +52,7 @@ const ListWrapper = ({
<div className="mb-4 flex items-center pt-3">
<div className="title-xl-semi-bold text-text-primary">{t('marketplace.pluginsResult', { ns: 'plugin', num: pluginsTotal })}</div>
<div className="mx-3 h-3.5 w-[1px] bg-divider-regular"></div>
<SortDropdown locale={locale} />
<SortDropdown />
</div>
)
}
@ -73,7 +70,6 @@ const ListWrapper = ({
marketplaceCollectionPluginsMap={marketplaceCollectionPluginsMapFromClient || marketplaceCollectionPluginsMap}
plugins={plugins}
showInstallButton={showInstallButton}
locale={locale}
onMoreClick={handleMoreClick}
/>
)

View File

@ -1,4 +1,5 @@
'use client'
import { useTranslation } from '#i18n'
import {
RiArchive2Line,
RiBrain2Line,
@ -12,7 +13,6 @@ import { Trigger as TriggerIcon } from '@/app/components/base/icons/src/vender/p
import { cn } from '@/utils/classnames'
import { PluginCategoryEnum } from '../types'
import { useMarketplaceContext } from './context'
import { useMixedTranslation } from './hooks'
export const PLUGIN_TYPE_SEARCH_MAP = {
all: 'all',
@ -25,16 +25,14 @@ export const PLUGIN_TYPE_SEARCH_MAP = {
bundle: 'bundle',
}
type PluginTypeSwitchProps = {
locale?: string
className?: string
showSearchParams?: boolean
}
const PluginTypeSwitch = ({
locale,
className,
showSearchParams,
}: PluginTypeSwitchProps) => {
const { t } = useMixedTranslation(locale)
const { t } = useTranslation()
const activePluginType = useMarketplaceContext(s => s.activePluginType)
const handleActivePluginTypeChange = useMarketplaceContext(s => s.handleActivePluginTypeChange)

View File

@ -10,9 +10,9 @@ import ToolSelectorTrigger from './trigger/tool-selector'
// Mock external dependencies only
// ================================
// Mock useMixedTranslation hook
vi.mock('../hooks', () => ({
useMixedTranslation: (_locale?: string) => ({
// Mock i18n translation hook
vi.mock('#i18n', () => ({
useTranslation: () => ({
t: (key: string, options?: { ns?: string }) => {
// Build full key with namespace prefix if provided
const fullKey = options?.ns ? `${options.ns}.${key}` : key
@ -364,13 +364,6 @@ describe('SearchBox', () => {
expect(container.querySelector('.custom-input-class')).toBeInTheDocument()
})
it('should pass locale to TagsFilter', () => {
render(<SearchBox {...defaultProps} locale="zh-CN" />)
// TagsFilter should be rendered with locale
expect(screen.getByTestId('portal-elem')).toBeInTheDocument()
})
it('should handle empty placeholder', () => {
render(<SearchBox {...defaultProps} placeholder="" />)
@ -449,12 +442,6 @@ describe('SearchBoxWrapper', () => {
expect(screen.getByRole('textbox')).toBeInTheDocument()
})
it('should render with locale prop', () => {
render(<SearchBoxWrapper locale="en-US" />)
expect(screen.getByRole('textbox')).toBeInTheDocument()
})
it('should render in marketplace mode', () => {
const { container } = render(<SearchBoxWrapper />)
@ -500,13 +487,6 @@ describe('SearchBoxWrapper', () => {
expect(screen.getByPlaceholderText('Search plugins')).toBeInTheDocument()
})
it('should pass locale to useMixedTranslation', () => {
render(<SearchBoxWrapper locale="zh-CN" />)
// Translation should still work
expect(screen.getByPlaceholderText('Search plugins')).toBeInTheDocument()
})
})
})
@ -665,12 +645,6 @@ describe('MarketplaceTrigger', () => {
})
describe('Props Variations', () => {
it('should handle locale prop', () => {
render(<MarketplaceTrigger {...defaultProps} locale="zh-CN" />)
expect(screen.getByText('All Tags')).toBeInTheDocument()
})
it('should handle empty tagsMap', () => {
const { container } = render(
<MarketplaceTrigger {...defaultProps} tagsMap={{}} tags={[]} />,
@ -1251,7 +1225,6 @@ describe('Combined Workflows', () => {
supportAddCustomTool
onShowAddCustomCollectionModal={vi.fn()}
placeholder="Search plugins"
locale="en-US"
wrapperClassName="custom-wrapper"
inputClassName="custom-input"
autoFocus={false}

View File

@ -13,7 +13,6 @@ type SearchBoxProps = {
tags: string[]
onTagsChange: (tags: string[]) => void
placeholder?: string
locale?: string
supportAddCustomTool?: boolean
usedInMarketplace?: boolean
onShowAddCustomCollectionModal?: () => void
@ -28,7 +27,6 @@ const SearchBox = ({
tags,
onTagsChange,
placeholder = '',
locale,
usedInMarketplace = false,
supportAddCustomTool,
onShowAddCustomCollectionModal,
@ -49,7 +47,6 @@ const SearchBox = ({
tags={tags}
onTagsChange={onTagsChange}
usedInMarketplace
locale={locale}
/>
<Divider type="vertical" className="mx-1 h-3.5" />
<div className="flex grow items-center gap-x-2 p-1">
@ -109,7 +106,6 @@ const SearchBox = ({
<TagsFilter
tags={tags}
onTagsChange={onTagsChange}
locale={locale}
/>
</>
)

View File

@ -1,16 +1,11 @@
'use client'
import { useTranslation } from '#i18n'
import { useMarketplaceContext } from '../context'
import { useMixedTranslation } from '../hooks'
import SearchBox from './index'
type SearchBoxWrapperProps = {
locale?: string
}
const SearchBoxWrapper = ({
locale,
}: SearchBoxWrapperProps) => {
const { t } = useMixedTranslation(locale)
const SearchBoxWrapper = () => {
const { t } = useTranslation()
const searchPluginText = useMarketplaceContext(v => v.searchPluginText)
const handleSearchPluginTextChange = useMarketplaceContext(v => v.handleSearchPluginTextChange)
const filterPluginTags = useMarketplaceContext(v => v.filterPluginTags)
@ -24,7 +19,6 @@ const SearchBoxWrapper = ({
onSearchChange={handleSearchPluginTextChange}
tags={filterPluginTags}
onTagsChange={handleFilterPluginTagsChange}
locale={locale}
placeholder={t('searchPlugins', { ns: 'plugin' })}
usedInMarketplace
/>

View File

@ -1,5 +1,6 @@
'use client'
import { useTranslation } from '#i18n'
import { useState } from 'react'
import Checkbox from '@/app/components/base/checkbox'
import Input from '@/app/components/base/input'
@ -9,7 +10,6 @@ import {
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import { useTags } from '@/app/components/plugins/hooks'
import { useMixedTranslation } from '@/app/components/plugins/marketplace/hooks'
import MarketplaceTrigger from './trigger/marketplace'
import ToolSelectorTrigger from './trigger/tool-selector'
@ -17,18 +17,16 @@ type TagsFilterProps = {
tags: string[]
onTagsChange: (tags: string[]) => void
usedInMarketplace?: boolean
locale?: string
}
const TagsFilter = ({
tags,
onTagsChange,
usedInMarketplace = false,
locale,
}: TagsFilterProps) => {
const { t } = useMixedTranslation(locale)
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const [searchText, setSearchText] = useState('')
const { tags: options, tagsMap } = useTags(t)
const { tags: options, tagsMap } = useTags()
const filteredOptions = options.filter(option => option.label.toLowerCase().includes(searchText.toLowerCase()))
const handleCheck = (id: string) => {
if (tags.includes(id))
@ -59,7 +57,6 @@ const TagsFilter = ({
open={open}
tags={tags}
tagsMap={tagsMap}
locale={locale}
onTagsChange={onTagsChange}
/>
)

View File

@ -1,15 +1,14 @@
import type { Tag } from '../../../hooks'
import { useTranslation } from '#i18n'
import { RiArrowDownSLine, RiCloseCircleFill, RiFilter3Line } from '@remixicon/react'
import * as React from 'react'
import { cn } from '@/utils/classnames'
import { useMixedTranslation } from '../../hooks'
type MarketplaceTriggerProps = {
selectedTagsLength: number
open: boolean
tags: string[]
tagsMap: Record<string, Tag>
locale?: string
onTagsChange: (tags: string[]) => void
}
@ -18,10 +17,9 @@ const MarketplaceTrigger = ({
open,
tags,
tagsMap,
locale,
onTagsChange,
}: MarketplaceTriggerProps) => {
const { t } = useMixedTranslation(locale)
const { t } = useTranslation()
return (
<div

View File

@ -8,7 +8,7 @@ import SortDropdown from './index'
// Mock external dependencies only
// ================================
// Mock useMixedTranslation hook
// Mock i18n translation hook
const mockTranslation = vi.fn((key: string, options?: { ns?: string }) => {
// Build full key with namespace prefix if provided
const fullKey = options?.ns ? `${options.ns}.${key}` : key
@ -22,8 +22,8 @@ const mockTranslation = vi.fn((key: string, options?: { ns?: string }) => {
return translations[fullKey] || key
})
vi.mock('../hooks', () => ({
useMixedTranslation: (_locale?: string) => ({
vi.mock('#i18n', () => ({
useTranslation: () => ({
t: mockTranslation,
}),
}))
@ -145,36 +145,6 @@ describe('SortDropdown', () => {
})
})
// ================================
// Props Testing
// ================================
describe('Props', () => {
it('should accept locale prop', () => {
render(<SortDropdown locale="zh-CN" />)
expect(screen.getByTestId('portal-wrapper')).toBeInTheDocument()
})
it('should call useMixedTranslation with provided locale', () => {
render(<SortDropdown locale="ja-JP" />)
// Translation function should be called for labels
expect(mockTranslation).toHaveBeenCalledWith('marketplace.sortBy', { ns: 'plugin' })
})
it('should render without locale prop (undefined)', () => {
render(<SortDropdown />)
expect(screen.getByText('Sort by')).toBeInTheDocument()
})
it('should render with empty string locale', () => {
render(<SortDropdown locale="" />)
expect(screen.getByText('Sort by')).toBeInTheDocument()
})
})
// ================================
// State Management Tests
// ================================
@ -618,13 +588,6 @@ describe('SortDropdown', () => {
expect(mockTranslation).toHaveBeenCalledWith('marketplace.sortOption.newlyReleased', { ns: 'plugin' })
expect(mockTranslation).toHaveBeenCalledWith('marketplace.sortOption.firstReleased', { ns: 'plugin' })
})
it('should pass locale to useMixedTranslation', () => {
render(<SortDropdown locale="pt-BR" />)
// Verify component renders with locale
expect(screen.getByTestId('portal-wrapper')).toBeInTheDocument()
})
})
// ================================

View File

@ -1,4 +1,5 @@
'use client'
import { useTranslation } from '#i18n'
import {
RiArrowDownSLine,
RiCheckLine,
@ -9,16 +10,10 @@ import {
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import { useMixedTranslation } from '@/app/components/plugins/marketplace/hooks'
import { useMarketplaceContext } from '../context'
type SortDropdownProps = {
locale?: string
}
const SortDropdown = ({
locale,
}: SortDropdownProps) => {
const { t } = useMixedTranslation(locale)
const SortDropdown = () => {
const { t } = useTranslation()
const options = [
{
value: 'install_count',

View File

@ -5,13 +5,11 @@ import PluginTypeSwitch from './plugin-type-switch'
import SearchBoxWrapper from './search-box/search-box-wrapper'
type StickySearchAndSwitchWrapperProps = {
locale?: string
pluginTypeSwitchClassName?: string
showSearchParams?: boolean
}
const StickySearchAndSwitchWrapper = ({
locale,
pluginTypeSwitchClassName,
showSearchParams,
}: StickySearchAndSwitchWrapperProps) => {
@ -25,9 +23,8 @@ const StickySearchAndSwitchWrapper = ({
pluginTypeSwitchClassName,
)}
>
<SearchBoxWrapper locale={locale} />
<SearchBoxWrapper />
<PluginTypeSwitch
locale={locale}
showSearchParams={showSearchParams}
/>
</div>

View File

@ -44,7 +44,7 @@ const PluginItem: FC<Props> = ({
}) => {
const { t } = useTranslation()
const { theme } = useTheme()
const { categoriesMap } = useCategories(t, true)
const { categoriesMap } = useCategories(true)
const currentPluginID = usePluginPageContext(v => v.currentPluginID)
const setCurrentPluginID = usePluginPageContext(v => v.setCurrentPluginID)
const { refreshPluginList } = useRefreshPluginList()

View File

@ -0,0 +1,21 @@
import { getLocaleOnServer, getResources } from '@/i18n-config/server'
import { I18nClientProvider } from './i18n'
export async function I18nServerProvider({
children,
}: {
children: React.ReactNode
}) {
const locale = await getLocaleOnServer()
const resource = await getResources(locale)
return (
<I18nClientProvider
locale={locale}
resource={resource}
>
{children}
</I18nClientProvider>
)
}

View File

@ -0,0 +1,24 @@
'use client'
import type { Resource } from 'i18next'
import type { Locale } from '@/i18n-config'
import { I18nextProvider } from 'react-i18next'
import { createI18nextInstance } from '@/i18n-config/client'
export function I18nClientProvider({
locale,
resource,
children,
}: {
locale: Locale
resource: Resource
children: React.ReactNode
}) {
const i18n = createI18nextInstance(locale, resource)
return (
<I18nextProvider i18n={i18n}>
{children}
</I18nextProvider>
)
}

View File

@ -32,7 +32,7 @@ import { useWebAppStore } from '@/context/web-app-context'
import { useAppFavicon } from '@/hooks/use-app-favicon'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import useDocumentTitle from '@/hooks/use-document-title'
import { changeLanguage } from '@/i18n-config/i18next-config'
import { changeLanguage } from '@/i18n-config/client'
import { AccessMode } from '@/models/access-control'
import { fetchSavedMessage as doFetchSavedMessage, removeMessage, saveMessage } from '@/service/share'
import { Resolution, TransferMethod } from '@/types/app'

View File

@ -19,7 +19,6 @@ vi.mock('@/app/components/plugins/marketplace/list', () => ({
marketplaceCollectionPluginsMap: Record<string, unknown[]>
plugins?: unknown[]
showInstallButton?: boolean
locale: string
}) => {
listRenderSpy(props)
return <div data-testid="marketplace-list" />
@ -42,10 +41,6 @@ vi.mock('@/utils/var', () => ({
getMarketplaceUrl: vi.fn(() => 'https://marketplace.test/market'),
}))
vi.mock('@/i18n-config', () => ({
getLocaleOnClient: () => 'en',
}))
vi.mock('next-themes', () => ({
useTheme: () => ({ theme: 'light' }),
}))
@ -148,7 +143,6 @@ describe('Marketplace', () => {
expect(screen.getByTestId('marketplace-list')).toBeInTheDocument()
expect(listRenderSpy).toHaveBeenCalledWith(expect.objectContaining({
showInstallButton: true,
locale: 'en',
}))
})
})

View File

@ -1,4 +1,5 @@
import type { useMarketplace } from './hooks'
import { useLocale } from '#i18n'
import {
RiArrowRightUpLine,
RiArrowUpDoubleLine,
@ -7,7 +8,6 @@ import { useTheme } from 'next-themes'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import List from '@/app/components/plugins/marketplace/list'
import { getLocaleOnClient } from '@/i18n-config'
import { getMarketplaceUrl } from '@/utils/var'
type MarketplaceProps = {
@ -24,7 +24,7 @@ const Marketplace = ({
showMarketplacePanel,
marketplaceContext,
}: MarketplaceProps) => {
const locale = getLocaleOnClient()
const locale = useLocale()
const { t } = useTranslation()
const { theme } = useTheme()
const {
@ -104,7 +104,6 @@ const Marketplace = ({
marketplaceCollectionPluginsMap={marketplaceCollectionPluginsMap || {}}
plugins={plugins}
showInstallButton
locale={locale}
/>
)
}

View File

@ -8,9 +8,10 @@ import { TanstackQueryInitializer } from '@/context/query-client'
import { getLocaleOnServer } from '@/i18n-config/server'
import { DatasetAttr } from '@/types/feature'
import { cn } from '@/utils/classnames'
import { ToastProvider } from './components/base/toast'
import BrowserInitializer from './components/browser-initializer'
import { ReactScanLoader } from './components/devtools/react-scan/loader'
import I18nServer from './components/i18n-server'
import { I18nServerProvider } from './components/provider/i18n-server'
import SentryInitializer from './components/sentry-initializer'
import RoutePrefixHandle from './routePrefixHandle'
import './styles/globals.css'
@ -104,11 +105,13 @@ const LocaleLayout = async ({
<BrowserInitializer>
<SentryInitializer>
<TanstackQueryInitializer>
<I18nServer>
<GlobalPublicStoreProvider>
{children}
</GlobalPublicStoreProvider>
</I18nServer>
<I18nServerProvider>
<ToastProvider>
<GlobalPublicStoreProvider>
{children}
</GlobalPublicStoreProvider>
</ToastProvider>
</I18nServerProvider>
</TanstackQueryInitializer>
</SentryInitializer>
</BrowserInitializer>

View File

@ -1,10 +1,10 @@
import type { Locale } from '@/i18n-config/language'
import { atom, useAtomValue } from 'jotai'
import { useTranslation } from '#i18n'
import { getDocLanguage, getLanguage, getPricingPageLanguage } from '@/i18n-config/language'
export const localeAtom = atom<Locale>('en-US')
export const useLocale = () => {
return useAtomValue(localeAtom)
const { i18n } = useTranslation()
return i18n.language as Locale
}
export const useGetLanguage = () => {

35
web/i18n-config/client.ts Normal file
View File

@ -0,0 +1,35 @@
'use client'
import type { Resource } from 'i18next'
import type { Locale } from '.'
import type { NamespaceCamelCase, NamespaceKebabCase } from './resources'
import { kebabCase } from 'es-toolkit/string'
import { createInstance } from 'i18next'
import resourcesToBackend from 'i18next-resources-to-backend'
import { getI18n, initReactI18next } from 'react-i18next'
import { getInitOptions } from './settings'
export function createI18nextInstance(lng: Locale, resources: Resource) {
const instance = createInstance()
instance
.use(initReactI18next)
.use(resourcesToBackend((
language: Locale,
namespace: NamespaceKebabCase | NamespaceCamelCase,
) => {
const namespaceKebab = kebabCase(namespace)
return import(`../i18n/${language}/${namespaceKebab}.json`)
}))
.init({
...getInitOptions(),
lng,
resources,
})
return instance
}
export const changeLanguage = async (lng?: Locale) => {
if (!lng)
return
const i18n = getI18n()
await i18n.changeLanguage(lng)
}

View File

@ -2,7 +2,7 @@ import type { Locale } from '@/i18n-config/language'
import Cookies from 'js-cookie'
import { LOCALE_COOKIE_NAME } from '@/config'
import { changeLanguage } from '@/i18n-config/i18next-config'
import { changeLanguage } from '@/i18n-config/client'
import { LanguagesSupported } from '@/i18n-config/language'
export const i18n = {
@ -19,10 +19,6 @@ export const setLocaleOnClient = async (locale: Locale, reloadPage = true) => {
location.reload()
}
export const getLocaleOnClient = (): Locale => {
return Cookies.get(LOCALE_COOKIE_NAME) as Locale || i18n.defaultLocale
}
export const renderI18nObject = (obj: Record<string, string>, language: string) => {
if (!obj)
return ''

View File

@ -1,6 +1,6 @@
'use client'
import type { NamespaceCamelCase } from './i18next-config'
import type { NamespaceCamelCase } from './resources'
import { useTranslation as useTranslationOriginal } from 'react-i18next'
export function useTranslation(ns?: NamespaceCamelCase) {

View File

@ -1,4 +1,4 @@
import type { NamespaceCamelCase } from './i18next-config'
import type { NamespaceCamelCase } from './resources'
import { use } from 'react'
import { getLocaleOnServer, getTranslation } from './server'

View File

@ -1,8 +1,4 @@
'use client'
import type { Locale } from '.'
import { camelCase, kebabCase } from 'es-toolkit/string'
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import { kebabCase } from 'es-toolkit/string'
import appAnnotation from '../i18n/en-US/app-annotation.json'
import appApi from '../i18n/en-US/app-api.json'
import appDebug from '../i18n/en-US/app-debug.json'
@ -35,7 +31,7 @@ import tools from '../i18n/en-US/tools.json'
import workflow from '../i18n/en-US/workflow.json'
// @keep-sorted
export const resources = {
const resources = {
app,
appAnnotation,
appApi,
@ -82,60 +78,5 @@ export type Resources = typeof resources
export type NamespaceCamelCase = keyof Resources
export type NamespaceKebabCase = KebabCase<NamespaceCamelCase>
const requireSilent = async (lang: Locale, namespace: NamespaceKebabCase) => {
let res
try {
res = (await import(`../i18n/${lang}/${namespace}.json`)).default
}
catch {
res = (await import(`../i18n/en-US/${namespace}.json`)).default
}
return res
}
const NAMESPACES = Object.keys(resources).map(kebabCase) as NamespaceKebabCase[]
// Load a single namespace for a language
export const loadNamespace = async (lang: Locale, ns: NamespaceKebabCase) => {
const camelNs = camelCase(ns) as NamespaceCamelCase
if (i18n.hasResourceBundle(lang, camelNs))
return
const resource = await requireSilent(lang, ns)
i18n.addResourceBundle(lang, camelNs, resource, true, true)
}
// Load all namespaces for a language (used when switching language)
export const loadLangResources = async (lang: Locale) => {
await Promise.all(
NAMESPACES.map(ns => loadNamespace(lang, ns)),
)
}
// Initial resources: load en-US namespaces for fallback/default locale
const getInitialTranslations = () => {
return {
'en-US': resources,
}
}
if (!i18n.isInitialized) {
i18n.use(initReactI18next).init({
lng: undefined,
fallbackLng: 'en-US',
resources: getInitialTranslations(),
defaultNS: 'common',
ns: Object.keys(resources),
keySeparator: false,
})
}
export const changeLanguage = async (lng?: Locale) => {
if (!lng)
return
await loadLangResources(lng)
await i18n.changeLanguage(lng)
}
export default i18n
export const namespacesCamelCase = Object.keys(resources) as NamespaceCamelCase[]
export const namespacesKebabCase = namespacesCamelCase.map(ns => kebabCase(ns)) as NamespaceKebabCase[]

View File

@ -1,15 +1,19 @@
import type { i18n as I18nInstance } from 'i18next'
import type { i18n as I18nInstance, Resource, ResourceLanguage } from 'i18next'
import type { Locale } from '.'
import type { NamespaceCamelCase, NamespaceKebabCase } from './i18next-config'
import type { NamespaceCamelCase, NamespaceKebabCase } from './resources'
import { match } from '@formatjs/intl-localematcher'
import { kebabCase } from 'es-toolkit/compat'
import { camelCase } from 'es-toolkit/string'
import { createInstance } from 'i18next'
import resourcesToBackend from 'i18next-resources-to-backend'
import Negotiator from 'negotiator'
import { cookies, headers } from 'next/headers'
import { cache } from 'react'
import { initReactI18next } from 'react-i18next/initReactI18next'
import { serverOnlyContext } from '@/utils/server-only-context'
import { i18n } from '.'
import { namespacesKebabCase } from './resources'
import { getInitOptions } from './settings'
const [getLocaleCache, setLocaleCache] = serverOnlyContext<Locale | null>(null)
const [getI18nInstance, setI18nInstance] = serverOnlyContext<I18nInstance | null>(null)
@ -27,9 +31,8 @@ const getOrCreateI18next = async (lng: Locale) => {
return import(`../i18n/${language}/${fileNamespace}.json`)
}))
.init({
...getInitOptions(),
lng,
fallbackLng: 'en-US',
keySeparator: false,
})
setI18nInstance(instance)
return instance
@ -76,3 +79,16 @@ export const getLocaleOnServer = async (): Promise<Locale> => {
setLocaleCache(matchedLocale)
return matchedLocale
}
export const getResources = cache(async (lng: Locale): Promise<Resource> => {
const messages = {} as ResourceLanguage
await Promise.all(
(namespacesKebabCase).map(async (ns) => {
const mod = await import(`../i18n/${lng}/${ns}.json`)
messages[camelCase(ns)] = mod.default
}),
)
return { [lng]: messages }
})

View File

@ -0,0 +1,13 @@
import type { InitOptions } from 'i18next'
import { namespacesCamelCase } from './resources'
export function getInitOptions(): InitOptions {
return {
// We do not have en for fallback
load: 'currentOnly',
fallbackLng: 'en-US',
partialBundledLanguages: true,
keySeparator: false,
ns: namespacesCamelCase,
}
}

2
web/types/i18n.d.ts vendored
View File

@ -1,4 +1,4 @@
import type { NamespaceCamelCase, Resources } from '../i18n-config/i18next-config'
import type { NamespaceCamelCase, Resources } from '../i18n-config/resources'
import 'i18next'
declare module 'i18next' {