import { memo, useCallback, useEffect, useMemo, useState, } from 'react' import type { ReactNode } from 'react' import { RiArrowDownSLine, RiEqualizer2Line, RiKey2Line, RiUserStarLine, } from '@remixicon/react' import { useTranslation } from 'react-i18next' import AddOAuthButton from './authorize/add-oauth-button' import AddApiKeyButton from './authorize/add-api-key-button' import type { PluginPayload } from './types' import cn from '@/utils/classnames' import Switch from '@/app/components/base/switch' import { PortalToFollowElem, PortalToFollowElemContent, PortalToFollowElemTrigger, } from '@/app/components/base/portal-to-follow-elem' export type EndUserCredentialSectionProps = { pluginPayload: PluginPayload canOAuth?: boolean canApiKey?: boolean disabled?: boolean useEndUserCredentialEnabled?: boolean endUserCredentialType?: string onEndUserCredentialChange?: (enabled: boolean) => void onEndUserCredentialTypeChange?: (type: string) => void onCredentialAdded?: () => void className?: string } const EndUserCredentialSection = ({ pluginPayload, canOAuth, canApiKey, disabled, useEndUserCredentialEnabled, endUserCredentialType, onEndUserCredentialChange, onEndUserCredentialTypeChange, onCredentialAdded, className, }: EndUserCredentialSectionProps) => { const { t } = useTranslation() const [showEndUserTypeMenu, setShowEndUserTypeMenu] = useState(false) const availableEndUserTypes = useMemo(() => { const list: { value: string; label: string; icon: ReactNode }[] = [] if (canOAuth) { list.push({ value: 'oauth2', label: t('plugin.auth.endUserCredentials.optionOAuth'), icon: , }) } if (canApiKey) { list.push({ value: 'api-key', label: t('plugin.auth.endUserCredentials.optionApiKey'), icon: , }) } return list }, [canOAuth, canApiKey, t]) const endUserCredentialLabel = useMemo(() => { const found = availableEndUserTypes.find(item => item.value === endUserCredentialType) return found?.label || availableEndUserTypes[0]?.label || '-' }, [availableEndUserTypes, endUserCredentialType]) useEffect(() => { if (!useEndUserCredentialEnabled) return if (!availableEndUserTypes.length) return const isValid = availableEndUserTypes.some(item => item.value === endUserCredentialType) if (!isValid) onEndUserCredentialTypeChange?.(availableEndUserTypes[0].value) }, [useEndUserCredentialEnabled, endUserCredentialType, availableEndUserTypes, onEndUserCredentialTypeChange]) const handleSelectEndUserType = useCallback((value: string) => { onEndUserCredentialTypeChange?.(value) setShowEndUserTypeMenu(false) }, [onEndUserCredentialTypeChange]) return (
{t('plugin.auth.endUserCredentials.title')}
{t('plugin.auth.endUserCredentials.desc')}
{ useEndUserCredentialEnabled && availableEndUserTypes.length > 0 && (
{t('plugin.auth.endUserCredentials.typeLabel')}
{canOAuth && ( { handleSelectEndUserType('oauth2') onCredentialAdded?.() }} /> )} {canApiKey && ( { handleSelectEndUserType('api-key') onCredentialAdded?.() }} /> )}
) }
) } export default memo(EndUserCredentialSection)