form.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { useCallback } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import { useEmbeddedChatbotContext } from '../context'
  4. import Input from './form-input'
  5. import { PortalSelect } from '@/app/components/base/select'
  6. const Form = () => {
  7. const { t } = useTranslation()
  8. const {
  9. inputsForms,
  10. newConversationInputs,
  11. handleNewConversationInputsChange,
  12. isMobile,
  13. } = useEmbeddedChatbotContext()
  14. const handleFormChange = useCallback((variable: string, value: string) => {
  15. handleNewConversationInputsChange({
  16. ...newConversationInputs,
  17. [variable]: value,
  18. })
  19. }, [newConversationInputs, handleNewConversationInputsChange])
  20. const renderField = (form: any) => {
  21. const {
  22. label,
  23. required,
  24. variable,
  25. options,
  26. } = form
  27. if (form.type === 'text-input' || form.type === 'paragraph') {
  28. return (
  29. <Input
  30. form={form}
  31. value={newConversationInputs[variable]}
  32. onChange={handleFormChange}
  33. />
  34. )
  35. }
  36. if (form.type === 'number') {
  37. return (
  38. <input
  39. className="grow h-9 rounded-lg bg-gray-100 px-2.5 outline-none appearance-none"
  40. type="number"
  41. value={newConversationInputs[variable] || ''}
  42. onChange={e => handleFormChange(variable, e.target.value)}
  43. placeholder={`${label}${!required ? `(${t('appDebug.variableTable.optional')})` : ''}`}
  44. />
  45. )
  46. }
  47. return (
  48. <PortalSelect
  49. popupClassName='w-[200px]'
  50. value={newConversationInputs[variable]}
  51. items={options.map((option: string) => ({ value: option, name: option }))}
  52. onSelect={item => handleFormChange(variable, item.value as string)}
  53. placeholder={`${label}${!required ? `(${t('appDebug.variableTable.optional')})` : ''}`}
  54. />
  55. )
  56. }
  57. if (!inputsForms.length)
  58. return null
  59. return (
  60. <div className='mb-4 py-2'>
  61. {
  62. inputsForms.map(form => (
  63. <div
  64. key={form.variable}
  65. className={`flex mb-3 last-of-type:mb-0 text-sm text-gray-900 ${isMobile && '!flex-wrap'}`}
  66. >
  67. <div className={`shrink-0 mr-2 py-2 w-[128px] ${isMobile && '!w-full'}`}>{form.label}</div>
  68. {renderField(form)}
  69. </div>
  70. ))
  71. }
  72. </div>
  73. )
  74. }
  75. export default Form