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.

7.8 KB
Raw Blame
'use client'
import type { OnFeaturesChange } from '@/app/components/base/features/types'
import type { I18nKeysWithPrefix } from '@/types/i18n'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import {
  Select,
  SelectItem,
  SelectItemIndicator,
  SelectItemText,
  SelectList,
  SelectPopup,
  SelectPortal,
  SelectPositioner,
  SelectTrigger,
} from '@langgenius/dify-ui/select'
import { Switch } from '@langgenius/dify-ui/switch'
import { skipToken, useQuery } from '@tanstack/react-query'
import { produce } from 'immer'
import { useId } from 'react'
import { useTranslation } from 'react-i18next'
import { replace } from 'string-ts'
import { AudioBtn } from '@/app/components/base/audio-btn'
import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'
import { languages } from '@/i18n/language'
import { useParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { TtsAutoPlay } from '@/types/app'

type SelectOption = {
  value: string
  name: string
}

type VoiceParamConfigProps = {
  onClose: () => void
  onChange?: OnFeaturesChange
}
const VoiceParamConfig = ({ onClose, onChange }: VoiceParamConfigProps) => {
  const languageLabelId = useId()

  const { t } = useTranslation(['appApi', 'appDebug', 'common'])
  const params = useParams<{ appId?: string; agentId?: string }>()
  const text2speech = useFeatures((state) => state.features.text2speech)
  const featuresStore = useFeaturesStore()
  const formatLanguageName = (item: SelectOption) => {
    const key = `voice.language.${replace(item.value, '-', '')}` as I18nKeysWithPrefix<
      'common',
      'voice.language.'
    >
    return t(($) => $[key], { ns: 'common', defaultValue: item.name })
  }

  let languageItem = languages.find((item) => item.value === text2speech?.language)
  if (languages && !languageItem) languageItem = languages[0]
  const localLanguagePlaceholder =
    languageItem?.name || t(($) => $['placeholder.select'], { ns: 'common' })

  const language = languageItem?.value
  const { data: voiceItems } = useQuery(
    params.agentId
      ? consoleQuery.agent.byAgentId.textToAudio.voices.get.queryOptions({
          input: {
            params: { agent_id: params.agentId },
            query: { language: language || 'en-US' },
          },
        })
      : consoleQuery.apps.byAppId.textToAudio.voices.get.queryOptions({
          input: params.appId
            ? {
                params: { app_id: params.appId },
                query: { language: language || 'en-US' },
              }
            : skipToken,
        }),
  )
  let voiceItem = voiceItems?.find((item) => item.value === text2speech?.voice)
  if (voiceItems && !voiceItem) voiceItem = voiceItems[0]
  const localVoicePlaceholder =
    voiceItem?.name || t(($) => $['placeholder.select'], { ns: 'common' })

  const handleChange = (value: Record<string, string>) => {
    const { features, setFeatures } = featuresStore!.getState()

    const newFeatures = produce(features, (draft) => {
      draft.text2speech = {
        ...draft.text2speech,
        ...value,
      }
    })

    setFeatures(newFeatures)
    if (onChange) onChange()
  }

  return (
    <>
      <div className="mb-4 flex items-center justify-between">
        <div className="system-xl-semibold text-text-primary">
          {t(($) => $['voice.voiceSettings.title'], { ns: 'appDebug' })}
        </div>
        <button
          type="button"
          className="rounded-md border-none bg-transparent p-1 hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"
          aria-label={t(($) => $['operation.close'], { ns: 'common' })}
          onClick={onClose}
        >
          <span aria-hidden className="i-ri-close-line size-4 text-text-tertiary" />
        </button>
      </div>
      <div className="mb-3">
        <div className="mb-1 flex items-center py-1 system-sm-semibold text-text-secondary">
          <span id={languageLabelId}>
            {t(($) => $['voice.voiceSettings.language'], { ns: 'appDebug' })}
          </span>
          <Infotip>
            <InfotipTrigger aria-labelledby={languageLabelId} />
            <InfotipContent aria-labelledby={languageLabelId} className="w-45 whitespace-pre-wrap">
              {t(($) => $['voice.voiceSettings.resolutionTooltip'], { ns: 'appDebug' })}
            </InfotipContent>
          </Infotip>
        </div>
        <Select
          value={languageItem?.value ?? null}
          onValueChange={(nextValue) => {
            if (nextValue == null) return
            handleChange({
              language: nextValue,
            })
          }}
        >
          <SelectTrigger
            aria-label={t(($) => $['voice.voiceSettings.language'], { ns: 'appDebug' })}
            className="w-full"
          >
            {languageItem ? formatLanguageName(languageItem) : localLanguagePlaceholder}
          </SelectTrigger>
          <SelectPortal>
            <SelectPositioner>
              <SelectPopup>
                <SelectList className="max-h-60">
                  {languages.map((item) => (
                    <SelectItem key={item.value} value={item.value}>
                      <SelectItemText>{formatLanguageName(item)}</SelectItemText>
                      <SelectItemIndicator />
                    </SelectItem>
                  ))}
                </SelectList>
              </SelectPopup>
            </SelectPositioner>
          </SelectPortal>
        </Select>
      </div>
      <div className="mb-3">
        <div className="mb-1 py-1 system-sm-semibold text-text-secondary">
          {t(($) => $['voice.voiceSettings.voice'], { ns: 'appDebug' })}
        </div>
        <div className="flex items-center gap-1">
          <Select
            value={voiceItem?.value ?? null}
            disabled={!languageItem}
            onValueChange={(nextValue) => {
              if (nextValue == null || nextValue === '') return
              handleChange({
                voice: nextValue,
              })
            }}
          >
            <div className="grow">
              <SelectTrigger
                aria-label={t(($) => $['voice.voiceSettings.voice'], { ns: 'appDebug' })}
                className="w-full"
              >
                {voiceItem?.name ?? localVoicePlaceholder}
              </SelectTrigger>
              <SelectPortal>
                <SelectPositioner>
                  <SelectPopup>
                    <SelectList className="max-h-60">
                      {voiceItems?.map((item: SelectOption) => (
                        <SelectItem key={item.value} value={item.value}>
                          <SelectItemText>{item.name}</SelectItemText>
                          <SelectItemIndicator />
                        </SelectItem>
                      ))}
                    </SelectList>
                  </SelectPopup>
                </SelectPositioner>
              </SelectPortal>
            </div>
          </Select>
          {languageItem?.example && (
            <div
              className="h-8 shrink-0 rounded-lg bg-components-button-tertiary-bg p-1"
              role="group"
              aria-label={t(($) => $.play, { ns: 'appApi', defaultValue: 'Play' })}
            >
              <AudioBtn value={languageItem?.example} isAudition voice={voiceItem?.value} />
            </div>
          )}
        </div>
      </div>
      <div>
        <div className="mb-1 py-1 system-sm-semibold text-text-secondary">
          {t(($) => $['voice.voiceSettings.autoPlay'], { ns: 'appDebug' })}
        </div>
        <Switch
          className="shrink-0"
          checked={text2speech?.autoPlay === TtsAutoPlay.enabled}
          onCheckedChange={(value: boolean) => {
            handleChange({
              autoPlay: value ? TtsAutoPlay.enabled : TtsAutoPlay.disabled,
            })
          }}
        />
      </div>
    </>
  )
}

export default VoiceParamConfig