import { memo, useEffect, useMemo, useState, } from 'react' import { RiAddLine, RiArrowDownSLine, RiKey2Line, } from '@remixicon/react' import { useTranslation } from 'react-i18next' import { PortalToFollowElem, PortalToFollowElemContent, PortalToFollowElemTrigger, } from '@/app/components/base/portal-to-follow-elem' import Authorize from './authorize' import Authorized from './authorized' import AddApiKeyButton from './authorize/add-api-key-button' import AddOAuthButton from './authorize/add-oauth-button' import EndUserCredentialSection from './end-user-credential-section' import Item from './authorized/item' import type { PluginPayload } from './types' import { usePluginAuth } from './hooks/use-plugin-auth' import cn from '@/utils/classnames' type PluginAuthProps = { pluginPayload: PluginPayload children?: React.ReactNode className?: string showConnectGuide?: boolean endUserCredentialEnabled?: boolean endUserCredentialType?: string onEndUserCredentialTypeChange?: (type: string) => void onEndUserCredentialChange?: (enabled: boolean) => void } const PluginAuth = ({ pluginPayload, children, className, showConnectGuide, endUserCredentialEnabled, endUserCredentialType, onEndUserCredentialTypeChange, onEndUserCredentialChange, }: PluginAuthProps) => { const { t } = useTranslation() const { isAuthorized, canOAuth, canApiKey, credentials, disabled, invalidPluginCredentialInfo, notAllowCustomCredential, hasOAuthClientConfigured, } = usePluginAuth(pluginPayload, !!pluginPayload.provider) const shouldShowGuide = !!showConnectGuide const [showCredentialPanel, setShowCredentialPanel] = useState(false) const [showAddMenu, setShowAddMenu] = useState(false) const configuredDisabled = !!endUserCredentialEnabled const shouldShowAuthorizeCard = useMemo(() => { const hasCredential = credentials.length > 0 const canAdd = canOAuth || canApiKey || hasOAuthClientConfigured return !hasCredential && canAdd }, [credentials.length, canOAuth, canApiKey, hasOAuthClientConfigured]) const containerClassName = useMemo(() => { if (showConnectGuide) return className return !isAuthorized ? className : undefined }, [isAuthorized, className, showConnectGuide]) useEffect(() => { if (isAuthorized) setShowCredentialPanel(false) }, [isAuthorized]) const credentialList = useMemo(() => { return (
{ credentials.length > 0 ? (
{credentials.map(credential => ( ))}
) : null }
) }, [credentials, t]) const endUserSwitch = ( ) return (
{ shouldShowGuide && (
{t('plugin.auth.configuredCredentials.title')}
{t('plugin.auth.configuredCredentials.desc')}
{ canOAuth && ( { setShowAddMenu(false) invalidPluginCredentialInfo() }} /> ) } { canApiKey && ( { setShowAddMenu(false) invalidPluginCredentialInfo() }} /> ) }
{credentialList}
{ shouldShowAuthorizeCard && (
) }
{endUserSwitch}
) } { !shouldShowGuide && !isAuthorized && ( ) } { isAuthorized && !children && ( ) } { isAuthorized && children }
) } export default memo(PluginAuth)