ChatInput.tsx 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { ChatContext } from '@/app/chat-context';
  2. import { apiInterceptors, newDialogue } from '@/client/api';
  3. import { STORAGE_INIT_MESSAGE_KET } from '@/utils';
  4. import { Button, Input } from 'antd';
  5. import cls from 'classnames';
  6. import { useRouter } from 'next/router';
  7. import { useContext, useState } from 'react';
  8. import { useTranslation } from 'react-i18next';
  9. function ChatInput() {
  10. const { setCurrentDialogInfo } = useContext(ChatContext);
  11. const { t } = useTranslation();
  12. const router = useRouter();
  13. const [userInput, setUserInput] = useState<string>('');
  14. const [isFocus, setIsFocus] = useState<boolean>(false);
  15. const [isZhInput, setIsZhInput] = useState<boolean>(false);
  16. const onSubmit = async () => {
  17. const [, res] = await apiInterceptors(newDialogue({ chat_mode: 'chat_normal' }));
  18. if (res) {
  19. setCurrentDialogInfo?.({
  20. chat_scene: res.chat_mode,
  21. app_code: res.chat_mode,
  22. });
  23. localStorage.setItem(
  24. 'cur_dialog_info',
  25. JSON.stringify({
  26. chat_scene: res.chat_mode,
  27. app_code: res.chat_mode,
  28. }),
  29. );
  30. localStorage.setItem(STORAGE_INIT_MESSAGE_KET, JSON.stringify({ id: res.conv_uid, message: userInput }));
  31. router.push(`/chat/?scene=chat_normal&id=${res.conv_uid}`);
  32. }
  33. setUserInput('');
  34. };
  35. return (
  36. <div
  37. className={`flex flex-1 h-12 p-2 pl-4 items-center justify-between bg-white dark:bg-[#242733] dark:border-[#6f7f95] rounded-xl border-t border-b border-l border-r ${
  38. isFocus ? 'border-[#0c75fc]' : ''
  39. }`}
  40. >
  41. <Input.TextArea
  42. placeholder={t('input_tips')}
  43. className='w-full resize-none border-0 p-0 focus:shadow-none'
  44. value={userInput}
  45. autoSize={{ minRows: 1 }}
  46. onKeyDown={e => {
  47. if (e.key === 'Enter') {
  48. if (e.shiftKey) {
  49. return;
  50. }
  51. if (isZhInput) {
  52. return;
  53. }
  54. e.preventDefault();
  55. if (!userInput.trim()) {
  56. return;
  57. }
  58. onSubmit();
  59. }
  60. }}
  61. onChange={e => {
  62. setUserInput(e.target.value);
  63. }}
  64. onFocus={() => {
  65. setIsFocus(true);
  66. }}
  67. onBlur={() => setIsFocus(false)}
  68. onCompositionStart={() => setIsZhInput(true)}
  69. onCompositionEnd={() => setIsZhInput(false)}
  70. />
  71. <Button
  72. type='primary'
  73. className={cls('flex items-center justify-center w-14 h-8 rounded-lg text-sm bg-button-gradient border-0', {
  74. 'opacity-40 cursor-not-allowed': !userInput.trim(),
  75. })}
  76. onClick={() => {
  77. if (!userInput.trim()) {
  78. return;
  79. }
  80. onSubmit();
  81. }}
  82. >
  83. {t('sent')}
  84. </Button>
  85. </div>
  86. );
  87. }
  88. export default ChatInput;