SerpapiPlugin.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { useTranslation } from 'react-i18next'
  2. import Image from 'next/image'
  3. import SerpapiLogo from '../../assets/serpapi.png'
  4. import KeyValidator from '../key-validator'
  5. import type { Form, ValidateValue } from '../key-validator/declarations'
  6. import { updatePluginKey, validatePluginKey } from './utils'
  7. import { useToastContext } from '@/app/components/base/toast'
  8. import type { PluginProvider } from '@/models/common'
  9. import { useAppContext } from '@/context/app-context'
  10. type SerpapiPluginProps = {
  11. plugin: PluginProvider
  12. onUpdate: () => void
  13. }
  14. const SerpapiPlugin = ({
  15. plugin,
  16. onUpdate,
  17. }: SerpapiPluginProps) => {
  18. const { t } = useTranslation()
  19. const { isCurrentWorkspaceManager } = useAppContext()
  20. const { notify } = useToastContext()
  21. const forms: Form[] = [{
  22. key: 'api_key',
  23. title: t('common.plugin.serpapi.apiKey'),
  24. placeholder: t('common.plugin.serpapi.apiKeyPlaceholder'),
  25. value: plugin.credentials?.api_key,
  26. validate: {
  27. before: (v) => {
  28. if (v?.api_key)
  29. return true
  30. },
  31. run: async (v) => {
  32. return validatePluginKey('serpapi', {
  33. credentials: {
  34. api_key: v?.api_key,
  35. },
  36. })
  37. },
  38. },
  39. handleFocus: (v, dispatch) => {
  40. if (v.api_key === plugin.credentials?.api_key)
  41. dispatch({ ...v, api_key: '' })
  42. },
  43. }]
  44. const handleSave = async (v: ValidateValue) => {
  45. if (!v?.api_key || v?.api_key === plugin.credentials?.api_key)
  46. return
  47. const res = await updatePluginKey('serpapi', {
  48. credentials: {
  49. api_key: v?.api_key,
  50. },
  51. })
  52. if (res.status === 'success') {
  53. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  54. onUpdate()
  55. return true
  56. }
  57. }
  58. return (
  59. <KeyValidator
  60. type='serpapi'
  61. title={<Image alt='serpapi logo' src={SerpapiLogo} width={64} />}
  62. status={plugin.credentials?.api_key ? 'success' : 'add'}
  63. forms={forms}
  64. keyFrom={{
  65. text: t('common.plugin.serpapi.keyFrom'),
  66. link: 'https://serpapi.com/manage-api-key',
  67. }}
  68. onSave={handleSave}
  69. disabled={!isCurrentWorkspaceManager}
  70. />
  71. )
  72. }
  73. export default SerpapiPlugin