Merge pull request #383 from danditomaso/feat/debounce-messages-input

Add debounce to message input field
This commit is contained in:
Dan Ditomaso
2025-01-28 15:36:53 -05:00
committed by GitHub
2 changed files with 57 additions and 27 deletions
@@ -1,8 +1,10 @@
import { debounce } from "@app/core/utils/debounce";
import { Button } from "@components/UI/Button.tsx"; import { Button } from "@components/UI/Button.tsx";
import { Input } from "@components/UI/Input.tsx"; import { Input } from "@components/UI/Input.tsx";
import { useDevice } from "@core/stores/deviceStore.ts"; import { useDevice } from "@core/stores/deviceStore.ts";
import type { Types } from "@meshtastic/js"; import type { Types } from "@meshtastic/js";
import { SendIcon } from "lucide-react"; import { SendIcon } from "lucide-react";
import { useCallback, useMemo, useState } from "react";
export interface MessageInputProps { export interface MessageInputProps {
to: Types.Destination; to: Types.Destination;
@@ -20,10 +22,16 @@ export const MessageInput = ({
setMessageDraft, setMessageDraft,
hardware, hardware,
} = useDevice(); } = useDevice();
const myNodeNum = hardware.myNodeNum; const myNodeNum = hardware.myNodeNum;
const [localDraft, setLocalDraft] = useState(messageDraft);
const sendText = async (message: string) => { const debouncedSetMessageDraft = useMemo(
() => debounce(setMessageDraft, 300),
[setMessageDraft],
);
const sendText = useCallback(
async (message: string) => {
await connection await connection
?.sendText(message, to, true, channel) ?.sendText(message, to, true, channel)
.then((id) => .then((id) =>
@@ -46,6 +54,14 @@ export const MessageInput = ({
e.error, e.error,
), ),
); );
},
[channel, connection, myNodeNum, setMessageState, to],
);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setLocalDraft(newValue);
debouncedSetMessageDraft(newValue);
}; };
return ( return (
@@ -54,7 +70,8 @@ export const MessageInput = ({
className="w-full" className="w-full"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
sendText(messageDraft); sendText(localDraft);
setLocalDraft("");
setMessageDraft(""); setMessageDraft("");
}} }}
> >
@@ -64,8 +81,8 @@ export const MessageInput = ({
autoFocus={true} autoFocus={true}
minLength={1} minLength={1}
placeholder="Enter Message" placeholder="Enter Message"
value={messageDraft} value={localDraft}
onChange={(e) => setMessageDraft(e.target.value)} onChange={handleInputChange}
/> />
</span> </span>
<Button type="submit"> <Button type="submit">
+13
View File
@@ -0,0 +1,13 @@
type Callback<Args extends unknown[]> = (...args: Args) => void;
export function debounce<Args extends unknown[]>(
callback: Callback<Args>,
wait: number,
): Callback<Args> {
let timeoutId: ReturnType<typeof setTimeout>;
return (...args: Args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => callback(...args), wait);
};
}