Skip to content

Commit

Permalink
nextjs input box fixes - smoother behavior of expanding and shrinking…
Browse files Browse the repository at this point in the history
… appropriately based on user input - resets cleanly on submit & doesn't bounce as user types
  • Loading branch information
ElishaKay committed Nov 1, 2024
1 parent dbacc94 commit 6971b20
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions frontend/nextjs/components/InputArea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ type TInputAreaProps = {
reset?: () => void;
};

// Debounce function to limit the rate at which a function can fire
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}

const InputArea: FC<TInputAreaProps> = ({
promptValue,
setPromptValue,
Expand Down Expand Up @@ -47,6 +60,18 @@ const InputArea: FC<TInputAreaProps> = ({
}
};

// Debounced version of the height adjustment function
const adjustHeight = debounce((target) => {
target.style.height = 'auto'; // Reset height to auto to allow shrinking
target.style.height = `${target.scrollHeight}px`; // Adjust height
}, 100); // Adjust the delay as needed

const handleTextareaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const target = e.target;
adjustHeight(target); // Use debounced function
setPromptValue(target.value);
};

return (
<form
className="mx-auto flex pt-2 pb-2 w-full items-center justify-between rounded-lg border bg-white px-3 shadow-[2px_2px_38px_0px_rgba(0,0,0,0.25),0px_-2px_4px_0px_rgba(0,0,0,0.25)_inset,1px_2px_4px_0px_rgba(0,0,0,0.25)_inset]"
Expand Down Expand Up @@ -95,17 +120,13 @@ const InputArea: FC<TInputAreaProps> = ({
ref={textareaRef}
className="focus-visible::outline-0 my-1 w-full pl-5 font-light not-italic leading-[normal]
text-[#1B1B16]/30 text-black outline-none focus-visible:ring-0 focus-visible:ring-offset-0
sm:text-xl min-h-[3em] resize-none overflow-hidden"
sm:text-xl min-h-[3em] resize-none"
disabled={disabled}
value={promptValue}
required
rows={2}
onKeyDown={handleKeyDown}
onChange={(e) => {
// e.target.style.height = 'auto'; // Reset height to auto to allow shrinking
e.target.style.height = `${e.target.scrollHeight}px`; // Adjust height
setPromptValue(e.target.value);
}}
onChange={handleTextareaChange}
/>
<button
disabled={disabled}
Expand Down

0 comments on commit 6971b20

Please sign in to comment.