()
| 34 | * A chat view component that displays a list of messages and a form for sending new messages. |
| 35 | */ |
| 36 | const ChatView = () => { |
| 37 | const messagesEndRef = useRef(); |
| 38 | const inputRef = useRef(); |
| 39 | const [formValue, setFormValue] = useState(''); |
| 40 | const [thinking, setThinking] = useState(false); |
| 41 | const [selected, setSelected] = useState(options[0]); |
| 42 | const [gpt, setGpt] = useState(gptModel[0]); |
| 43 | const [messages, addMessage] = useContext(ChatContext); |
| 44 | const [modalOpen, setModalOpen] = useState(false); |
| 45 | |
| 46 | /** |
| 47 | * Scrolls the chat area to the bottom. |
| 48 | */ |
| 49 | const scrollToBottom = () => { |
| 50 | messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); |
| 51 | }; |
| 52 | |
| 53 | /** |
| 54 | * Adds a new message to the chat. |
| 55 | * |
| 56 | * @param {string} newValue - The text of the new message. |
| 57 | * @param {boolean} [ai=false] - Whether the message was sent by an AI or the user. |
| 58 | */ |
| 59 | const updateMessage = (newValue, ai = false, selected) => { |
| 60 | const id = Date.now() + Math.floor(Math.random() * 1000000); |
| 61 | const newMsg = { |
| 62 | id: id, |
| 63 | createdAt: Date.now(), |
| 64 | text: newValue, |
| 65 | ai: ai, |
| 66 | selected: `${selected}`, |
| 67 | }; |
| 68 | |
| 69 | addMessage(newMsg); |
| 70 | }; |
| 71 | |
| 72 | /** |
| 73 | * Sends our prompt to our API and get response to our request from openai. |
| 74 | * |
| 75 | * @param {Event} e - The submit event of the form. |
| 76 | */ |
| 77 | const sendMessage = async (e) => { |
| 78 | e.preventDefault(); |
| 79 | |
| 80 | const key = window.localStorage.getItem('api-key'); |
| 81 | if (!key) { |
| 82 | setModalOpen(true); |
| 83 | return; |
| 84 | } |
| 85 | |
| 86 | const cleanPrompt = replaceProfanities(formValue); |
| 87 | |
| 88 | const newMsg = cleanPrompt; |
| 89 | const aiModel = selected; |
| 90 | const gptVersion = gpt; |
| 91 | |
| 92 | setThinking(true); |
| 93 | setFormValue(''); |
nothing calls this directly
no test coverage detected