Skip to content

Commit

Permalink
Merge pull request lencx#1373 from imsharukh1994/imsharukh1994-patch-1
Browse files Browse the repository at this point in the history
Enhance ChatInput Component: Add Error Handling and Debounce Sync
  • Loading branch information
lencx authored Aug 29, 2024
2 parents ef74c4a + 4586e44 commit a6de9a8
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/view/Ask.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,31 @@
import { useState, useEffect, useRef } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { useHotkeys } from 'react-hotkeys-hook';

import useInfo from '~hooks/useInfo';
import SendIcon from '~icons/Send';
import debounce from 'lodash/debounce';

export default function ChatInput() {
const inputRef = useRef<HTMLTextAreaElement>(null);
const [message, setMessage] = useState('');
const { isMac } = useInfo();

useEffect(() => {
invoke('ask_sync', { message: JSON.stringify(message) });
}, [message])
const syncMessage = debounce(async () => {
try {
await invoke('ask_sync', { message: JSON.stringify(message) });
} catch (error) {
console.error('Error syncing message:', error);
}
}, 300); // Debounce by 300ms

syncMessage();
return () => syncMessage.cancel(); // Cleanup debounce on unmount
}, [message]);

useHotkeys(isMac ? 'meta+enter' : 'ctrl+enter', async (event: KeyboardEvent) => {
event.preventDefault();
handleSend();
await handleSend();
}, {
enableOnFormTags: true,
}, [message]);
Expand All @@ -27,7 +36,11 @@ export default function ChatInput() {

const handleSend = async () => {
if (!message) return;
await invoke('ask_send', { message: JSON.stringify(message) });
try {
await invoke('ask_send', { message: JSON.stringify(message) });
} catch (error) {
console.error('Error sending message:', error);
}
setMessage('');
if (inputRef.current) {
inputRef.current.value = '';
Expand All @@ -50,6 +63,7 @@ export default function ChatInput() {
className="absolute right-2 text-gray-400/80 dark:text-gray-600 cursor-pointer"
onClick={handleSend}
title={`Send message (${isMac ? '⌘⏎' : '⌃⏎'})`}
aria-label="Send message"
/>
</div>
);
Expand Down

0 comments on commit a6de9a8

Please sign in to comment.