Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 80 additions & 6 deletions src/components/Textarea.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import { cva, VariantProps } from 'class-variance-authority';
import * as React from 'react';
import { cn } from '../utils';
import {
ChangeEvent,
forwardRef,
TextareaHTMLAttributes,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
useState,
} from 'react';
import { cn, throttle } from '../utils';

const variants = cva('textarea min-h-auto resize-none', {
variants: {
Expand All @@ -21,10 +31,10 @@ const variants = cva('textarea min-h-auto resize-none', {
},
});

export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement> &
export type TextAreaProps = TextareaHTMLAttributes<HTMLTextAreaElement> &
VariantProps<typeof variants>;

const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
({ className, variant, size, ...props }, ref) => (
<textarea
className={cn(variants({ variant, size, className }))}
Expand All @@ -34,6 +44,70 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
/>
)
);
Textarea.displayName = 'Textarea';
TextArea.displayName = 'TextArea';

export { Textarea };
const AutoSizingTextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
({ value: initial, onChange, ...props }, ref) => {
const textAreaRef = useRef<HTMLTextAreaElement>(null);
useImperativeHandle(ref, () => textAreaRef.current!, []);

const [value, setValue] = useState<
string | number | readonly string[] | undefined
>('');

useEffect(() => {
setValue(initial);
}, [initial]);

const handleChange = useCallback(
(event: ChangeEvent<HTMLTextAreaElement>) => {
setValue(event.target.value);
if (onChange) onChange(event);
},
[onChange]
);

const adjustHeight = throttle((textarea: HTMLTextAreaElement | null) => {
if (!textarea) return;

// Only perform auto-sizing on large screens (matching Tailwind's xl: breakpoint)
if (!window.matchMedia('(min-width: 1280px)').matches) {
// On small screens, reset inline height and max-height styles.
// This allows CSS (e.g., `rows` attribute or classes) to control the height,
// and enables manual resizing if `resize-vertical` is set.
textarea.style.height = ''; // Use 'auto' or '' to reset
textarea.style.maxHeight = '';
return; // Do not adjust height programmatically on small screens
}

const computedStyle = window.getComputedStyle(textarea);
// Get the max-height specified by CSS (e.g., from `xl:max-h-48`)
const currentMaxHeight = computedStyle.maxHeight;

// Temporarily remove max-height to allow scrollHeight to be calculated correctly
textarea.style.maxHeight = 'none';
// Reset height to 'auto' to measure the actual scrollHeight needed
textarea.style.height = 'auto';
// Set the height to the calculated scrollHeight
textarea.style.height = textarea.scrollHeight + 2 + 'px';
// Re-apply the original max-height from CSS to enforce the limit
textarea.style.maxHeight = currentMaxHeight;
}, 100);

useLayoutEffect(() => {
adjustHeight(textAreaRef?.current);
}, [adjustHeight, ref, value]);

return (
<TextArea
ref={textAreaRef}
value={value}
onChange={handleChange}
{...props}
/>
);
}
);
AutoSizingTextArea.displayName = 'AutoSizingTextArea';

export { AutoSizingTextArea, TextArea };
104 changes: 0 additions & 104 deletions src/hooks/useChatTextarea.ts

This file was deleted.

6 changes: 3 additions & 3 deletions src/pages/Chat/components/CanvasPyInterpreter.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Icon, Textarea } from '../../../components';
import { Button, Icon, TextArea } from '../../../components';
import LocalStorage from '../../../database/localStorage';
import { useChatContext } from '../../../store/chat';
import { CanvasType } from '../../../types';
Expand Down Expand Up @@ -162,7 +162,7 @@ export default function CanvasPyInterpreter() {
</Button>
</div>
<div className="grid grid-rows-3 gap-4 h-full">
<Textarea
<TextArea
className="h-full font-mono"
size="full"
value={code}
Expand Down Expand Up @@ -196,7 +196,7 @@ export default function CanvasPyInterpreter() {
</OpenInNewTab>
</span>
</div>
<Textarea
<TextArea
className="h-full font-mono dark-color"
size="full"
value={output}
Expand Down
56 changes: 34 additions & 22 deletions src/pages/Chat/components/ChatInput.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { memo, useCallback, useEffect, useMemo } from 'react';
import {
ChangeEvent,
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import toast from 'react-hot-toast';
import { useTranslation } from 'react-i18next';
import { TbAdjustmentsHorizontal } from 'react-icons/tb';
import { useNavigate } from 'react-router';
import { Button, Icon, Label, Textarea } from '../../../components';
import {
ChatTextareaApi,
useChatTextarea,
} from '../../../hooks/useChatTextarea';
import { AutoSizingTextArea, Button, Icon, Label } from '../../../components';
import { useFileUpload } from '../../../hooks/useFileUpload';
import SpeechToText, {
IS_SPEECH_RECOGNITION_SUPPORTED,
Expand All @@ -28,54 +32,61 @@ export const ChatInput = memo(
const { t } = useTranslation();
const navigate = useNavigate();
const { prefilledContent, isPrefilledSend } = usePrefilledMessage();
const textarea: ChatTextareaApi = useChatTextarea(prefilledContent);
const extraContext = useFileUpload();
const { isGenerating, stopGenerating } = useChatContext();

const textAreaRef = useRef<HTMLTextAreaElement>(null);
const [textAreaValue, setTextAreaValue] = useState('');

const isPending = useMemo(
() => (!convId ? false : isGenerating(convId)),
[convId, isGenerating]
);

const handleChange = useCallback(
(event: ChangeEvent<HTMLTextAreaElement>) => {
setTextAreaValue(event.target.value);
},
[]
);

const handleStop = useCallback(() => {
if (!convId) return;
stopGenerating(convId);
}, [convId, stopGenerating]);

const handleRecord: SpeechRecordCallback = useCallback(
(text: string) => textarea.setValue(text),
[textarea]
);
const handleRecord: SpeechRecordCallback = useCallback((text: string) => {
setTextAreaValue(text);
}, []);

const sendNewMessage = async () => {
const lastInpMsg = textarea.value();
const lastInpMsg = textAreaValue;
if (lastInpMsg.trim().length === 0) {
toast.error(t('chatInput.errors.emptyMessage'));
return;
}

textarea.setValue('');
setTextAreaValue('');
if (!(await onSend(lastInpMsg, extraContext.items))) {
// restore the input message if failed
textarea.setValue(lastInpMsg);
setTextAreaValue(lastInpMsg);
}
// OK
extraContext.clearItems();
};

// for vscode context
textarea.refOnSubmit.current = sendNewMessage;

useEffect(() => {
if (!textAreaRef.current) return;

// set textarea with prefilled value
if (prefilledContent) {
textarea.setValue(prefilledContent);
setTextAreaValue(prefilledContent);
}

// send the prefilled message if needed
// otherwise, focus on the input
if (isPrefilledSend) sendNewMessage();
else textarea.focus();
else textAreaRef.current.focus();

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isPrefilledSend, prefilledContent]);
Expand All @@ -91,15 +102,16 @@ export const ChatInput = memo(
disabled={isPending}
>
<div className="bg-base-200 flex flex-col lg:border-1 lg:border-base-content/30 rounded-lg shadow-sm md:shadow-md p-2">
<Textarea
<AutoSizingTextArea
// Default (mobile): Enable vertical resize, overflow auto for scrolling if needed
// Large screens (lg:): Disable manual resize, apply max-height for autosize limit
className="text-base p-0 px-2"
variant="transparent"
size="full"
placeholder={t('chatInput.placeholder')}
ref={textarea.ref}
onInput={textarea.onInput} // Hook's input handler (will only resize height on lg+ screens)
ref={textAreaRef}
value={textAreaValue}
onChange={handleChange}
onKeyDown={(e) => {
if (e.nativeEvent.isComposing || e.keyCode === 229) return;
if (e.key === 'Enter' && !e.shiftKey) {
Expand Down
4 changes: 2 additions & 2 deletions src/pages/Chat/components/ChatMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
} from '@radix-ui/react-collapsible';
import { memo, useMemo, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { Button, Icon, Label, Textarea } from '../../../components';
import { AutoSizingTextArea, Button, Icon, Label } from '../../../components';
import IndexedDB from '../../../database/indexedDB';
import { useFileUpload } from '../../../hooks/useFileUpload';
import TextToSpeech, {
Expand Down Expand Up @@ -415,7 +415,7 @@ function EditMessage({
extraContext={extraContext}
disabled={msg.role !== 'user'}
>
<Textarea
<AutoSizingTextArea
className="max-w-2xl w-[calc(90vw-8em)]"
size="full"
value={editingContent}
Expand Down
4 changes: 2 additions & 2 deletions src/pages/Settings/components/common.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Dropdown, Label, Textarea } from '../../../components';
import { Dropdown, Label, TextArea } from '../../../components';
import { CONFIG_DEFAULT } from '../../../config';
import { DropdownOption, SettingFieldInput } from '../../../types/settings';
import { normalizeUrl } from '../../../utils';
Expand Down Expand Up @@ -48,7 +48,7 @@ export function SettingsModalLongInput({
{({ label, note }) => (
<Label variant="form-control" className="max-w-80">
<div className="text-sm opacity-60 mb-1">{label}</div>
<Textarea
<TextArea
size="default"
placeholder={`Default: ${CONFIG_DEFAULT[field.key] || 'none'}`}
value={value}
Expand Down