refactor message layout for improved UI consistency

This commit is contained in:
ecwu
2024-12-20 18:21:28 +08:00
parent 17a4bf6d6b
commit 368d9810c2
3 changed files with 391 additions and 356 deletions

View File

@@ -12,6 +12,15 @@ import { MessageToolCall } from "@/messageToolCall";
import { MessageToolResp } from "@/messageToolResp"; import { MessageToolResp } from "@/messageToolResp";
import { EditMessage } from "@/editMessage"; import { EditMessage } from "@/editMessage";
import logprobToColor from "@/logprob"; import logprobToColor from "@/logprob";
import {
ChatBubble,
ChatBubbleAvatar,
ChatBubbleMessage,
ChatBubbleAction,
ChatBubbleActionWrapper,
} from "@/components/ui/chat/chat-bubble";
import { useToast } from "@/hooks/use-toast";
import { ClipboardIcon, PencilIcon, TrashIcon } from "lucide-react";
export const isVailedJSON = (str: string): boolean => { export const isVailedJSON = (str: string): boolean => {
try { try {
@@ -74,10 +83,13 @@ export default function Message(props: Props) {
</div> </div>
); );
const { toast } = useToast();
const copyToClipboard = (text: string) => { const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text); navigator.clipboard.writeText(text);
setShowCopiedHint(true); // TODO: Remove show copied hint
setTimeout(() => setShowCopiedHint(false), 1000); toast({
description: Tr("Message copied to clipboard!"),
});
}; };
const CopyIcon = ({ textToCopy }: { textToCopy: string }) => { const CopyIcon = ({ textToCopy }: { textToCopy: string }) => {
@@ -108,49 +120,25 @@ export default function Message(props: Props) {
</span> </span>
</div> </div>
)} )}
<div <ChatBubble
className={`flex ${ variant={chat.role === "assistant" ? "received" : "sent"}
chat.role === "assistant" ? "justify-start" : "justify-end" className={chat.role !== "assistant" ? "flex-row-reverse" : ""}
}`}
>
<div className={`w-full`}>
<div
className={`chat min-w-16 p-2 my-2 ${
chat.role === "assistant" ? "chat-start" : "chat-end"
} ${chat.hide ? "opacity-50" : ""}`}
>
<div
className={`chat-bubble max-w-full ${
chat.role === "assistant"
? renderColor
? "chat-bubble-neutral"
: "chat-bubble-secondary"
: "chat-bubble-primary"
}`}
> >
<ChatBubbleAvatar fallback={chat.role === "assistant" ? "AI" : "US"} />
<ChatBubbleMessage isLoading={false}>
{chat.hide ? ( {chat.hide ? (
<MessageHide chat={chat} /> <MessageHide chat={chat} />
) : typeof chat.content !== "string" ? ( ) : typeof chat.content !== "string" ? (
<MessageDetail chat={chat} renderMarkdown={renderMarkdown} /> <MessageDetail chat={chat} renderMarkdown={renderMarkdown} />
) : chat.tool_calls ? ( ) : chat.tool_calls ? (
<MessageToolCall <MessageToolCall chat={chat} copyToClipboard={copyToClipboard} />
chat={chat}
copyToClipboard={copyToClipboard}
/>
) : chat.role === "tool" ? ( ) : chat.role === "tool" ? (
<MessageToolResp <MessageToolResp chat={chat} copyToClipboard={copyToClipboard} />
chat={chat}
copyToClipboard={copyToClipboard}
/>
) : renderMarkdown ? ( ) : renderMarkdown ? (
// @ts-ignore
<Markdown markdown={getMessageText(chat)} /> <Markdown markdown={getMessageText(chat)} />
) : ( ) : (
<div className="message-content"> <div className="message-content">
{ {chat.content &&
// only show when content is string or list of message
// this check is used to avoid rendering tool call
chat.content &&
(chat.logprobs && renderColor (chat.logprobs && renderColor
? chat.logprobs.content ? chat.logprobs.content
.filter((c) => c.token) .filter((c) => c.token)
@@ -164,15 +152,34 @@ export default function Message(props: Props) {
{c.token} {c.token}
</div> </div>
)) ))
: getMessageText(chat)) : getMessageText(chat))}
}
</div> </div>
)} )}
</div> </ChatBubbleMessage>
<div className="chat-footer opacity-50 flex gap-x-2"> <ChatBubbleActionWrapper>
<DeleteIcon /> <ChatBubbleAction
<button onClick={() => setShowEdit(true)}>Edit</button> icon={<TrashIcon className="size-4" />}
<CopyIcon textToCopy={getMessageText(chat)} /> onClick={() => {
chatStore.history[messageIndex].hide =
!chatStore.history[messageIndex].hide;
chatStore.totalTokens = 0;
for (const i of chatStore.history
.filter(({ hide }) => !hide)
.slice(chatStore.postBeginIndex)
.map(({ token }) => token)) {
chatStore.totalTokens += i;
}
setChatStore({ ...chatStore });
}}
/>
<ChatBubbleAction
icon={<PencilIcon className="size-4" />}
onClick={() => setShowEdit(true)}
/>
<ChatBubbleAction
icon={<ClipboardIcon className="size-4" />}
onClick={() => copyToClipboard(getMessageText(chat))}
/>
{chatStore.tts_api && chatStore.tts_key && ( {chatStore.tts_api && chatStore.tts_key && (
<TTSButton <TTSButton
chatStore={chatStore} chatStore={chatStore}
@@ -181,14 +188,8 @@ export default function Message(props: Props) {
/> />
)} )}
<TTSPlay chat={chat} /> <TTSPlay chat={chat} />
{chat.response_model_name && ( </ChatBubbleActionWrapper>
<> </ChatBubble>
<span className="opacity-50">{chat.response_model_name}</span>
<hr />
</>
)}
</div>
</div>
{showEdit && ( {showEdit && (
<EditMessage <EditMessage
setShowEdit={setShowEdit} setShowEdit={setShowEdit}
@@ -200,27 +201,26 @@ export default function Message(props: Props) {
{showCopiedHint && <CopiedHint />} {showCopiedHint && <CopiedHint />}
{chatStore.develop_mode && ( {chatStore.develop_mode && (
<div <div
className={`gap-1 chat-end flex ${ className={`flex flex-wrap items-center gap-2 mt-2 ${
chat.role === "assistant" ? "justify-start" : "justify-end" chat.role !== "assistant" ? "justify-end" : ""
}`} }`}
> >
<span className="">token</span> <div className="flex items-center gap-2">
<span className="text-sm">token</span>
<input <input
type="number"
value={chat.token} value={chat.token}
className="input input-bordered input-xs w-16" className="h-8 w-16 rounded-md border border-input bg-background px-2 text-sm"
onChange={(event: any) => { readOnly
chat.token = parseInt(event.target.value);
setChatStore({ ...chatStore });
}}
/> />
<button <button
className="inline-flex items-center justify-center rounded-md h-8 w-8 hover:bg-accent hover:text-accent-foreground"
onClick={() => { onClick={() => {
chatStore.history.splice(messageIndex, 1); chatStore.history.splice(messageIndex, 1);
chatStore.postBeginIndex = Math.max( chatStore.postBeginIndex = Math.max(
chatStore.postBeginIndex - 1, chatStore.postBeginIndex - 1,
0 0
); );
//chatStore.totalTokens =
chatStore.totalTokens = 0; chatStore.totalTokens = 0;
for (const i of chatStore.history for (const i of chatStore.history
.filter(({ hide }) => !hide) .filter(({ hide }) => !hide)
@@ -231,31 +231,43 @@ export default function Message(props: Props) {
setChatStore({ ...chatStore }); setChatStore({ ...chatStore });
}} }}
> >
<XMarkIcon className="w-4 h-4" /> <XMarkIcon className="h-4 w-4" />
</button> </button>
<span </div>
onClick={(event: any) => { <div className="flex items-center gap-4">
<label className="flex items-center gap-2">
<input
type="checkbox"
className="h-4 w-4 rounded border-primary"
checked={chat.example}
onChange={() => {
chat.example = !chat.example; chat.example = !chat.example;
setChatStore({ ...chatStore }); setChatStore({ ...chatStore });
}} }}
> />
<label className="">{Tr("example")}</label> <span className="text-sm font-medium">{Tr("example")}</span>
<input type="checkbox" checked={chat.example} /> </label>
</span> <label className="flex items-center gap-2">
<span <input
onClick={(event: any) => setRenderWorkdown(!renderMarkdown)} type="checkbox"
> className="h-4 w-4 rounded border-primary"
<label className="">{Tr("render")}</label> checked={renderMarkdown}
<input type="checkbox" checked={renderMarkdown} /> onChange={() => setRenderWorkdown(!renderMarkdown)}
</span> />
<span onClick={(event: any) => setRenderColor(!renderColor)}> <span className="text-sm font-medium">{Tr("render")}</span>
<label className="">{Tr("color")}</label> </label>
<input type="checkbox" checked={renderColor} /> <label className="flex items-center gap-2">
</span> <input
type="checkbox"
className="h-4 w-4 rounded border-primary"
checked={renderColor}
onChange={() => setRenderColor(!renderColor)}
/>
<span className="text-sm font-medium">{Tr("color")}</span>
</label>
</div>
</div> </div>
)} )}
</div>
</div>
</> </>
); );
} }

View File

@@ -68,6 +68,7 @@ import {
ScissorsIcon, ScissorsIcon,
WholeWordIcon, WholeWordIcon,
EllipsisIcon, EllipsisIcon,
CogIcon,
} from "lucide-react"; } from "lucide-react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@@ -307,10 +308,12 @@ export function App() {
<SidebarRail /> <SidebarRail />
</Sidebar> </Sidebar>
<SidebarInset> <SidebarInset>
<header className="flex h-16 shrink-0 items-center gap-2 border-b"> <header className="flex sticky top-0 bg-background h-16 shrink-0 items-center gap-2 border-b z-50">
<div className="flex items-center gap-2 px-3"> <div className="flex items-center gap-2 px-3">
<SidebarTrigger /> <SidebarTrigger />
<Separator orientation="vertical" className="mr-2 h-4" /> <Separator orientation="vertical" className="mr-2 h-4" />
<div className="flex justify-between items-center gap-2">
<div>
<div className="dropdown lg:hidden flex items-center gap-2"> <div className="dropdown lg:hidden flex items-center gap-2">
<h1 className="text-lg font-bold">{chatStore.model}</h1>{" "} <h1 className="text-lg font-bold">{chatStore.model}</h1>{" "}
<Badge variant="outline"> <Badge variant="outline">
@@ -344,8 +347,8 @@ export function App() {
</MenubarTrigger> </MenubarTrigger>
<MenubarContent> <MenubarContent>
<MenubarItem> <MenubarItem>
{models[chatStore.model]?.price?.prompt * 1000 * 1000}$ / {models[chatStore.model]?.price?.prompt * 1000 * 1000}
1M input tokens $ / 1M input tokens
</MenubarItem> </MenubarItem>
</MenubarContent> </MenubarContent>
</MenubarMenu> </MenubarMenu>
@@ -393,6 +396,9 @@ export function App() {
</Menubar> </Menubar>
</div> </div>
</div> </div>
<CogIcon />
</div>
</div>
</header> </header>
<ChatBOX <ChatBOX
db={db} db={db}

View File

@@ -40,6 +40,16 @@ import VersionHint from "@/components/VersionHint";
import StatusBar from "@/components/StatusBar"; import StatusBar from "@/components/StatusBar";
import WhisperButton from "@/components/WhisperButton"; import WhisperButton from "@/components/WhisperButton";
import AddToolMsg from "./AddToolMsg"; import AddToolMsg from "./AddToolMsg";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import {
ChatBubble,
ChatBubbleAvatar,
ChatBubbleMessage,
ChatBubbleAction,
ChatBubbleActionWrapper,
} from "@/components/ui/chat/chat-bubble";
import { ChatMessageList } from "@/components/ui/chat/chat-message-list";
export default function ChatBOX(props: { export default function ChatBOX(props: {
db: Promise<IDBPDatabase<ChatStore>>; db: Promise<IDBPDatabase<ChatStore>>;
@@ -436,7 +446,7 @@ export default function ChatBOX(props: {
return ( return (
<div className="grow flex flex-col p-2 w-full"> <div className="grow flex flex-col p-2 w-full">
{showSettings && ( {true && (
<Settings <Settings
chatStore={chatStore} chatStore={chatStore}
setChatStore={setChatStore} setChatStore={setChatStore}
@@ -532,13 +542,14 @@ export default function ChatBOX(props: {
setChatStore={setChatStore} setChatStore={setChatStore}
/> />
)} )}
<ChatMessageList>
{chatStore.history.filter((msg) => !msg.example).length == 0 && ( {chatStore.history.filter((msg) => !msg.example).length == 0 && (
<div className="bg-base-200 break-all p-3 my-3 text-left"> <div className="bg-base-200 break-all p-3 my-3 text-left">
<h2> <h2>
<span>{Tr("Saved prompt templates")}</span> <span>{Tr("Saved prompt templates")}</span>
<button <Button
className="mx-2 underline cursor-pointer" variant="link"
className="mx-2"
onClick={() => { onClick={() => {
chatStore.systemMessageContent = ""; chatStore.systemMessageContent = "";
chatStore.toolsString = ""; chatStore.toolsString = "";
@@ -547,7 +558,7 @@ export default function ChatBOX(props: {
}} }}
> >
{Tr("Reset Current")} {Tr("Reset Current")}
</button> </Button>
</h2> </h2>
<div className="divider"></div> <div className="divider"></div>
<div className="flex flex-wrap"> <div className="flex flex-wrap">
@@ -600,8 +611,10 @@ export default function ChatBOX(props: {
)} )}
<p className="text-center"> <p className="text-center">
{chatStore.history.length > 0 && ( {chatStore.history.length > 0 && (
<button <Button
className="btn btn-sm btn-warning disabled:line-through disabled:btn-neutral disabled:text-white m-2 p-2" variant="secondary"
size="sm"
className="m-2"
disabled={showGenerating} disabled={showGenerating}
onClick={async () => { onClick={async () => {
const messageIndex = chatStore.history.length - 1; const messageIndex = chatStore.history.length - 1;
@@ -609,25 +622,24 @@ export default function ChatBOX(props: {
chatStore.history[messageIndex].hide = true; chatStore.history[messageIndex].hide = true;
} }
//chatStore.totalTokens =
setChatStore({ ...chatStore }); setChatStore({ ...chatStore });
await complete(); await complete();
}} }}
> >
{Tr("Re-Generate")} {Tr("Re-Generate")}
</button> </Button>
)} )}
{chatStore.develop_mode && chatStore.history.length > 0 && ( {chatStore.develop_mode && chatStore.history.length > 0 && (
<button <Button
className="btn btn-outline btn-sm btn-warning disabled:line-through disabled:bg-neural" variant="outline"
size="sm"
disabled={showGenerating} disabled={showGenerating}
onClick={async () => { onClick={async () => {
await complete(); await complete();
}} }}
> >
{Tr("Completion")} {Tr("Completion")}
</button> </Button>
)} )}
</p> </p>
<p className="p-2 my-2 text-center opacity-50 dark:text-white"> <p className="p-2 my-2 text-center opacity-50 dark:text-white">
@@ -642,18 +654,19 @@ export default function ChatBOX(props: {
<VersionHint chatStore={chatStore} /> <VersionHint chatStore={chatStore} />
{showRetry && ( {showRetry && (
<p className="text-right p-2 my-2 dark:text-white"> <p className="text-right p-2 my-2 dark:text-white">
<button <Button
className="p-1 rounded bg-rose-500" variant="destructive"
onClick={async () => { onClick={async () => {
setShowRetry(false); setShowRetry(false);
await complete(); await complete();
}} }}
> >
{Tr("Retry")} {Tr("Retry")}
</button> </Button>
</p> </p>
)} )}
<div ref={messagesEndRef}></div> <div ref={messagesEndRef}></div>
</ChatMessageList>
</div> </div>
{images.length > 0 && ( {images.length > 0 && (
<div className="flex flex-wrap"> <div className="flex flex-wrap">
@@ -683,16 +696,17 @@ export default function ChatBOX(props: {
</span> </span>
)} )}
<div className="flex justify-between my-1"> <div className="sticky top-0 z-10 bg-background flex justify-between my-1 gap-2 p-2">
<button <Button
className="btn btn-primary disabled:line-through disabled:text-white disabled:bg-neutral m-1 p-1" variant="default"
size="sm"
disabled={showGenerating || !chatStore.apiKey} disabled={showGenerating || !chatStore.apiKey}
onClick={() => { onClick={() => {
setShowAddImage(!showAddImage); setShowAddImage(!showAddImage);
}} }}
> >
Image Image
</button> </Button>
{showAddImage && ( {showAddImage && (
<AddImage <AddImage
chatStore={chatStore} chatStore={chatStore}
@@ -702,8 +716,8 @@ export default function ChatBOX(props: {
setImages={setImages} setImages={setImages}
/> />
)} )}
<textarea <Textarea
autofocus autoFocus
value={inputMsg} value={inputMsg}
ref={userInputRef} ref={userInputRef}
onChange={(event: any) => { onChange={(event: any) => {
@@ -711,7 +725,6 @@ export default function ChatBOX(props: {
autoHeight(event.target); autoHeight(event.target);
}} }}
onKeyPress={(event: any) => { onKeyPress={(event: any) => {
console.log(event);
if (event.ctrlKey && event.code === "Enter") { if (event.ctrlKey && event.code === "Enter") {
send(event.target.value, true); send(event.target.value, true);
setInputMsg(""); setInputMsg("");
@@ -722,14 +735,15 @@ export default function ChatBOX(props: {
autoHeight(event.target); autoHeight(event.target);
setInputMsg(event.target.value); setInputMsg(event.target.value);
}} }}
className="textarea textarea-bordered textarea-sm grow w-0" className="min-h-[40px] flex-grow resize-none"
placeholder="Type here..."
style={{ style={{
lineHeight: "1.39", lineHeight: "1.39",
}} }}
placeholder="Type here..." />
></textarea> <Button
<button variant="default"
className="btn btn-primary disabled:btn-neutral disabled:line-through m-1 p-1" size="sm"
disabled={showGenerating} disabled={showGenerating}
onClick={() => { onClick={() => {
send(inputMsg, true); send(inputMsg, true);
@@ -738,7 +752,7 @@ export default function ChatBOX(props: {
}} }}
> >
{Tr("Send")} {Tr("Send")}
</button> </Button>
{chatStore.whisper_api && chatStore.whisper_key && ( {chatStore.whisper_api && chatStore.whisper_key && (
<WhisperButton <WhisperButton
chatStore={chatStore} chatStore={chatStore}
@@ -747,8 +761,9 @@ export default function ChatBOX(props: {
/> />
)} )}
{chatStore.develop_mode && ( {chatStore.develop_mode && (
<button <Button
className="btn disabled:line-through disabled:btn-neutral disabled:text-white m-1 p-1" variant="outline"
size="sm"
disabled={showGenerating || !chatStore.apiKey} disabled={showGenerating || !chatStore.apiKey}
onClick={() => { onClick={() => {
chatStore.history.push({ chatStore.history.push({
@@ -768,29 +783,31 @@ export default function ChatBOX(props: {
}} }}
> >
{Tr("AI")} {Tr("AI")}
</button> </Button>
)} )}
{chatStore.develop_mode && ( {chatStore.develop_mode && (
<button <Button
className="btn disabled:line-through disabled:btn-neutral disabled:text-white m-1 p-1" variant="outline"
size="sm"
disabled={showGenerating || !chatStore.apiKey} disabled={showGenerating || !chatStore.apiKey}
onClick={() => { onClick={() => {
send(inputMsg, false); send(inputMsg, false);
}} }}
> >
{Tr("User")} {Tr("User")}
</button> </Button>
)} )}
{chatStore.develop_mode && ( {chatStore.develop_mode && (
<button <Button
className="btn disabled:line-through disabled:btn-neutral disabled:text-white m-1 p-1" variant="outline"
size="sm"
disabled={showGenerating || !chatStore.apiKey} disabled={showGenerating || !chatStore.apiKey}
onClick={() => { onClick={() => {
setShowAddToolMsg(true); setShowAddToolMsg(true);
}} }}
> >
{Tr("Tool")} {Tr("Tool")}
</button> </Button>
)} )}
{showAddToolMsg && ( {showAddToolMsg && (
<AddToolMsg <AddToolMsg