File size: 2,504 Bytes
ba76bdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"use client";

import React from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Send, Paperclip } from 'lucide-react';

interface MessageFormProps {
  input: string;
  setInput: (value: string) => void;
  handleSendMessage: (e: React.FormEvent<HTMLFormElement>) => Promise<void>;
  isLoading: boolean;
  handleFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  isFileSelected: boolean;
}

export default function MessageForm({
  input,
  setInput,
  handleSendMessage,
  isLoading,
  handleFileChange,
  isFileSelected,
}: MessageFormProps) {
  const fileInputRef = React.useRef<HTMLInputElement>(null);

  const handleAttachClick = () => {
    fileInputRef.current?.click();
  }

  const handleFileReset = (e: React.MouseEvent<HTMLInputElement>) => {
    // Reset file input value so the same file can be selected again
    (e.target as HTMLInputElement).value = '';
  }

  return (
    <form onSubmit={handleSendMessage} className="relative flex w-full items-center">
      <Button 
        type="button" 
        variant="ghost" 
        size="icon" 
        disabled={isLoading} 
        onClick={handleAttachClick} 
        className="absolute left-3 top-1/2 -translate-y-1/2 h-8 w-8 shrink-0 rounded-full"
      >
        <Paperclip className="h-4 w-4" />
        <span className="sr-only">Attach file</span>
      </Button>
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileChange}
        onClick={handleFileReset}
        className="hidden"
        accept="image/*"
        disabled={isLoading}
      />
      <Input
        type="text"
        placeholder="Type a message..."
        value={input}
        onChange={(e) => setInput(e.target.value)}
        disabled={isLoading}
        className="flex-1 rounded-full border bg-input pr-12 pl-12 py-6 shadow-lg focus-visible:ring-0 focus-visible:ring-offset-0"
        autoComplete="off"
        onKeyDown={(e) => {
          if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            const form = e.target as HTMLInputElement;
            form.form?.requestSubmit();
          }
        }}
      />
      <Button type="submit" size="icon" disabled={isLoading || (!input.trim() && !isFileSelected)} className="absolute right-3 top-1/2 -translate-y-1/2 h-8 w-8 shrink-0 rounded-full">
        <Send className="h-4 w-4" />
        <span className="sr-only">Send</span>
      </Button>
    </form>
  );
}