An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Add user message editing functionality
Yoshiki Miura2e577d0fe2f6
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsxindex 8178b305..18cc07f7 100644--- a/components/chat-messages.tsx+++ b/components/chat-messages.tsx@@ -13,6 +13,7 @@ interface ChatMessagesProps {addToolResult?: (params: { toolCallId: string; result: any }) => void/** Ref for anchoring auto-scroll position */anchorRef: React.RefObject<HTMLDivElement>+ onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>}export function ChatMessages({@@ -22,7 +23,8 @@ export function ChatMessages({isLoading,chatId,addToolResult,- anchorRef+ anchorRef,+ onUpdateMessage}: ChatMessagesProps) {const [openStates, setOpenStates] = useState<Record<string, boolean>>({})const manualToolCallId = 'manual-tool-call'@@ -96,6 +98,7 @@ export function ChatMessages({onQuerySelect={onQuerySelect}chatId={chatId}addToolResult={addToolResult}+ onUpdateMessage={onUpdateMessage}/></div>))}diff --git a/components/chat.tsx b/components/chat.tsxindex 50884e00..4bc4fe31 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -32,7 +32,8 @@ export function Chat({append,data,setData,- addToolResult+ addToolResult,+ reload} = useChat({initialMessages: savedMessages,id: CHAT_ID,@@ -69,6 +70,45 @@ export function Chat({})}+ // Function to update message content and reload the conversation+ const handleUpdateAndReloadMessage = async (+ messageId: string,+ newContent: string+ ) => {+ // Update the message with new content+ setMessages(currentMessages =>+ currentMessages.map(msg =>+ msg.id === messageId ? { ...msg, content: newContent } : msg+ )+ )++ try {+ // Find the updated message's index+ const messageIndex = messages.findIndex(msg => msg.id === messageId)+ if (messageIndex === -1) return++ // Keep only messages up to that point+ const messagesUpToEdited = messages.slice(0, messageIndex + 1)++ // Update messages to include only up to the edited message+ setMessages(messagesUpToEdited)++ // Reset data to clear any tool calls+ setData(undefined)++ // Regenerate the conversation using reload+ await reload({+ body: {+ chatId: id,+ regenerate: true+ }+ })+ } catch (error) {+ console.error('Failed to reload after message update:', error)+ toast.error(`Failed to reload conversation: ${(error as Error).message}`)+ }+ }+const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {e.preventDefault()setData(undefined) // reset data to clear tool call@@ -85,6 +125,7 @@ export function Chat({chatId={id}addToolResult={addToolResult}anchorRef={anchorRef}+ onUpdateMessage={handleUpdateAndReloadMessage}/><ChatPanelinput={input}diff --git a/components/render-message.tsx b/components/render-message.tsxindex f860318b..a15103e7 100644--- a/components/render-message.tsx+++ b/components/render-message.tsx@@ -14,6 +14,7 @@ interface RenderMessageProps {onQuerySelect: (query: string) => voidchatId?: stringaddToolResult?: (params: { toolCallId: string; result: any }) => void+ onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>}export function RenderMessage({@@ -23,7 +24,8 @@ export function RenderMessage({onOpenChange,onQuerySelect,chatId,- addToolResult+ addToolResult,+ onUpdateMessage}: RenderMessageProps) {const relatedQuestions = useMemo(() =>@@ -91,7 +93,13 @@ export function RenderMessage({}, [reasoningAnnotation])if (message.role === 'user') {- return <UserMessage message={message.content} />+ return (+ <UserMessage+ message={message.content}+ messageId={messageId}+ onUpdateMessage={onUpdateMessage}+ />+ )}// New way: Use parts instead of toolInvocationsdiff --git a/components/user-message.tsx b/components/user-message.tsxindex fcf5dd2e..f6b3e2f2 100644--- a/components/user-message.tsx+++ b/components/user-message.tsx@@ -1,14 +1,97 @@-import React from 'react'+'use client'++import { cn } from '@/lib/utils'+import { Pencil } from 'lucide-react'+import React, { useState } from 'react'+import TextareaAutosize from 'react-textarea-autosize'import { CollapsibleMessage } from './collapsible-message'+import { Button } from './ui/button'type UserMessageProps = {message: string+ messageId?: string+ onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>}-export const UserMessage: React.FC<UserMessageProps> = ({ message }) => {+export const UserMessage: React.FC<UserMessageProps> = ({+ message,+ messageId,+ onUpdateMessage+}) => {+ const [isEditing, setIsEditing] = useState(false)+ const [editedContent, setEditedContent] = useState(message)++ const handleEditClick = (e: React.MouseEvent<HTMLButtonElement>) => {+ e.stopPropagation()+ setEditedContent(message)+ setIsEditing(true)+ }++ const handleCancelClick = () => {+ setIsEditing(false)+ }++ const handleSaveClick = async () => {+ if (!onUpdateMessage || !messageId) return++ setIsEditing(false)++ try {+ await onUpdateMessage(messageId, editedContent)+ } catch (error) {+ console.error('Failed to save message:', error)+ }+ }+return (<CollapsibleMessage role="user">- <div className="flex-1 break-words w-full">{message}</div>+ <div+ className="flex-1 break-words w-full group outline-none relative"+ tabIndex={0}+ >+ {isEditing ? (+ <div className="flex flex-col gap-2">+ <TextareaAutosize+ value={editedContent}+ onChange={e => setEditedContent(e.target.value)}+ autoFocus+ className="resize-none flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"+ minRows={2}+ maxRows={10}+ />+ <div className="flex justify-end gap-2">+ <Button variant="secondary" size="sm" onClick={handleCancelClick}>+ Cancel+ </Button>+ <Button size="sm" onClick={handleSaveClick}>+ Save+ </Button>+ </div>+ </div>+ ) : (+ <div className="flex justify-between items-start">+ <div className="flex-1">{message}</div>+ <div+ className={cn(+ 'absolute top-1 right-1 transition-opacity ml-2',+ 'opacity-0',+ 'group-focus-within:opacity-100',+ 'md:opacity-0',+ 'md:group-hover:opacity-100'+ )}+ >+ <Button+ variant="ghost"+ size="icon"+ className="rounded-full h-7 w-7"+ onClick={handleEditClick}+ >+ <Pencil className="size-3.5" />+ </Button>+ </div>+ </div>+ )}+ </div></CollapsibleMessage>)}