Skip to content

Build and run agents you can see, understand and trust.

refactor(webui): refactor the text input component in web ui (#2102)

Ziyang Guoaa8123ec6184
diff --git a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
index 59aa319ce..e76d87261 100644
--- a/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
+++ b/examples/web_ui/frontend/src/components/chat/ChatContent.tsx
@@ -3,11 +3,11 @@ import { ArrowDown } from 'lucide-react';
import React from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
-import { EmptyMessage } from './Empty';
import { MessageBubble } from '@/components/chat/MessageBubble';
import { TextInput } from '@/components/chat/TextInput.tsx';
import { Button } from '@/components/ui/button.tsx';
import type { ReplyPhase } from '@/hooks/useMessages';
+import { useTranslation } from '@/i18n/useI18n';
import { cn } from '@/lib/utils';
interface ChatContentProps {
@@ -57,9 +57,11 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
allowedInputTypes,
fileProcessor,
}) => {
+ const { t } = useTranslation();
const scrollAreaRef = useRef<HTMLDivElement>(null);
const prevMsgCountRef = useRef<number>(0);
const wasNearBottomRef = useRef<boolean>(true);
+ const isEmpty = msgs.length === 0;
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const updateScrollState = useCallback(() => {
@@ -107,15 +109,38 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
return () => scrollArea.removeEventListener('scroll', updateScrollState);
}, [updateScrollState]);
+ // On an empty session the prompt and the input centre together, so every box
+ // down to the message list shrinks to its content instead of filling.
return (
- <div className={cn('flex flex-col h-full w-full items-center p-2 gap-4', className)}>
- <div className="relative flex-1 min-h-0 w-full max-w-full">
+ <div
+ className={cn(
+ 'flex flex-col h-full w-full items-center p-2 gap-4',
+ isEmpty && 'justify-center',
+ className,
+ )}
+ >
+ <div
+ className={cn(
+ 'relative min-h-0 w-full max-w-full',
+ isEmpty ? 'flex-none' : 'flex-1',
+ )}
+ >
<div
ref={scrollAreaRef}
- className="size-full overflow-auto no-scrollbar overflow-x-hidden"
+ className={cn(
+ 'overflow-auto no-scrollbar overflow-x-hidden',
+ isEmpty ? 'w-full' : 'size-full',
+ )}
>
- <div className="flex flex-col gap-4 size-full max-w-full">
- {msgs.length > 0 ? (
+ <div
+ className={cn(
+ 'flex flex-col gap-4 max-w-full',
+ isEmpty ? 'w-full' : 'size-full',
+ )}
+ >
+ {isEmpty ? (
+ <p className="text-center text-lg mb-2">{t('chat.greeting')}</p>
+ ) : (
msgs.map((message) => (
<MessageBubble
key={message.id}
@@ -123,8 +148,6 @@ const ChatContentComponent: React.FC<ChatContentProps> = ({
onUserConfirm={onUserConfirm}
/>
))
- ) : (
- <EmptyMessage />
)}
</div>
</div>
diff --git a/examples/web_ui/frontend/src/components/chat/Empty.tsx b/examples/web_ui/frontend/src/components/chat/Empty.tsx
deleted file mode 100644
index 3f3b9cf87..000000000
--- a/examples/web_ui/frontend/src/components/chat/Empty.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { MessagesSquare } from 'lucide-react';
-
-import {
- Empty,
- EmptyDescription,
- EmptyHeader,
- EmptyMedia,
- EmptyTitle,
-} from '@/components/ui/empty';
-import { useTranslation } from '@/i18n/useI18n';
-
-/**
- * Empty state component shown when there are no messages.
- * @returns An empty state element with icon and description.
- */
-export function EmptyMessage() {
- const { t } = useTranslation();
-
- return (
- <Empty className="size-full">
- <EmptyHeader>
- <EmptyMedia variant="icon">
- <MessagesSquare />
- </EmptyMedia>
- <EmptyTitle>{t('chat.noMessages')}</EmptyTitle>
- <EmptyDescription>{t('chat.noMessagesDesc')}</EmptyDescription>
- </EmptyHeader>
- </Empty>
- );
-}
diff --git a/examples/web_ui/frontend/src/components/chat/TextInput.tsx b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
index eac1f77f0..fb151761b 100644
--- a/examples/web_ui/frontend/src/components/chat/TextInput.tsx
+++ b/examples/web_ui/frontend/src/components/chat/TextInput.tsx
@@ -4,6 +4,7 @@ import React, {
useState,
useRef,
useMemo,
+ useLayoutEffect,
type KeyboardEvent,
useImperativeHandle,
forwardRef,
@@ -15,7 +16,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import type { ReplyPhase } from '@/hooks/useMessages';
import { useTranslation } from '@/i18n/useI18n.ts';
import { cn } from '@/lib/utils';
-import { isMac } from '@/utils/platform';
/**
* Represents a file that has been selected and processed (or is being processed).
@@ -71,6 +71,20 @@ export interface TextInputRef {
focus: () => void;
}
+/** One line box of textarea text: ``text-sm`` (14px) at a 1.5 line-height. */
+const LINE_HEIGHT_PX = 21;
+/** Height of the input in its collapsed, single-line state. */
+const COLLAPSED_HEIGHT_PX = 52;
+/**
+ * Padding rather than height: a textarea top-aligns its text, so forcing the
+ * height would leave dead space under the caret instead of centring the line.
+ */
+const TEXTAREA_PADDING_Y_PX = (COLLAPSED_HEIGHT_PX - LINE_HEIGHT_PX) / 2;
+/** Growth stops after six lines of text; the textarea scrolls beyond that. */
+const MAX_HEIGHT_PX = LINE_HEIGHT_PX * 6 + TEXTAREA_PADDING_Y_PX * 2;
+/** Horizontal padding of the textarea, mirrored by the overlay and the ghost. */
+const TEXTAREA_PADDING_X_PX = 12;
+
/**
* A text input component with file attachment support and autocomplete functionality.
*
@@ -105,6 +119,8 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
const textareaRef = useRef<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const measureRef = useRef<HTMLSpanElement>(null);
+ /** ``true`` — textarea takes the full width, buttons drop to their own row. */
+ const [isStacked, setIsStacked] = useState(false);
// Derive the accept attribute for the hidden file input
const acceptAttr =
@@ -123,6 +139,24 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
focus: () => textareaRef.current?.focus(),
}));
+ // Grow the textarea with its content. The ``auto`` reset is what lets it
+ // shrink again — ``scrollHeight`` never reports less than the current height.
+ useLayoutEffect(() => {
+ const textarea = textareaRef.current;
+ if (!textarea) return;
+ textarea.style.height = 'auto';
+ textarea.style.height = `${textarea.scrollHeight}px`;
+ // Stacking widens the textarea, so the line count has to be redone.
+ }, [value, isStacked]);
+
+ // Measured on the ghost, not the textarea: stacking widens the textarea, so
+ // measuring it would flip-flop (wraps → stack → fits → unstack → wraps).
+ useLayoutEffect(() => {
+ const ghost = measureRef.current;
+ if (!ghost) return;
+ setIsStacked(ghost.scrollHeight > LINE_HEIGHT_PX);
+ }, [value]);
+
// Calculate autocomplete suggestion using useMemo
const suggestion = useMemo(() => {
if (autoComplete && value && isFocused) {
@@ -256,117 +290,143 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
};
return (
- <div
- id="tour-chat-input"
- className={cn(
- 'flex flex-col gap-2 rounded-2xl border bg-background p-3',
- className,
- )}
- data-tour="chat-input"
- >
- {/* File list */}
- {files.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {files.map((file, index) => (
- <div
- key={index}
- className="flex items-center gap-1 rounded bg-muted px-2 py-1 text-sm"
- >
- {file.status === 'processing' && (
- <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground" />
- )}
- <span className="max-w-[200px] truncate">{file.name}</span>
- <button
- onClick={() => setFiles(files.filter((_, i) => i !== index))}
- className="text-muted-foreground hover:text-foreground"
+ <div className={cn('flex flex-col gap-1', className)}>
+ <div
+ id="tour-chat-input"
+ className="flex w-full flex-col gap-2 rounded-[28px] border bg-background px-2"
+ data-tour="chat-input"
+ >
+ {/* File list */}
+ {files.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {files.map((file, index) => (
+ <div
+ key={index}
+ className="flex items-center gap-1 rounded bg-muted px-2 py-1 text-sm"
>
- <X className="h-3 w-3" />
- </button>
+ {file.status === 'processing' && (
+ <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground" />
+ )}
+ <span className="max-w-[200px] truncate">{file.name}</span>
+ <button
+ onClick={() =>
+ setFiles(files.filter((_, i) => i !== index))
+ }
+ className="text-muted-foreground hover:text-foreground"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* ``items-end`` in both layouts: the buttons are then already at the
+ bottom before stacking moves them there, so nothing jumps. */}
+ <div className="relative flex flex-wrap items-end justify-end">
+ {/* Ghost row, always laid out side-by-side, so the width it hands
+ the text is the narrow one whichever layout is on screen. */}
+ <div
+ aria-hidden
+ className="pointer-events-none invisible absolute inset-x-0 top-0 flex h-0 items-start overflow-hidden"
+ >
+ <div className="min-w-0 flex-1">
+ {/* Padding-x and line-height decide where text wraps, so they
+ match the textarea; padding-y is left off on purpose. */}
+ <span
+ ref={measureRef}
+ className="block text-sm"
+ style={{
+ paddingLeft: `${TEXTAREA_PADDING_X_PX}px`,
+ paddingRight: `${TEXTAREA_PADDING_X_PX}px`,
+ lineHeight: `${LINE_HEIGHT_PX}px`,
+ whiteSpace: 'pre-wrap',
+ wordWrap: 'break-word',
+ }}
+ >
+ {value}
+ </span>
</div>
- ))}
- </div>
- )}
-
- {/* Input area */}
- <div className="relative">
- <div className="relative">
- {/* Hidden measurement element */}
- <span
- ref={measureRef}
- className="invisible absolute whitespace-pre text-sm"
- style={{
- font: 'inherit',
- padding: '0.5rem 0.75rem',
- lineHeight: '1.5em',
- }}
+ {/* Stands in for the button cluster below — keep the count, the
+ gap and the ``size-9`` footprint in step with it. */}
+ <div className="flex shrink-0 gap-2">
+ <div className="size-9" />
+ <div className="size-9" />
+ </div>
+ </div>
+
+ {/* ``min-w-0`` lets the textarea shrink instead of pushing the
+ buttons out of the row once the text gets long. */}
+ <div
+ className={cn('relative min-w-0', isStacked ? 'basis-full' : 'flex-1')}
>
- {value}
- </span>
-
- <textarea
- ref={textareaRef}
- value={value}
- onChange={(e) => setValue(e.target.value)}
- onKeyDown={handleKeyDown}
- onFocus={() => setIsFocused(true)}
- onBlur={() => setIsFocused(false)}
- placeholder={defaultPlaceholder}
- disabled={disabled}
- rows={1}
- className="w-full resize-none rounded-md border-0 bg-transparent px-3 py-2 text-sm outline-none placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
- style={{
- maxHeight: 'calc(1.5em * 6)',
- lineHeight: '1.5em',
- overflowY: 'auto',
- }}
- autoFocus={true}
- />
-
- {/* Autocomplete suggestion - using absolute positioning overlay */}
- {suggestion && isFocused && (
- <div
- className="pointer-events-none absolute left-0 top-0 px-3 py-2 text-sm"
+ {/* ``block`` — inline-block would sit on the text baseline and
+ leave a descender gap that makes the wrapper taller. */}
+ <textarea
+ ref={textareaRef}
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={handleKeyDown}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ placeholder={defaultPlaceholder}
+ disabled={disabled}
+ rows={1}
+ className="block w-full resize-none rounded-md border-0 bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
style={{
- lineHeight: '1.5em',
- whiteSpace: 'pre-wrap',
- wordWrap: 'break-word',
+ minHeight: `${COLLAPSED_HEIGHT_PX}px`,
+ maxHeight: `${MAX_HEIGHT_PX}px`,
+ lineHeight: `${LINE_HEIGHT_PX}px`,
+ paddingTop: `${TEXTAREA_PADDING_Y_PX}px`,
+ paddingBottom: `${TEXTAREA_PADDING_Y_PX}px`,
+ overflowY: 'auto',
}}
- >
- {/* Invisible input text */}
- <span className="invisible">{value}</span>
- {/* Suggestion text */}
- <span className="text-muted-foreground">{suggestion}</span>
- {/* Tab hint */}
- <span className="ml-2 text-xs text-muted-foreground/60">
- <Kbd>Tab</Kbd> {t('textInput.toComplete')}
- </span>
- </div>
- )}
- </div>
+ autoFocus={true}
+ />
- {/* Button row */}
- <div className="mt-2 flex items-center justify-between">
- <div>
- <span
- className={`text-muted-foreground text-sm ${!isFocused && 'hidden'}`}
- >
- <Kbd>{isMac() ? '⇧' : 'Shift'}</Kbd> + <Kbd>Enter</Kbd>{' '}
- {t('textInput.newLine')}
- </span>
+ {/* Autocomplete overlay — its padding and line-height mirror the
+ textarea's, or the suggestion drifts off the real text. */}
+ {suggestion && isFocused && (
+ <div
+ className="pointer-events-none absolute left-0 top-0 px-3 text-sm"
+ style={{
+ lineHeight: `${LINE_HEIGHT_PX}px`,
+ paddingTop: `${TEXTAREA_PADDING_Y_PX}px`,
+ paddingBottom: `${TEXTAREA_PADDING_Y_PX}px`,
+ whiteSpace: 'pre-wrap',
+ wordWrap: 'break-word',
+ }}
+ >
+ {/* Invisible input text */}
+ <span className="invisible">{value}</span>
+ {/* Suggestion text */}
+ <span className="text-muted-foreground">{suggestion}</span>
+ {/* Tab hint */}
+ <span className="ml-2 text-xs text-muted-foreground/60">
+ <Kbd>Tab</Kbd> {t('textInput.toComplete')}
+ </span>
+ </div>
+ )}
</div>
- <div className="flex gap-2">
+
+ {/* Collapsed-height box centring the buttons, so a single line still
+ reads as centred while the row bottom-aligns them. */}
+ <div
+ className="flex shrink-0 items-center gap-2"
+ style={{ height: `${COLLAPSED_HEIGHT_PX}px` }}
+ >
{/* Attachment button */}
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
- size="icon"
+ size="icon-lg"
onClick={() => fileInputRef.current?.click()}
disabled={attachDisabled}
className="shrink-0 rounded-full"
>
- <Paperclip className="h-4 w-4" />
+ <Paperclip className="size-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
@@ -383,7 +443,7 @@ export const TextInput = forwardRef<TextInputRef, TextInputProps>(
type="button"
onClick={sendButton.onClick}
disabled={sendButton.disabled}
- size="icon"
+ size="icon-lg"
className="shrink-0 rounded-full"
>
<sendButton.icon className="h-4 w-4" />
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index 3d2914354..41ca3ce62 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -87,7 +87,6 @@
},
"textInput": {
"toComplete": "to complete",
- "newLine": "new line",
"attach": "Attach file",
"attachNotSupported": "This model does not support file attachments",
"send": "Send",
@@ -118,8 +117,7 @@
"subagentConfirmTitle": "{{name}} requests confirmation",
"newSession": "New Session",
"noSessions": "No sessions yet",
- "noMessages": "No Messages Yet",
- "noMessagesDesc": "Start your conversation by sending a message",
+ "greeting": "Where should we start?",
"agent": {
"selectPlaceholder": "Select an agent",
"emptyTitle": "No agents",
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index 431c9964d..252fa7000 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -87,7 +87,6 @@
},
"textInput": {
"toComplete": "补全",
- "newLine": "换行",
"attach": "添加附件",
"attachNotSupported": "当前模型不支持文件附件",
"send": "发送",
@@ -118,8 +117,7 @@
"subagentConfirmTitle": "{{name}} 请求确认",
"newSession": "新会话",
"noSessions": "暂无会话",
- "noMessages": "暂无消息",
- "noMessagesDesc": "发送一条消息开始新的对话",
+ "greeting": "我们从哪儿开始?",
"agent": {
"selectPlaceholder": "选择 Agent",
"emptyTitle": "暂无 Agent",