Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(web): preserve i18n translation type safety (#42839)

Stephen Zhou16100f839f1b
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
index 6724f9c3cc7..260cfc3079b 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import type { ReactNode } from 'react'
import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -12,7 +13,7 @@ vi.mock('react-i18next', async () => {
t: withSelectorKey((key: string, options?: Record<string, unknown>) => {
const ns = options?.ns as string | undefined
return ns ? `${ns}.${key}` : key
- }),
+ }) as TFunction<['appDebug']>,
i18n: { language: 'en', changeLanguage: vi.fn() },
}),
Trans: withSelectorKeyProps(
@@ -99,7 +100,7 @@ vi.mock('../../config-string', () => ({
),
}))
-const t = withSelectorKey((key: string) => key)
+const t = withSelectorKey((key: string) => key) as TFunction<['appDebug']>
const createPayloadChangeHandler = () => vi.fn<(value: unknown) => void>()
@@ -141,7 +142,7 @@ const createBaseProps = () => {
required: false,
hide: false,
} as any,
- t: withSelectorKey(t),
+ t,
payloadChangeHandlers,
}
}
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts b/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts
index ab6ce9a5ab2..83ba4964e08 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import type { InputVar } from '@/app/components/workflow/types'
import { DEFAULT_FILE_UPLOAD_SETTING } from '@/app/components/workflow/constants'
import { ChangeType, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
@@ -14,7 +15,7 @@ import {
validateConfigModalPayload,
} from '../utils'
-const t = withSelectorKey((key: string) => key)
+const t = withSelectorKey((key: string) => key) as TFunction<['appDebug', 'workflow']>
const createInputVar = (overrides: Partial<InputVar> = {}): InputVar => ({
type: InputVarType.textInput,
diff --git a/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx b/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx
index bd9edb47fc9..3fbf0fcd05e 100644
--- a/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx
@@ -1,8 +1,8 @@
'use client'
+import type { TFunction } from 'i18next'
import type { ChangeEvent, FC } from 'react'
import type { Item as SelectOptionItem } from './type-select'
import type { ConfigModalValidationError } from './utils'
-import type { SelectorTranslate } from '@/app/components/app/configuration/utils'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { InputVar, UploadFileSetting } from '@/app/components/workflow/types'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
@@ -25,7 +25,6 @@ import {
import { Textarea } from '@langgenius/dify-ui/textarea'
import * as React from 'react'
import { Trans } from 'react-i18next'
-import { getStringSelectorTranslate } from '@/app/components/app/configuration/utils'
import { FileUploaderInAttachmentWrapper } from '@/app/components/base/file-uploader'
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
import FileUploadSetting from '@/app/components/workflow/nodes/_base/components/file-upload-setting'
@@ -59,7 +58,7 @@ type ConfigModalFormFieldsProps = {
showHiddenField?: boolean
tempPayload: InputVar
validationError?: ConfigModalValidationError
- t: SelectorTranslate<'appDebug'>
+ t: TFunction<['appDebug']>
}
const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
@@ -79,13 +78,12 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
showHiddenField = true,
tempPayload,
validationError,
- t: rawTranslate,
+ t,
}) => {
const hiddenLabelId = React.useId()
const fileInputTypes: readonly InputVarType[] = [InputVarType.singleFile, InputVarType.multiFiles]
- const t = getStringSelectorTranslate(rawTranslate)
const { type, label, variable } = tempPayload
const numberDefault =
typeof tempPayload.default === 'number' ||
diff --git a/web/app/components/app/configuration/config-var/config-modal/utils.ts b/web/app/components/app/configuration/config-var/config-modal/utils.ts
index 03f5794d0a3..2251c333335 100644
--- a/web/app/components/app/configuration/config-var/config-modal/utils.ts
+++ b/web/app/components/app/configuration/config-var/config-modal/utils.ts
@@ -1,8 +1,7 @@
+import type { TFunction } from 'i18next'
import type { Item as SelectItem } from './type-select'
-import type { SelectorTranslate } from '@/app/components/app/configuration/utils'
import type { InputVar, MoreInfo } from '@/app/components/workflow/types'
import { produce } from 'immer'
-import { getStringSelectorTranslate } from '@/app/components/app/configuration/utils'
import { DEFAULT_FILE_UPLOAD_SETTING } from '@/app/components/workflow/constants'
import { ChangeType, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
import { checkKeys } from '@/utils/var'
@@ -15,7 +14,7 @@ type ValidateConfigModalPayloadOptions = {
tempPayload: InputVar
payload?: InputVar
maxFileUploadLimit?: number
- t: SelectorTranslate<'appDebug' | 'workflow'>
+ t: TFunction<['appDebug', 'workflow']>
}
export type ConfigModalValidationError = {
@@ -126,13 +125,12 @@ export const createPayloadForType = (payload: InputVar, type: InputVarType) => {
export const buildSelectOptions = ({
isBasicApp,
supportFile,
- t: rawTranslate,
+ t,
}: {
isBasicApp: boolean
supportFile?: boolean
- t: SelectorTranslate<'appDebug' | 'workflow'>
+ t: TFunction<['appDebug', 'workflow']>
}): SelectItem[] => {
- const t = getStringSelectorTranslate(rawTranslate)
return [
{
name: t(($) => $['variableConfig.text-input'], { ns: 'appDebug' }),
@@ -181,11 +179,10 @@ export const validateConfigModalPayload = ({
tempPayload,
payload,
maxFileUploadLimit,
- t: rawTranslate,
+ t,
}: ValidateConfigModalPayloadOptions): ValidateConfigModalPayloadResult => {
const fileInputTypes: readonly InputVarType[] = [InputVarType.singleFile, InputVarType.multiFiles]
- const t = getStringSelectorTranslate(rawTranslate)
const normalizedTempPayload = fileInputTypes.includes(tempPayload.type)
? {
...tempPayload,
diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx
index 3b0a49c7197..d83522ff973 100644
--- a/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx
@@ -1,5 +1,6 @@
import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen'
import type { OperationKey } from '@orpc/tanstack-query'
+import type { TFunction } from 'i18next'
import type { ReactElement } from 'react'
import type { DataSet } from '@/models/datasets'
import type { RetrievalConfig } from '@/types/app'
@@ -210,7 +211,7 @@ describe('RetrievalSection', () => {
const t = withSelectorKey((key: string, options?: { ns?: string }) => {
const prefix = options?.ns ? `${options.ns}.` : ''
return `${prefix}${key}`
- }, 'datasetSettings')
+ }, 'datasetSettings') as TFunction<['datasetSettings']>
const rowClass = 'row'
const labelClass = 'label'
diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx
index be73d57d64c..bee49a88883 100644
--- a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx
+++ b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx
@@ -1,5 +1,4 @@
import type { FC } from 'react'
-import type { RetrievalTranslate } from './retrieval-section'
import type { Member } from '@/models/common'
import type { DataSet } from '@/models/datasets'
import type { RetrievalConfig } from '@/types/app'
@@ -68,8 +67,7 @@ const SettingsModal: FC<SettingsModalProps> = ({
select: (response) => response.data,
}),
)
- const { t } = useTranslation(['appDebug', 'common', 'datasetSettings'])
- const translateRetrieval: RetrievalTranslate = (selector, options) => t(selector, options)
+ const { t } = useTranslation(['datasetSettings', 'appDebug', 'common'])
const docLink = useDocLink()
const ref = useRef(null)
const nameInputId = useId()
@@ -352,7 +350,7 @@ const SettingsModal: FC<SettingsModalProps> = ({
isExternal
rowClass={rowClass}
labelClass={labelClass}
- t={translateRetrieval}
+ t={t}
topK={topK}
scoreThreshold={scoreThreshold}
scoreThresholdEnabled={scoreThresholdEnabled}
@@ -364,7 +362,7 @@ const SettingsModal: FC<SettingsModalProps> = ({
isExternal={false}
rowClass={rowClass}
labelClass={labelClass}
- t={translateRetrieval}
+ t={t}
indexMethod={indexMethod}
retrievalConfig={retrievalConfig}
showMultiModalTip={showMultiModalTip}
diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/retrieval-section.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/retrieval-section.tsx
index 517d3238447..9667f2f21af 100644
--- a/web/app/components/app/configuration/dataset-config/settings-modal/retrieval-section.tsx
+++ b/web/app/components/app/configuration/dataset-config/settings-modal/retrieval-section.tsx
@@ -1,4 +1,4 @@
-import type { SelectorParam } from 'i18next'
+import type { TFunction } from 'i18next'
import type { FC } from 'react'
import type { DataSet } from '@/models/datasets'
import type { RetrievalConfig } from '@/types/app'
@@ -11,10 +11,7 @@ import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-me
import { IndexingType } from '@/app/components/datasets/create/step-two'
import RetrievalSettings from '@/app/components/datasets/external-knowledge-base/create/RetrievalSettings'
-export type RetrievalTranslate = (
- selector: SelectorParam<'datasetSettings'>,
- options: { ns: 'datasetSettings' },
-) => string
+type RetrievalTranslate = TFunction<['datasetSettings']>
type CommonSectionProps = {
rowClass: string
diff --git a/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts b/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts
index d42d1c5e464..c9e48116fa1 100644
--- a/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts
+++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import type { VisionSettings } from '@/types/app'
import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'
import { withSelectorKey } from '@/test/i18n-mock'
@@ -26,7 +27,7 @@ const mockGetSelectedDatasetsMode = vi.fn()
const mockToastError = vi.fn()
const mockToastSuccess = vi.fn()
const mockToastWarning = vi.fn()
-const t = withSelectorKey((key: string) => key)
+const t = withSelectorKey((key: string) => key) as TFunction<['appDebug', 'common']>
const baseVisionConfig: VisionSettings = {
enabled: false,
diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts
index 94f7ce598e6..a61fc791d4e 100644
--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts
+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts
@@ -1,4 +1,4 @@
-import type { SelectorTranslate } from '../../utils'
+import type { TFunction } from 'i18next'
import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { ModelConfig } from '@/models/debug'
import type { VisionSettings } from '@/types/app'
@@ -7,7 +7,6 @@ import { useMemo } from 'react'
import { toast } from '@/app/components/app/configuration/toast'
import { AppModeEnum, ModelModeType } from '@/types/app'
import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'
-import { getStringSelectorTranslate } from '../../utils'
type ModelChangeHandlerOptions = {
chatPromptLength: number
@@ -29,7 +28,7 @@ type ModelChangeHandlerOptions = {
resolvedModelModeType: ModelModeType
setCompletionParams: (value: FormValue) => void
setModelConfig: (config: ModelConfig) => void
- t: SelectorTranslate<'appDebug' | 'common'>
+ t: TFunction<['appDebug', 'common']>
visionConfig: VisionSettings
}
@@ -46,7 +45,7 @@ export const createModelChangeHandler =
resolvedModelModeType,
setCompletionParams,
setModelConfig,
- t: rawTranslate,
+ t,
visionConfig,
}: ModelChangeHandlerOptions) =>
async ({
@@ -60,7 +59,6 @@ export const createModelChangeHandler =
mode?: string
features?: string[]
}) => {
- const t = getStringSelectorTranslate(rawTranslate)
if (isAdvancedMode) {
if (nextModelMode === ModelModeType.completion) {
if (mode !== AppModeEnum.COMPLETION) {
diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/publish.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/publish.ts
index 3751c8fa711..6845dfb3ecf 100644
--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/publish.ts
+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/publish.ts
@@ -1,4 +1,4 @@
-import type { SelectorTranslate } from '../../utils'
+import type { TFunction } from 'i18next'
import type { ConfigurationPublishConfig } from './types'
import type { Features as FeaturesData } from '@/app/components/base/features/types'
import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'
@@ -12,7 +12,6 @@ import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/
import { PromptMode } from '@/models/debug'
import { AgentStrategy, AppModeEnum, ModelModeType } from '@/types/app'
import { promptVariablesToUserInputsForm } from '@/utils/model-config'
-import { getStringSelectorTranslate } from '../../utils'
import { normalizeChatPromptConfig, normalizeCompletionPromptConfig } from './prompt-config'
export function buildPublishBody({
@@ -123,7 +122,7 @@ export const createPublishHandler =
resolvedModelModeType,
setCanReturnToSimpleMode,
setPublishedConfig,
- t: rawTranslate,
+ t,
}: {
appId: string
chatPromptConfig: BackendModelConfig['chat_prompt_config']
@@ -144,14 +143,13 @@ export const createPublishHandler =
resolvedModelModeType: ModelModeType
setCanReturnToSimpleMode: (value: boolean) => void
setPublishedConfig: (config: ConfigurationPublishConfig) => void
- t: SelectorTranslate<'appDebug' | 'common'>
+ t: TFunction<['appDebug', 'common']>
}) =>
async (
updateAppModelConfig: (params: { url: string; body: BackendModelConfig }) => Promise<unknown>,
modelAndParameter?: { model: string; provider: string; parameters: FormValue },
features?: FeaturesData,
) => {
- const t = getStringSelectorTranslate(rawTranslate)
const modelId = modelAndParameter?.model || modelConfig.model_id
const promptTemplate = modelConfig.configs.prompt_template
const promptVariables = modelConfig.configs.prompt_variables
diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-publish.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-publish.ts
index 7ff59a334d1..acd09978711 100644
--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-publish.ts
+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-publish.ts
@@ -1,5 +1,5 @@
+import type { TFunction } from 'i18next'
import type { Dispatch, SetStateAction } from 'react'
-import type { SelectorTranslate } from '../../utils'
import type { ConfigurationPublishConfig } from './types'
import type { AppPublisherPublishParams } from '@/app/components/app/app-publisher/types'
import type { Features as FeaturesData } from '@/app/components/base/features/types'
@@ -32,7 +32,7 @@ type UseConfigurationPublishParams = {
setCanReturnToSimpleMode: (value: boolean) => void
setPublishedConfig: Dispatch<SetStateAction<ConfigurationPublishConfig | null>>
syncToPublishedConfig: (config: ConfigurationPublishConfig) => void
- t: SelectorTranslate<'appDebug' | 'common'>
+ t: TFunction<['appDebug', 'common']>
updateModelConfig: (params: { url: string; body: BackendModelConfig }) => Promise<unknown>
}
diff --git a/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal-utils.spec.ts b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal-utils.spec.ts
index b020d8cadcb..d1809a3a4d2 100644
--- a/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal-utils.spec.ts
+++ b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal-utils.spec.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import type { I18nText } from '@/i18n/language'
import type { CodeBasedExtensionItem } from '@/models/common'
import { LanguagesSupported } from '@/i18n/language'
@@ -13,7 +14,7 @@ const t = withSelectorKey((key: string, options?: Record<string, unknown>) => {
if (options?.key) return `${key}:${options.key as string}`
return key
-})
+}) as TFunction<['appDebug', 'common']>
const i18n = (en: string, zh = en): I18nText =>
({ 'en-US': en, 'zh-Hans': zh }) as unknown as I18nText
diff --git a/web/app/components/app/configuration/tools/external-data-tool-modal-utils.ts b/web/app/components/app/configuration/tools/external-data-tool-modal-utils.ts
index 165554ac3bd..bfcd7139415 100644
--- a/web/app/components/app/configuration/tools/external-data-tool-modal-utils.ts
+++ b/web/app/components/app/configuration/tools/external-data-tool-modal-utils.ts
@@ -1,6 +1,5 @@
-import type { SelectorTranslate } from '@/app/components/app/configuration/utils'
+import type { TFunction } from 'i18next'
import type { CodeBasedExtensionItem, ExternalDataTool } from '@/models/common'
-import { getStringSelectorTranslate } from '@/app/components/app/configuration/utils'
import { LanguagesSupported } from '@/i18n/language'
const systemTypes = ['api'] as const
@@ -16,22 +15,21 @@ type BuildProvidersParams = {
data: CodeBasedExtensionItem[]
}
locale: string
- t: SelectorTranslate<'appDebug' | 'common'>
+ t: TFunction<['appDebug', 'common']>
}
type ValidationParams = {
currentProvider?: Provider
locale: string
localeData: ExternalDataTool
- t: SelectorTranslate<'appDebug' | 'common'>
+ t: TFunction<['appDebug', 'common']>
}
export const buildProviders = ({
codeBasedExtensionList,
locale,
- t: rawTranslate,
+ t,
}: BuildProvidersParams): Provider[] => {
- const t = getStringSelectorTranslate(rawTranslate)
return [
{
key: 'api',
@@ -86,9 +84,8 @@ export const getValidationError = ({
currentProvider,
locale,
localeData,
- t: rawTranslate,
+ t,
}: ValidationParams) => {
- const t = getStringSelectorTranslate(rawTranslate)
if (!localeData.type) {
return t(($) => $['errorMessage.valueOfVarRequired'], {
ns: 'appDebug',
diff --git a/web/app/components/app/configuration/utils.ts b/web/app/components/app/configuration/utils.ts
index 2db481ff92b..c9a7f6e22ae 100644
--- a/web/app/components/app/configuration/utils.ts
+++ b/web/app/components/app/configuration/utils.ts
@@ -1,4 +1,3 @@
-import type { Namespace, SelectorParam, TFunction } from 'i18next'
import type { Features as FeaturesData, FileUpload } from '@/app/components/base/features/types'
import type { Collection } from '@/app/components/tools/types'
import type {
@@ -11,34 +10,6 @@ import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
import { AppModeEnum, ModelModeType, Resolution } from '@/types/app'
-export type SelectorTranslate<Ns extends Namespace> = <
- const TargetNs extends Ns,
- const Selector extends SelectorParam<TargetNs>,
->(
- selector: Selector,
- options: { ns: TargetNs } & Record<string, unknown>,
-) => ReturnType<TFunction<['app']>>
-
-type StringSelectorTranslate<Ns extends Namespace> = <
- const TargetNs extends Ns,
- const Selector extends SelectorParam<TargetNs>,
->(
- selector: Selector,
- options: { ns: TargetNs } & Record<string, unknown>,
-) => string
-
-export const getStringSelectorTranslate = <Ns extends Namespace>(
- translate: SelectorTranslate<Ns>,
-): StringSelectorTranslate<Ns> => {
- return (selector, options) => {
- const result = translate(selector, options)
- if (typeof result !== 'string')
- throw new TypeError('Expected translation selector to return a string')
-
- return result
- }
-}
-
export const withCollectionIconBasePath = (collectionList: Collection[], prefix?: string) => {
if (!prefix) return collectionList
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-common-modal-state.helpers.spec.ts b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-common-modal-state.helpers.spec.ts
index 05f105d69fd..2335322e34d 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-common-modal-state.helpers.spec.ts
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/__tests__/use-common-modal-state.helpers.spec.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import type { RefObject } from 'react'
import type { FormRefObject } from '@/app/components/base/form/types'
import type { TriggerSubscriptionBuilder } from '@/app/components/workflow/block-selector/types'
@@ -135,7 +136,7 @@ describe('use-common-modal-state helpers', () => {
const t = withSelectorKey(
(key: string, options?: Record<string, unknown>) => `${options?.ns}.${key}`,
'pluginTrigger',
- )
+ ) as TFunction<['pluginTrigger']>
expect(
getConfirmButtonText({
@@ -175,7 +176,7 @@ describe('use-common-modal-state helpers', () => {
t: withSelectorKey(
(key: string, options?: Record<string, unknown>) => `${options?.ns}.${key}`,
'pluginTrigger',
- ),
+ ) as TFunction<['pluginTrigger']>,
}),
)
@@ -209,7 +210,7 @@ describe('use-common-modal-state helpers', () => {
t: withSelectorKey(
(key: string, options?: Record<string, unknown>) => `${options?.ns}.${key}`,
'pluginTrigger',
- ),
+ ) as TFunction<['pluginTrigger']>,
}),
)
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.helpers.ts b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.helpers.ts
index 7ba99ffeab3..e30b63238df 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.helpers.ts
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.helpers.ts
@@ -1,5 +1,5 @@
'use client'
-import type { SelectorParam } from 'i18next'
+import type { TFunction } from 'i18next'
import type { Dispatch, SetStateAction } from 'react'
import type { FormRefObject } from '@/app/components/base/form/types'
import type { TriggerSubscriptionBuilder } from '@/app/components/workflow/block-selector/types'
@@ -14,10 +14,7 @@ type FormValuesResult = {
isCheckValidated: boolean
}
-export type PluginTriggerTranslate = (
- selector: SelectorParam<'pluginTrigger'>,
- options: { ns: 'pluginTrigger' },
-) => string
+export type PluginTriggerTranslate = TFunction<['pluginTrigger']>
type InitializeBuilderParams = {
createBuilder: (params: {
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts
index d3c283c81a4..79dd140e81c 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts
@@ -1,7 +1,6 @@
'use client'
import type { SimpleDetail } from '../../../store'
import type { SchemaItem } from '../components/modal-steps'
-import type { PluginTriggerTranslate } from './use-common-modal-state.helpers'
import type { FormRefObject } from '@/app/components/base/form/types'
import type {
TriggerLogEntity,
@@ -108,10 +107,6 @@ export const useCommonModalState = ({
onClose,
}: UseCommonModalStateParams): UseCommonModalStateReturn => {
const { t } = useTranslation(['pluginTrigger'])
- const translatePluginTriggerKey = useCallback<PluginTriggerTranslate>(
- (selector, options) => t(selector, options),
- [t],
- )
const detail = usePluginStore((state) => state.detail)
const { refetch } = useSubscriptionList()
@@ -187,7 +182,7 @@ export const useCommonModalState = ({
provider: detail?.provider,
subscriptionBuilder,
setSubscriptionBuilder,
- t: translatePluginTriggerKey,
+ t,
})
// Cleanup debounced function
@@ -201,7 +196,7 @@ export const useCommonModalState = ({
endpoint: subscriptionBuilder?.endpoint,
isConfigurationStep: currentStep === ApiKeyStep.Configuration,
subscriptionFormRef,
- t: translatePluginTriggerKey,
+ t,
})
// Handle manual properties change
@@ -334,9 +329,9 @@ export const useCommonModalState = ({
isVerifyStep: currentStep === ApiKeyStep.Verify,
isVerifyingCredentials,
isBuilding,
- t: translatePluginTriggerKey,
+ t,
})
- }, [currentStep, isVerifyingCredentials, isBuilding, translatePluginTriggerKey])
+ }, [currentStep, isVerifyingCredentials, isBuilding, t])
return {
currentStep,
diff --git a/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-batch.spec.ts b/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-batch.spec.ts
index 0c6927b04a6..b1810d87c30 100644
--- a/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-batch.spec.ts
+++ b/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-batch.spec.ts
@@ -1,3 +1,4 @@
+import type { TextGenerationTranslate } from '../../types'
import type { PromptConfig, PromptVariable } from '@/models/debug'
import { act, renderHook } from '@testing-library/react'
import { BATCH_CONCURRENCY } from '@/config'
@@ -21,7 +22,8 @@ const createPromptConfig = (): PromptConfig => ({
],
})
-const createTranslator = () => withSelectorKey(vi.fn((key: string) => key))
+const createTranslator = () =>
+ withSelectorKey(vi.fn((key: string) => key)) as TextGenerationTranslate
const renderBatchHook = (promptConfig: PromptConfig = createPromptConfig()) => {
const notify = vi.fn()
diff --git a/web/app/components/share/text-generation/index.tsx b/web/app/components/share/text-generation/index.tsx
index 840b3c6d599..7fb76acfd0a 100644
--- a/web/app/components/share/text-generation/index.tsx
+++ b/web/app/components/share/text-generation/index.tsx
@@ -1,6 +1,6 @@
'use client'
import type { FC } from 'react'
-import type { InputValueTypes, TextGenerationRunControl, TextGenerationTranslate } from './types'
+import type { InputValueTypes, TextGenerationRunControl } from './types'
import type { VisionFile } from '@/types/app'
import { cn } from '@langgenius/dify-ui/cn'
import { useBoolean } from 'ahooks'
@@ -21,12 +21,6 @@ type IMainProps = {
}
const TextGeneration: FC<IMainProps> = ({ isInstalledApp = false, isWorkflow = false }) => {
const { t } = useTranslation(['share', 'appDebug', 'common'])
- const translateBatchKey: TextGenerationTranslate = useCallback(
- (selector, options) => {
- return t(selector, options)
- },
- [t],
- )
const media = useBreakpoints()
const isPC = media === MediaType.pc
const searchParams = useSearchParams()
@@ -89,7 +83,7 @@ const TextGeneration: FC<IMainProps> = ({ isInstalledApp = false, isWorkflow = f
} = useTextGenerationBatch({
promptConfig,
notify,
- t: translateBatchKey,
+ t,
})
useEffect(() => {
if (isCallBatchAPI) setRunControl(null)
diff --git a/web/app/components/share/text-generation/result/__tests__/result-request.spec.ts b/web/app/components/share/text-generation/result/__tests__/result-request.spec.ts
index 77fa2b646eb..d3d929fc407 100644
--- a/web/app/components/share/text-generation/result/__tests__/result-request.spec.ts
+++ b/web/app/components/share/text-generation/result/__tests__/result-request.spec.ts
@@ -1,3 +1,4 @@
+import type { TextGenerationTranslate } from '../../types'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { PromptConfig } from '@/models/debug'
import type { VisionFile, VisionSettings } from '@/types/app'
@@ -5,7 +6,8 @@ import { withSelectorKey } from '@/test/i18n-mock'
import { Resolution, TransferMethod } from '@/types/app'
import { buildResultRequestData, validateResultRequest } from '../result-request'
-const createTranslator = () => withSelectorKey(vi.fn((key: string) => key))
+const createTranslator = () =>
+ withSelectorKey(vi.fn((key: string) => key)) as TextGenerationTranslate
const createFileEntity = (overrides: Partial<FileEntity> = {}): FileEntity => ({
id: 'file-1',
diff --git a/web/app/components/share/text-generation/result/__tests__/workflow-stream-handlers.spec.ts b/web/app/components/share/text-generation/result/__tests__/workflow-stream-handlers.spec.ts
index 335ce562c2e..d756577c1f1 100644
--- a/web/app/components/share/text-generation/result/__tests__/workflow-stream-handlers.spec.ts
+++ b/web/app/components/share/text-generation/result/__tests__/workflow-stream-handlers.spec.ts
@@ -1,3 +1,4 @@
+import type { TextGenerationTranslate } from '../../types'
import type { WorkflowProcess } from '@/app/components/base/chat/types'
import type { IOtherOptions } from '@/service/base'
import type { HumanInputFormData, HumanInputFormTimeoutData, NodeTracing } from '@/types/workflow'
@@ -429,7 +430,7 @@ describe('createWorkflowStreamHandlers', () => {
setMessageId,
setRespondingFalse,
setWorkflowProcessData,
- t: withSelectorKey((key: string) => key),
+ t: withSelectorKey((key: string) => key) as TextGenerationTranslate,
taskId: 3,
})
@@ -798,7 +799,7 @@ describe('createWorkflowStreamHandlers', () => {
setWorkflowProcessData: (value) => {
existingProcess = value!
},
- t: withSelectorKey((key: string) => key),
+ t: withSelectorKey((key: string) => key) as TextGenerationTranslate,
taskId: 5,
}) as Required<
Pick<IOtherOptions, 'onWorkflowStarted' | 'onWorkflowFinished' | 'onTextReplace'>
diff --git a/web/app/components/share/text-generation/result/hooks/__tests__/use-result-sender.spec.ts b/web/app/components/share/text-generation/result/hooks/__tests__/use-result-sender.spec.ts
index 8dc1dba662b..0ad8ae15535 100644
--- a/web/app/components/share/text-generation/result/hooks/__tests__/use-result-sender.spec.ts
+++ b/web/app/components/share/text-generation/result/hooks/__tests__/use-result-sender.spec.ts
@@ -1,3 +1,4 @@
+import type { TextGenerationTranslate } from '../../../types'
import type { ResultInputValue } from '../../result-request'
import type { ResultRunStateController } from '../use-result-run-state'
import type { PromptConfig } from '@/models/debug'
@@ -219,7 +220,7 @@ const renderSender = ({
onShowRes,
promptConfig,
runState: runState || createRunStateHarness().runState,
- t: withSelectorKey((key: string) => key),
+ t: withSelectorKey((key: string) => key) as TextGenerationTranslate,
taskId,
visionConfig,
}),
diff --git a/web/app/components/share/text-generation/result/index.tsx b/web/app/components/share/text-generation/result/index.tsx
index 6241ee9adec..7b7aa9751e8 100644
--- a/web/app/components/share/text-generation/result/index.tsx
+++ b/web/app/components/share/text-generation/result/index.tsx
@@ -1,6 +1,5 @@
'use client'
import type { FC } from 'react'
-import type { TextGenerationTranslate } from '../types'
import type { PromptConfig } from '@/models/debug'
import type { SiteInfo } from '@/models/share'
import type { AppSourceType } from '@/service/share'
@@ -73,11 +72,7 @@ const Result: FC<IResultProps> = ({
onRunControlChange,
hideInlineStopButton = false,
}) => {
- const { t } = useTranslation(['appDebug', 'common', 'share'])
- const translateResultKey = useCallback<TextGenerationTranslate>(
- (selector, options) => t(selector, options),
- [t],
- )
+ const { t } = useTranslation(['share', 'appDebug', 'common'])
const notify = useCallback(
({ type, message }: { type: 'error' | 'info' | 'success' | 'warning'; message: string }) => {
toast(message, { type })
@@ -108,7 +103,7 @@ const Result: FC<IResultProps> = ({
onShowRes,
promptConfig,
runState,
- t: translateResultKey,
+ t,
taskId,
visionConfig,
})
diff --git a/web/app/components/share/text-generation/types.ts b/web/app/components/share/text-generation/types.ts
index 3899669a754..c3d64897861 100644
--- a/web/app/components/share/text-generation/types.ts
+++ b/web/app/components/share/text-generation/types.ts
@@ -1,13 +1,7 @@
-import type { SelectorParam } from 'i18next'
+import type { TFunction } from 'i18next'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
-export type TextGenerationTranslate = <
- Ns extends 'appDebug' | 'common' | 'share',
- Selector extends SelectorParam<Ns>,
->(
- selector: Selector,
- options: { ns: Ns } & Record<string, unknown>,
-) => string
+export type TextGenerationTranslate = TFunction<['share', 'appDebug', 'common']>
type TaskParam = {
inputs: Record<string, string | boolean | undefined>
diff --git a/web/app/components/workflow/nodes/_base/__tests__/node-sections.spec.tsx b/web/app/components/workflow/nodes/_base/__tests__/node-sections.spec.tsx
index 033d78c189e..1b7ac24d2fc 100644
--- a/web/app/components/workflow/nodes/_base/__tests__/node-sections.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/__tests__/node-sections.spec.tsx
@@ -1,10 +1,11 @@
+import type { TFunction } from 'i18next'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
import { withSelectorKey } from '@/test/i18n-mock'
import { NodeBody, NodeDescription, NodeHeaderMeta } from '../node-sections'
-const t = withSelectorKey((key: string) => key)
+const t = withSelectorKey((key: string) => key) as TFunction<['workflow']>
describe('node sections', () => {
it('should render loop and loading metadata in the header section', () => {
diff --git a/web/app/components/workflow/nodes/_base/components/before-run-form/__tests__/helpers.spec.ts b/web/app/components/workflow/nodes/_base/components/before-run-form/__tests__/helpers.spec.ts
index 3c0a39378ff..599159977f2 100644
--- a/web/app/components/workflow/nodes/_base/components/before-run-form/__tests__/helpers.spec.ts
+++ b/web/app/components/workflow/nodes/_base/components/before-run-form/__tests__/helpers.spec.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import type { InputVar } from '@/app/components/workflow/types'
import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
import { withSelectorKey } from '@/test/i18n-mock'
@@ -64,7 +65,7 @@ describe('before-run-form helpers', () => {
it('should report required and uploading file errors', () => {
const t = withSelectorKey(
(key: string, options?: Record<string, unknown>) => `${key}:${options?.field ?? ''}`,
- )
+ ) as TFunction<['appDebug', 'workflow']>
expect(
getFormErrorMessage(
diff --git a/web/app/components/workflow/nodes/_base/components/before-run-form/helpers.ts b/web/app/components/workflow/nodes/_base/components/before-run-form/helpers.ts
index e90ea12be68..f9315de08ff 100644
--- a/web/app/components/workflow/nodes/_base/components/before-run-form/helpers.ts
+++ b/web/app/components/workflow/nodes/_base/components/before-run-form/helpers.ts
@@ -1,14 +1,11 @@
-import type { SelectorParam } from 'i18next'
+import type { TFunction } from 'i18next'
import type { Props as FormProps } from './form'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { getProcessedFiles } from '@/app/components/base/file-uploader/utils'
import { InputVarType } from '@/app/components/workflow/types'
import { TransferMethod } from '@/types/app'
-export type BeforeRunFormTranslator = <Namespace extends 'workflow' | 'appDebug'>(
- selector: SelectorParam<Namespace>,
- options: { ns: Namespace } & Record<string, unknown>,
-) => string
+export type BeforeRunFormTranslator = TFunction<['appDebug', 'workflow']>
export function formatValue(value: unknown, type: InputVarType) {
if (type === InputVarType.checkbox) return !!value
diff --git a/web/app/components/workflow/nodes/_base/components/before-run-form/index.tsx b/web/app/components/workflow/nodes/_base/components/before-run-form/index.tsx
index 9d8b60ab04b..65c57cc7109 100644
--- a/web/app/components/workflow/nodes/_base/components/before-run-form/index.tsx
+++ b/web/app/components/workflow/nodes/_base/components/before-run-form/index.tsx
@@ -1,7 +1,6 @@
'use client'
import type { FC } from 'react'
import type { Props as FormProps } from './form'
-import type { BeforeRunFormTranslator } from './helpers'
import type { Emoji } from '@/app/components/tools/types'
import type { SpecialResultPanelProps } from '@/app/components/workflow/run/special-result-panel'
import type { NodeRunningStatus } from '@/app/components/workflow/types'
@@ -63,15 +62,13 @@ const BeforeRunForm: FC<BeforeRunFormProps> = ({
handleAfterHumanInputStepRun,
}) => {
const { t } = useTranslation(['appDebug', 'workflow'])
- const translateFormError: BeforeRunFormTranslator = (selector, options) => t(selector, options)
-
const isHumanInput = nodeType === BlockEnum.HumanInput
const showBackButton = filteredExistVarForms.length > 0
const isFileLoaded = isFilesLoaded(forms)
const handleRunOrGenerateForm = () => {
- const errMsg = getFormErrorMessage(forms, existVarValuesInForms, translateFormError)
+ const errMsg = getFormErrorMessage(forms, existVarValuesInForms, t)
if (errMsg) {
toast.error(errMsg)
return
diff --git a/web/app/components/workflow/nodes/_base/components/variable/utils.ts b/web/app/components/workflow/nodes/_base/components/variable/utils.ts
index 3afc68b546a..4ac9f6f98ab 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/utils.ts
+++ b/web/app/components/workflow/nodes/_base/components/variable/utils.ts
@@ -1,4 +1,4 @@
-import type { SelectorParam, TFunction } from 'i18next'
+import type { TFunction } from 'i18next'
import type { AnswerNodeType } from '../../../answer/types'
import type { CodeNodeType } from '../../../code/types'
import type { DocExtractorNodeType } from '../../../document-extractor/types'
@@ -68,21 +68,7 @@ import { AppModeEnum } from '@/types/app'
import { OUTPUT_FILE_SUB_VARIABLES } from '../../../constants'
import { Type } from '../../../llm/types'
-type WorkflowTranslate = <const Selector extends SelectorParam<'workflow'>>(
- selector: Selector,
- options: { ns: 'workflow' } & Record<string, unknown>,
-) => ReturnType<TFunction<['workflow']>>
-
-const translateWorkflowString = <const Selector extends SelectorParam<'workflow'>>(
- t: WorkflowTranslate,
- selector: Selector,
-): string => {
- const result = t(selector, { ns: 'workflow' })
- if (typeof result !== 'string')
- throw new TypeError('Expected workflow translation selector to return a string')
-
- return result
-}
+type WorkflowTranslate = TFunction<['workflow']>
export const isSystemVar = (valueSelector: ValueSelector) => {
return valueSelector[0] === 'sys' || valueSelector[1] === 'sys'
@@ -1164,7 +1150,7 @@ export const toNodeAvailableVars = ({
: {}
const iterationVar = {
nodeId: iterationNode?.id,
- title: translateWorkflowString(t!, ($) => $['nodes.iteration.currentIteration']),
+ title: t!(($) => $['nodes.iteration.currentIteration'], { ns: 'workflow' }),
vars: [
{
variable: 'item',
diff --git a/web/app/components/workflow/nodes/_base/node-sections.tsx b/web/app/components/workflow/nodes/_base/node-sections.tsx
index b813face820..1b6cd0c7830 100644
--- a/web/app/components/workflow/nodes/_base/node-sections.tsx
+++ b/web/app/components/workflow/nodes/_base/node-sections.tsx
@@ -1,4 +1,4 @@
-import type { SelectorParam } from 'i18next'
+import type { TFunction } from 'i18next'
import type { ReactElement } from 'react'
import type { IterationNodeType } from '@/app/components/workflow/nodes/iteration/types'
import type { NodeProps } from '@/app/components/workflow/types'
@@ -13,10 +13,7 @@ type HeaderMetaProps = {
t: WorkflowTranslator
}
-export type WorkflowTranslator = (
- selector: SelectorParam<'workflow'>,
- options: { ns: 'workflow' } & Record<string, unknown>,
-) => string
+type WorkflowTranslator = TFunction<['workflow']>
export const NodeHeaderMeta = ({ data, hasVarValue, isLoading, loopIndex, t }: HeaderMetaProps) => {
return (
diff --git a/web/app/components/workflow/nodes/_base/node.tsx b/web/app/components/workflow/nodes/_base/node.tsx
index b24c3443218..61e56c5bf40 100644
--- a/web/app/components/workflow/nodes/_base/node.tsx
+++ b/web/app/components/workflow/nodes/_base/node.tsx
@@ -1,5 +1,4 @@
import type { FC, ReactElement } from 'react'
-import type { WorkflowTranslator } from './node-sections'
import type { NodeProps } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import { useSuspenseQuery } from '@tanstack/react-query'
@@ -50,8 +49,7 @@ type BaseNodeProps = {
}
const BaseNode: FC<BaseNodeProps> = ({ id, data, children }) => {
- const { t } = useTranslation(['plugin', 'workflow'])
- const translateWorkflow: WorkflowTranslator = (selector, options) => t(selector, options)
+ const { t } = useTranslation(['workflow', 'plugin'])
const nodeRef = useRef<HTMLDivElement>(null)
const { nodesReadOnly } = useNodesReadOnly()
@@ -263,7 +261,7 @@ const BaseNode: FC<BaseNodeProps> = ({ id, data, children }) => {
hasVarValue={hasVarValue}
isLoading={isLoading}
loopIndex={LoopIndex}
- t={translateWorkflow}
+ t={t}
/>
</div>
</div>
diff --git a/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/use-variable-modal-state.spec.ts b/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/use-variable-modal-state.spec.ts
index 983009c6daf..598b92c1aa0 100644
--- a/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/use-variable-modal-state.spec.ts
+++ b/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/use-variable-modal-state.spec.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import type { ChangeEvent } from 'react'
import { act, renderHook } from '@testing-library/react'
import { withSelectorKey } from '@/test/i18n-mock'
@@ -8,7 +9,7 @@ vi.mock('uuid', () => ({
v4: () => 'generated-id',
}))
-const t = withSelectorKey((key: string) => key)
+const t = withSelectorKey((key: string) => key) as TFunction<['appDebug', 'workflow']>
const createOptions = (overrides: Partial<Parameters<typeof useVariableModalState>[0]> = {}) => ({
chatVar: undefined,
diff --git a/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/variable-modal.helpers.spec.ts b/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/variable-modal.helpers.spec.ts
index a5e959dbae5..c685f9df3ea 100644
--- a/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/variable-modal.helpers.spec.ts
+++ b/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/variable-modal.helpers.spec.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import { withSelectorKey } from '@/test/i18n-mock'
import { ChatVarType } from '../../type'
import {
@@ -146,7 +147,7 @@ describe('variable-modal helpers', () => {
it('should validate variable names and notify when invalid', () => {
const notify = vi.fn()
- const t = withSelectorKey((key: string) => key)
+ const t = withSelectorKey((key: string) => key) as TFunction<['appDebug', 'workflow']>
expect(
validateVariableName({
diff --git a/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/variable-modal.sections.spec.tsx b/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/variable-modal.sections.spec.tsx
index 804b017e20c..3db45173f7a 100644
--- a/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/variable-modal.sections.spec.tsx
+++ b/web/app/components/workflow/panel/chat-variable-panel/components/__tests__/variable-modal.sections.spec.tsx
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import { fireEvent, render, screen } from '@testing-library/react'
import { withSelectorKey } from '@/test/i18n-mock'
import { ChatVarType } from '../../type'
@@ -85,7 +86,7 @@ describe('variable-modal sections', () => {
onObjectChange={onObjectChange}
onValueChange={onValueChange}
placeholder="placeholder"
- t={withSelectorKey((key: string) => key)}
+ t={withSelectorKey((key: string) => key) as TFunction<['appDebug', 'workflow']>}
toggleLabelKey="chatVariable.modal.editInJSON"
type={ChatVarType.String}
value="draft"
diff --git a/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.helpers.ts b/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.helpers.ts
index 81f7b3764fd..d4bcfb409e3 100644
--- a/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.helpers.ts
+++ b/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.helpers.ts
@@ -1,4 +1,4 @@
-import type { SelectorParam } from 'i18next'
+import type { SelectorParam, TFunction } from 'i18next'
import type { ReactNode } from 'react'
import type { ChatVarType } from '../type'
import type { ConversationVariable } from '@/app/components/workflow/types'
@@ -32,10 +32,7 @@ export type ToastPayload = {
export const MAX_DESCRIPTION_LENGTH = 255
-export type ChatVariableTranslator = <Namespace extends 'workflow' | 'appDebug'>(
- selector: SelectorParam<Namespace>,
- options: { ns: Namespace } & Record<string, unknown>,
-) => string
+export type ChatVariableTranslator = TFunction<['appDebug', 'workflow']>
type VariableNameErrorKey = Exclude<ReturnType<typeof checkKeys>['errorMessageKey'], ''>
diff --git a/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.tsx b/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.tsx
index ab5cf3e0b96..6f59d50f9cb 100644
--- a/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.tsx
+++ b/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.tsx
@@ -1,4 +1,4 @@
-import type { ChatVariableTranslator, ToastPayload } from './variable-modal.helpers'
+import type { ToastPayload } from './variable-modal.helpers'
import type { ConversationVariable } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -31,7 +31,6 @@ type ModalPropsType = {
const ChatVariableModal = ({ chatVar, onClose, onSave }: ModalPropsType) => {
const { t } = useTranslation(['appDebug', 'common', 'workflow'])
- const translateChatVariable: ChatVariableTranslator = (selector, options) => t(selector, options)
const workflowStore = useWorkflowStore()
const notify = React.useCallback(({ children, message, type = 'info' }: ToastPayload) => {
toast[type](message, children ? { description: children } : undefined)
@@ -61,16 +60,12 @@ const ChatVariableModal = ({ chatVar, onClose, onSave }: ModalPropsType) => {
notify,
onClose,
onSave,
- t: translateChatVariable,
+ t,
})
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
replaceSpaceWithUnderscoreInVarNameInput(e.target)
- if (
- e.target.value &&
- !validateVariableName({ name: e.target.value, notify, t: translateChatVariable })
- )
- return
+ if (e.target.value && !validateVariableName({ name: e.target.value, notify, t })) return
handleVarNameChange(e)
}
@@ -94,9 +89,7 @@ const ChatVariableModal = ({ chatVar, onClose, onSave }: ModalPropsType) => {
<div className="max-h-120 overflow-y-auto px-4 py-2">
<NameSection
name={name}
- onBlur={(nextName) =>
- validateVariableName({ name: nextName, notify, t: translateChatVariable })
- }
+ onBlur={(nextName) => validateVariableName({ name: nextName, notify, t })}
onChange={handleNameChange}
placeholder={t(($) => $['chatVariable.modal.namePlaceholder'], { ns: 'workflow' }) || ''}
title={t(($) => $['chatVariable.modal.name'], { ns: 'workflow' })}
@@ -125,7 +118,7 @@ const ChatVariableModal = ({ chatVar, onClose, onSave }: ModalPropsType) => {
onObjectChange={setObjectValue}
onValueChange={setValue}
placeholder={placeholder}
- t={translateChatVariable}
+ t={t}
toggleLabelKey={
type === ChatVarType.Object ||
type === ChatVarType.ArrayString ||
diff --git a/web/app/components/workflow/run/utils/format-log/parallel/__tests__/index.spec.ts b/web/app/components/workflow/run/utils/format-log/parallel/__tests__/index.spec.ts
index c2875d47b78..c69a8179621 100644
--- a/web/app/components/workflow/run/utils/format-log/parallel/__tests__/index.spec.ts
+++ b/web/app/components/workflow/run/utils/format-log/parallel/__tests__/index.spec.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next'
import type { NodeTracing } from '@/types/workflow'
import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
import { withSelectorKey } from '@/test/i18n-mock'
@@ -7,7 +8,7 @@ const t = withSelectorKey((key: string, options?: Record<string, string>) => {
if (key === 'common.parallel') return 'Parallel'
if (key === 'common.branch') return 'Branch'
return options?.ns ? `${options.ns}.${key}` : key
-}, 'workflow')
+}, 'workflow') as TFunction<['workflow']>
const createNodeTracing = (overrides: Partial<NodeTracing> = {}): NodeTracing => ({
id: 'trace-1',
diff --git a/web/app/components/workflow/run/utils/format-log/parallel/index.ts b/web/app/components/workflow/run/utils/format-log/parallel/index.ts
index 54c301b6abb..b883fbb69d2 100644
--- a/web/app/components/workflow/run/utils/format-log/parallel/index.ts
+++ b/web/app/components/workflow/run/utils/format-log/parallel/index.ts
@@ -1,22 +1,8 @@
-import type { SelectorParam, TFunction } from 'i18next'
+import type { TFunction } from 'i18next'
import type { NodeTracing } from '@/types/workflow'
import { BlockEnum } from '@/app/components/workflow/types'
-export type WorkflowTranslate = <const Selector extends SelectorParam<'workflow'>>(
- selector: Selector,
- options: { ns: 'workflow' },
-) => ReturnType<TFunction<['workflow']>>
-
-const translateWorkflowString = <const Selector extends SelectorParam<'workflow'>>(
- t: WorkflowTranslate,
- selector: Selector,
-): string => {
- const result = t(selector, { ns: 'workflow' })
- if (typeof result !== 'string')
- throw new TypeError('Expected workflow translation selector to return a string')
-
- return result
-}
+export type WorkflowTranslate = TFunction<['workflow']>
function findLastIndex<T>(list: T[], predicate: (item: T) => boolean): number {
for (let index = list.length - 1; index >= 0; index--) {
@@ -76,7 +62,7 @@ function addTitle(
if (isParallelStartNode) {
node.parallelDetail!.isParallelStartNode = true
- node.parallelDetail!.parallelTitle = `${translateWorkflowString(t, ($) => $['common.parallel'])}-${parallelIndexInfo}`
+ node.parallelDetail!.parallelTitle = `${t(($) => $['common.parallel'], { ns: 'workflow' })}-${parallelIndexInfo}`
}
const isBrachStartNode = parallel_start_node_id === node.node_id
@@ -89,7 +75,7 @@ function addTitle(
}
}
- node.parallelDetail!.branchTitle = `${translateWorkflowString(t, ($) => $['common.branch'])}-${belongParallelIndexInfo}-${branchLetter}`
+ node.parallelDetail!.branchTitle = `${t(($) => $['common.branch'], { ns: 'workflow' })}-${belongParallelIndexInfo}-${branchLetter}`
}
if (node.parallelDetail?.children && node.parallelDetail.children.length > 0) {
diff --git a/web/features/new-rag/__tests__/add-source-page.spec.tsx b/web/features/new-rag/__tests__/add-source-page.spec.tsx
index 65035fd0b92..21c36628dc5 100644
--- a/web/features/new-rag/__tests__/add-source-page.spec.tsx
+++ b/web/features/new-rag/__tests__/add-source-page.spec.tsx
@@ -16,6 +16,18 @@ const routerMock = vi.hoisted(() => ({
vi.mock('@/next/navigation', () => ({ useRouter: () => routerMock }))
+vi.mock('react-i18next', async () => {
+ const { createReactI18nextMock } = await import('@/test/i18n-mock')
+ const { default: dataset } = await import('@/i18n/locales/en-US/dataset.json')
+ return createReactI18nextMock({
+ 'dataset.newKnowledge.connectProvider': dataset['newKnowledge.connectProvider'],
+ 'dataset.newKnowledge.connectionFailed': dataset['newKnowledge.connectionFailed'],
+ 'dataset.newKnowledge.connectionNeedsAttention':
+ dataset['newKnowledge.connectionNeedsAttention'],
+ 'dataset.newKnowledge.connectionProvisioning': dataset['newKnowledge.connectionProvisioning'],
+ })
+})
+
const toastInfoMock = vi.hoisted(() => vi.fn())
vi.mock('@/app/notifications', () => ({
@@ -542,7 +554,7 @@ describe('AddSourcePage', () => {
)
await user.type(screen.getByLabelText(/Api Key/), 'secret-value')
await user.type(screen.getByLabelText('Endpoint'), 'https://crawl.example.com')
- await user.click(screen.getByRole('button', { name: 'dataset.newKnowledge.connectProvider' }))
+ await user.click(screen.getByRole('button', { name: 'Connect Firecrawl' }))
await waitFor(() =>
expect(clientMock.createConnection).toHaveBeenCalledWith({
@@ -581,7 +593,7 @@ describe('AddSourcePage', () => {
)
await user.type(screen.getByLabelText(/Api Key/), 'secret-value')
const connectButton = screen.getByRole('button', {
- name: 'dataset.newKnowledge.connectProvider',
+ name: 'Connect Firecrawl',
})
await user.click(connectButton)
@@ -608,7 +620,7 @@ describe('AddSourcePage', () => {
screen.getByRole('button', { name: /^dataset\.newKnowledge\.configureProvider/ }),
)
await user.type(screen.getByLabelText(/Api Key/), 'secret-value')
- await user.click(screen.getByRole('button', { name: 'dataset.newKnowledge.connectProvider' }))
+ await user.click(screen.getByRole('button', { name: 'Connect Firecrawl' }))
await waitFor(() => expect(historyBack).toHaveBeenCalledOnce())
expect(screen.queryByText(/dataset\.newKnowledge\.providerConnected/)).not.toBeInTheDocument()
@@ -713,9 +725,13 @@ describe('AddSourcePage', () => {
)
await user.type(screen.getByLabelText(/Api Key/), 'do-not-retain')
await user.type(screen.getByLabelText('Endpoint'), 'https://crawl.example.com')
- await user.click(screen.getByRole('button', { name: 'dataset.newKnowledge.connectProvider' }))
+ await user.click(screen.getByRole('button', { name: 'Connect Firecrawl' }))
- expect(await screen.findByText('dataset.newKnowledge.connectionFailed')).toBeInTheDocument()
+ expect(
+ await screen.findByText(
+ "We couldn't connect Firecrawl. Re-enter the credential and try again.",
+ ),
+ ).toBeInTheDocument()
expect(screen.getByLabelText(/Api Key/)).toHaveValue('')
expect(screen.getByLabelText('Endpoint')).toHaveValue('https://crawl.example.com')
})
@@ -732,13 +748,15 @@ describe('AddSourcePage', () => {
screen.getByRole('button', { name: /^dataset\.newKnowledge\.configureProvider/ }),
)
await user.type(screen.getByLabelText(/Api Key/), 'secret-value')
- await user.click(screen.getByRole('button', { name: 'dataset.newKnowledge.connectProvider' }))
+ await user.click(screen.getByRole('button', { name: 'Connect Firecrawl' }))
await waitFor(() => expect(clientMock.createConnection).toHaveBeenCalledOnce())
await screen.findByRole('progressbar', { name: 'common.loading' })
act(() => window.dispatchEvent(new PopStateEvent('popstate')))
expect(await screen.findByText(/dataset\.newKnowledge\.providerConnected/)).toBeInTheDocument()
- expect(screen.queryByText('dataset.newKnowledge.connectionFailed')).not.toBeInTheDocument()
+ expect(
+ screen.queryByText("We couldn't connect Firecrawl. Re-enter the credential and try again."),
+ ).not.toBeInTheDocument()
})
it('clears an API key when authentication modes are changed and changed back', async () => {
@@ -770,7 +788,7 @@ describe('AddSourcePage', () => {
await user.type(screen.getByLabelText(/Api Key/), 'must-not-be-sent')
await user.click(screen.getByRole('radio', { name: 'dataset.newKnowledge.authKind.endpoint' }))
await user.type(screen.getByLabelText('Endpoint'), 'https://crawl.example.com')
- await user.click(screen.getByRole('button', { name: 'dataset.newKnowledge.connectProvider' }))
+ await user.click(screen.getByRole('button', { name: 'Connect Firecrawl' }))
await waitFor(() =>
expect(clientMock.createConnection).toHaveBeenCalledWith({
@@ -823,6 +841,9 @@ describe('AddSourcePage', () => {
clientMock.refreshConnection.mockResolvedValue(connection('active'))
render(<AddSourcePage knowledgeSpaceId="space-1" />)
+ expect(
+ screen.getByRole('heading', { name: 'Firecrawl connection needs attention' }),
+ ).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))
await waitFor(() =>
@@ -924,9 +945,7 @@ describe('AddSourcePage', () => {
const view = render(<AddSourcePage knowledgeSpaceId="space-1" />)
await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))
- expect(
- await screen.findByText('dataset.newKnowledge.connectionProvisioning'),
- ).toBeInTheDocument()
+ expect(await screen.findByText('Firecrawl is connecting')).toBeInTheDocument()
queryState.connections.data = {
pages: [
diff --git a/web/features/new-rag/add-source-page.tsx b/web/features/new-rag/add-source-page.tsx
index 16cafdeddd4..e327eb0a6e8 100644
--- a/web/features/new-rag/add-source-page.tsx
+++ b/web/features/new-rag/add-source-page.tsx
@@ -412,7 +412,7 @@ function ConnectionForm({
</div>
{error && (
<p role="alert" className="mt-3 system-xs-regular text-text-destructive">
- {t(($) => $['newKnowledge.connectionFailed'])}
+ {t(($) => $['newKnowledge.connectionFailed'], { provider: FIRECRAWL_CONNECTION_NAME })}
</p>
)}
<Button
@@ -425,7 +425,7 @@ function ConnectionForm({
<span id={connectButtonLabelId}>
{pending
? t(($) => $['newKnowledge.connectingProvider'])
- : t(($) => $['newKnowledge.connectProvider'])}
+ : t(($) => $['newKnowledge.connectProvider'], { provider: FIRECRAWL_CONNECTION_NAME })}
</span>
</Button>
</form>
@@ -529,7 +529,9 @@ function ConnectionProblem({
return (
<div className="rounded-xl border border-components-option-card-option-border bg-background-section p-4">
<h3 className="system-sm-semibold text-text-primary">
- {t(($) => $['newKnowledge.connectionNeedsAttention'])}
+ {t(($) => $['newKnowledge.connectionNeedsAttention'], {
+ provider: FIRECRAWL_CONNECTION_NAME,
+ })}
</h3>
<p className="mt-1 system-xs-regular text-text-tertiary">
{t(($) => $['newKnowledge.connectionNeedsAttentionDescription'])}
@@ -581,7 +583,9 @@ function ProvisioningConnection({
return (
<div className="rounded-xl bg-background-section p-4">
<p className="system-sm-semibold text-text-primary">
- {t(($) => $['newKnowledge.connectionProvisioning'])}
+ {t(($) => $['newKnowledge.connectionProvisioning'], {
+ provider: FIRECRAWL_CONNECTION_NAME,
+ })}
</p>
{error && (
<p role="alert" className="mt-2 system-xs-regular text-text-destructive">
diff --git a/web/i18n/__tests__/settings.spec.ts b/web/i18n/__tests__/settings.spec.ts
new file mode 100644
index 00000000000..9a2a7a0420f
--- /dev/null
+++ b/web/i18n/__tests__/settings.spec.ts
@@ -0,0 +1,30 @@
+import { createInstance } from 'i18next'
+import app from '../locales/en-US/app.json'
+import common from '../locales/en-US/common.json'
+import { getInitOptions } from '../settings'
+
+describe('default translation namespace', () => {
+ it.each([
+ { namespaces: [] },
+ { namespaces: ['common'] },
+ { namespaces: ['app', 'common'] },
+ ] as const)(
+ 'resolves implicit selectors in app when preloading $namespaces',
+ async ({ namespaces }) => {
+ const i18n = createInstance()
+ await i18n.init({
+ ...getInitOptions(namespaces),
+ lng: 'en-US',
+ resources: { 'en-US': { app, common } },
+ })
+
+ expect(i18n.t(($) => $['gotoAnything.actions.docDesc'])).toBe(
+ app['gotoAnything.actions.docDesc'],
+ )
+ expect(i18n.getFixedT('en-US')(($) => $['gotoAnything.actions.docDesc'])).toBe(
+ app['gotoAnything.actions.docDesc'],
+ )
+ expect(i18n.t(($) => $['operation.save'], { ns: 'common' })).toBe(common['operation.save'])
+ },
+ )
+})
diff --git a/web/i18n/server.ts b/web/i18n/server.ts
index 69942db1a2b..f82332a9a9b 100644
--- a/web/i18n/server.ts
+++ b/web/i18n/server.ts
@@ -24,7 +24,6 @@ const getOrCreateI18next = cache(async (lng: Locale) => {
)
.init({
...getInitOptions([]),
- defaultNS: 'app',
lng,
})
return instance
diff --git a/web/i18n/settings.ts b/web/i18n/settings.ts
index 7731218f1a8..ae33d561ead 100644
--- a/web/i18n/settings.ts
+++ b/web/i18n/settings.ts
@@ -9,7 +9,7 @@ export function getInitOptions(requiredNamespaces: readonly Namespace[] = namesp
load: 'currentOnly',
fallbackLng: defaultLocale,
partialBundledLanguages: true,
- defaultNS: requiredNamespaces.includes(defaultNS) ? defaultNS : 'common',
+ defaultNS,
enableSelector: 'optimize',
keySeparator: false,
ns: [...requiredNamespaces],