feat: update chat view layout

This commit is contained in:
Steven
2023-03-19 00:42:35 +08:00
parent 19c3905e9e
commit 208c894db8
15 changed files with 210 additions and 117 deletions

View File

@ -0,0 +1,68 @@
import { Menu } from "@headlessui/react";
import Link from "next/link";
import { toast } from "react-hot-toast";
import { useChatStore, useMessageStore, useUserStore } from "../../store";
import Icon from "../Icon";
const Header = () => {
const userStore = useUserStore();
const chatStore = useChatStore();
const messageStore = useMessageStore();
const currentChat = chatStore.currentChat;
const chatTitle = currentChat ? userStore.getAssistantById(currentChat.assistantId)?.name : "No chat";
const handleClearMessage = () => {
messageStore.clearMessage((message) => message.chatId !== currentChat?.id);
toast.success("Message cleared");
};
return (
<div className="sticky top-0 w-full text-center py-4 border-b bg-gray-100 bg-opacity-80 backdrop-blur">
<span className="absolute left-2 top-3">
<Menu>
<Menu.Button>
<Icon.Io.IoIosMenu className="text-gray-600 w-8 h-auto p-1 rounded-md cursor-pointer hover:shadow hover:bg-white" />
</Menu.Button>
<Menu.Items className="absolute left-0 -mt-1 w-32 origin-top-right rounded-lg bg-white shadow-lg ring-1 ring-black ring-opacity-5 p-1 space-y-1">
<Menu.Item>
<Link className="w-full p-2 rounded-lg flex flex-row justify-start items-center hover:bg-gray-100" href="/">
<Icon.Io.IoMdHome className="text-gray-600 w-5 h-auto mr-1" />
Home
</Link>
</Menu.Item>
<Menu.Item>
<a
href="https://github.com/bytebase/chatdba"
target="_blank"
className="w-full p-2 rounded-lg flex flex-row justify-start items-center hover:bg-gray-100"
>
<Icon.Io.IoLogoGithub className="text-gray-600 w-5 h-auto mr-1" /> GitHub
</a>
</Menu.Item>
</Menu.Items>
</Menu>
</span>
<span>{chatTitle}</span>
<span className="absolute right-2 top-3">
<Menu>
<Menu.Button>
<Icon.Io.IoIosMore className="text-gray-600 w-8 h-auto p-1 rounded-md cursor-pointer hover:shadow hover:bg-white" />
</Menu.Button>
<Menu.Items className="absolute right-0 -mt-1 w-32 origin-top-right rounded-lg bg-white shadow-lg ring-1 ring-black ring-opacity-5 p-1 space-y-1">
<Menu.Item>
<div
className="w-full p-2 rounded-lg flex flex-row justify-start items-center cursor-pointer hover:bg-gray-100"
onClick={handleClearMessage}
>
<Icon.Io.IoMdTrash className="text-gray-600 w-5 h-auto mr-1" />
Clear
</div>
</Menu.Item>
</Menu.Items>
</Menu>
</span>
</div>
);
};
export default Header;

View File

@ -1,16 +1,21 @@
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { toast } from "react-hot-toast";
import TextareaAutosize from "react-textarea-autosize";
import { useChatStore, useMessageStore, useUserStore } from "../../store";
import { UserRole } from "../../types";
import { generateUUID } from "../../utils";
import Icon from "../Icon";
const MessageTextarea = () => {
interface Props {
sendMessage: () => Promise<void>;
}
const MessageTextarea = (props: Props) => {
const { sendMessage } = props;
const userStore = useUserStore();
const chatStore = useChatStore();
const messageStore = useMessageStore();
const [value, setValue] = useState<string>("");
const [isInIME, setIsInIME] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
@ -25,10 +30,20 @@ const MessageTextarea = () => {
const handleSend = async () => {
if (!chatStore.currentChat) {
toast.error("Please select a chat first.");
return;
}
if (!value) {
toast.error("Please enter a message.");
return;
}
const currentChat = chatStore.currentChat;
if (currentChat.isRequesting) {
toast.error("Please wait for the previous message to be sent.");
return;
}
messageStore.addMessage({
id: generateUUID(),
chatId: currentChat.id,
@ -39,35 +54,32 @@ const MessageTextarea = () => {
setValue("");
textareaRef.current!.value = "";
const messageList = messageStore.getState().messageList.filter((message) => message.chatId === currentChat.id);
const { data } = await axios.post<string>("/api/chat", {
messages: messageList.map((message) => ({
role: message.creatorId === userStore.currentUser.id ? UserRole.User : UserRole.Assistant,
content: message.content,
})),
});
messageStore.addMessage({
id: generateUUID(),
chatId: currentChat.id,
creatorId: currentChat.userId,
createdAt: Date.now(),
content: data,
});
await sendMessage();
};
const handleKeyDown = (event: React.KeyboardEvent) => {
if (event.key === "Enter" && !event.shiftKey && !isInIME) {
event.preventDefault();
handleSend();
}
};
return (
<div className="w-full h-auto border rounded-md mb-2 px-2 py-1 relative shadow bg-white">
<div className="w-full h-auto flex flex-row justify-between items-end border rounded-lg mb-2 px-2 py-1 relative shadow bg-white">
<TextareaAutosize
ref={textareaRef}
className="w-full h-full outline-none border-none bg-transparent pt-1 mt-1 px-2 resize-none hide-scrollbar"
className="w-full h-full outline-none border-none bg-transparent leading-6 py-1 px-2 resize-none hide-scrollbar"
placeholder="Type a message..."
rows={1}
minRows={1}
maxRows={5}
onCompositionStart={() => setIsInIME(true)}
onCompositionEnd={() => setIsInIME(false)}
onChange={handleChange}
onSubmit={handleSend}
onKeyDown={handleKeyDown}
/>
<div className="absolute bottom-2 right-2 w-8 p-1 cursor-pointer rounded-md hover:shadow hover:bg-gray-100" onClick={handleSend}>
<Icon.Io.IoMdSend className="w-full h-auto text-blue-800" />
<div className="w-8 p-1 cursor-pointer rounded-md hover:shadow hover:bg-gray-100" onClick={handleSend}>
<Icon.Io.IoMdSend className="w-full h-auto text-indigo-600" />
</div>
</div>
);

View File

@ -16,10 +16,10 @@ const MessageView = (props: Props) => {
return (
<div className={`w-full flex flex-row justify-start items-start my-4 ${isCurrentUser ? "justify-end pl-8 sm:pl-16" : "pr-8 sm:pr-16"}`}>
{isCurrentUser ? (
<div className="w-auto max-w-full bg-white px-3 py-2 rounded-lg rounded-tr-none shadow">{message.content}</div>
<div className="w-auto max-w-full bg-indigo-600 text-white px-4 py-2 rounded-lg rounded-tr-none shadow">{message.content}</div>
) : (
<div
className="w-auto max-w-full bg-white px-3 py-2 rounded-lg rounded-tl-none shadow"
className="w-auto max-w-full bg-gray-100 px-4 py-2 rounded-lg rounded-tl-none shadow"
dangerouslySetInnerHTML={{ __html: marked.parse(message.content) }}
></div>
)}

View File

@ -1,58 +0,0 @@
import Link from "next/link";
import { useEffect, useState } from "react";
import { useChatStore, useUserStore } from "../../store";
import { Chat, User } from "../../types";
import Icon from "../Icon";
const Sidebar = () => {
const userStore = useUserStore();
const chatStore = useChatStore();
const [currentChat, setCurrentChat] = useState<Chat | null>(null);
useEffect(() => {
setCurrentChat(chatStore.currentChat);
}, [chatStore.currentChat]);
const handleAssistantClick = (user: User) => {
for (const chat of chatStore.chatList) {
if (chat.userId === user.id) {
chatStore.setCurrentChat(chat);
return;
}
}
chatStore.createChat(user);
};
return (
<div className="w-52 lg:w-64 h-full transition-all shrink-0 border-r px-3 flex flex-col justify-start items-center sticky top-0 bg-white sm:rounded-l-md">
<h2 className="py-4 w-full flex flex-row justify-center items-center">
<Icon.Io.IoIosChatbubbles className="text-gray-600 mr-2 w-6 h-auto" /> Assistant list
</h2>
<div className="w-full mt-2 flex flex-col justify-start items-start">
{userStore.assistantList.map((assistant) => (
<div
className={`w-full py-2 px-3 rounded-md mb-2 cursor-pointer hover:opacity-80 hover:bg-gray-100 ${
currentChat?.userId === assistant.id && "shadow bg-gray-100 font-medium"
}`}
onClick={() => handleAssistantClick(assistant)}
key={assistant.id}
>
{assistant.name}
</div>
))}
</div>
<div className="grow w-full flex flex-col justify-end items-center pb-6">
<div className="w-full flex flex-row justify-center items-center space-x-3">
<Link href="/" className="p-1 rounded-md hover:shadow hover:bg-gray-100">
<Icon.Io.IoMdHome className="text-gray-600 w-6 h-auto" />
</Link>
<a href="https://github.com/bytebase/chatdba" target="_blank" className="p-1 rounded-md hover:shadow hover:bg-gray-100">
<Icon.Io.IoLogoGithub className="text-gray-600 w-6 h-auto" />
</a>
</div>
</div>
</div>
);
};
export default Sidebar;

View File

@ -1,8 +1,11 @@
import { useEffect, useState } from "react";
import { useChatStore, useMessageStore, useUserStore } from "../../store";
import { Chat, Message } from "../../types";
import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { defaultChat, useChatStore, useMessageStore, useUserStore } from "../../store";
import { Chat, Message, UserRole } from "../../types";
import { generateUUID } from "../../utils";
import Icon from "../Icon";
import Header from "./Header";
import MessageView from "./MessageView";
import Sidebar from "./Sidebar";
import MessageTextarea from "./MessageTextarea";
const ChatView = () => {
@ -11,29 +14,76 @@ const ChatView = () => {
const messageStore = useMessageStore();
const [messageList, setMessageList] = useState<Message[]>([]);
const [currentChat, setCurrentChat] = useState<Chat | null>(null);
const chatTitle = currentChat ? userStore.getAssistantById(currentChat.userId)?.name : "No chat";
const chatViewRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!userStore.getAssistantById(chatStore.currentChat.assistantId)) {
chatStore.setCurrentChat(defaultChat);
}
setCurrentChat(chatStore.currentChat);
}, [chatStore.currentChat]);
}, [chatStore, userStore]);
useEffect(() => {
setMessageList(messageStore.messageList.filter((message) => message.chatId === currentChat?.id));
}, [currentChat?.id, messageStore.messageList]);
useEffect(() => {
if (!currentChat || !chatViewRef.current) {
return;
}
chatViewRef.current.scrollTop = chatViewRef.current.scrollHeight;
}, [currentChat, currentChat?.isRequesting]);
const sendMessageToCurrentChat = async () => {
if (!currentChat || !chatViewRef.current) {
return;
}
if (currentChat.isRequesting) {
return;
}
chatStore.setCurrentChat({
...currentChat,
isRequesting: true,
});
const messageList = messageStore.getState().messageList.filter((message) => message.chatId === currentChat.id);
const { data } = await axios.post<string>("/api/chat", {
messages: messageList.map((message) => ({
role: message.creatorId === userStore.currentUser.id ? UserRole.User : UserRole.Assistant,
content: message.content,
})),
});
messageStore.addMessage({
id: generateUUID(),
chatId: currentChat.id,
creatorId: currentChat.assistantId,
createdAt: Date.now(),
content: data,
});
chatStore.setCurrentChat({
...currentChat,
isRequesting: false,
});
};
return (
<div className="relative w-full max-w-full h-full flex flex-row justify-start items-start">
<Sidebar />
<main className="relative grow w-auto h-full max-h-full flex flex-col justify-start items-start overflow-y-auto bg-gray-100 sm:rounded-r-md">
<div className="sticky top-0 w-full text-center py-4 border-b bg-white">{chatTitle}</div>
<div className="p-2 w-full h-auto grow max-w-3xl py-1 px-4 sm:px-8 mx-auto">
{messageList.length === 0 ? <></> : messageList.map((message) => <MessageView key={message.id} message={message} />)}
</div>
<div className="sticky bottom-0 w-full max-w-3xl py-2 px-4 sm:px-8 mx-auto backdrop-blur">
<MessageTextarea />
</div>
</main>
</div>
<main
ref={chatViewRef}
className="relative sm:border-x w-full h-full max-h-full flex flex-col justify-start items-start overflow-y-auto"
>
<Header />
<div className="p-2 w-full h-auto grow max-w-3xl py-1 px-4 sm:px-8 mx-auto">
{messageList.length === 0 ? <></> : messageList.map((message) => <MessageView key={message.id} message={message} />)}
{currentChat?.isRequesting && (
<div className="w-full pt-4 pb-12 flex justify-center items-center text-gray-600">
<Icon.Bi.BiLoader className="w-5 h-auto mr-2 animate-spin" /> Loading...
</div>
)}
</div>
<div className="sticky bottom-0 w-full max-w-3xl py-2 px-4 sm:px-8 mx-auto backdrop-blur">
<MessageTextarea sendMessage={sendMessageToCurrentChat} />
</div>
</main>
);
};

View File

@ -1,7 +1,9 @@
import * as Bi from "react-icons/bi";
import * as Hi from "react-icons/hi";
import * as Io from "react-icons/io";
const Icon = {
Bi,
Hi,
Io,
};

View File

@ -7,6 +7,7 @@
"start": "next start"
},
"dependencies": {
"@headlessui/react": "^1.7.13",
"@vercel/analytics": "^0.1.11",
"axios": "^1.3.4",
"csstype": "^3.1.1",

View File

@ -2,11 +2,13 @@ import { AppProps } from "next/app";
import React from "react";
import { Analytics } from "@vercel/analytics/react";
import "../styles/tailwind.css";
import { Toaster } from "react-hot-toast";
function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<Component {...pageProps} />
<Toaster position="top-right" />
<Analytics />
</>
);

View File

@ -12,8 +12,8 @@ const ChatPage: NextPage = () => {
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="w-full h-screen flex flex-col justify-center items-center bg-gray-200">
<div className="w-full max-w-6xl h-full sm:h-4/5 shadow">
<main className="w-full h-screen flex flex-col justify-center items-center">
<div className="w-full h-full md:w-4/5">
<ChatView />
</div>
</main>

14
pnpm-lock.yaml generated
View File

@ -1,6 +1,7 @@
lockfileVersion: 5.4
specifiers:
'@headlessui/react': ^1.7.13
'@types/marked': ^4.0.8
'@types/node': ^18.11.18
'@types/react': ^18.0.26
@ -27,6 +28,7 @@ specifiers:
zustand: ^4.3.6
dependencies:
'@headlessui/react': 1.7.13_biqbaboplfbrettd7655fr4n2y
'@vercel/analytics': 0.1.11_react@18.2.0
axios: 1.3.4
csstype: 3.1.1
@ -79,6 +81,18 @@ packages:
- supports-color
dev: true
/@headlessui/react/1.7.13_biqbaboplfbrettd7655fr4n2y:
resolution: {integrity: sha512-9n+EQKRtD9266xIHXdY5MfiXPDfYwl7zBM7KOx2Ae3Gdgxy8QML1FkCMjq6AsOf0l6N9uvI4HcFtuFlenaldKg==}
engines: {node: '>=10'}
peerDependencies:
react: ^16 || ^17 || ^18
react-dom: ^16 || ^17 || ^18
dependencies:
client-only: 0.0.1
react: 18.2.0
react-dom: 18.2.0_react@18.2.0
dev: false
/@humanwhocodes/config-array/0.9.5:
resolution: {integrity: sha512-ObyMyWxZiCu/yTisA7uzx81s40xR2fD5Cg/2Kq7G02ajkNubJf6BopgDTmDyc3U7sXpNKM8cYOw7s7Tyr+DnCw==}
engines: {node: '>=10.10.0'}

View File

@ -3,9 +3,10 @@ import { persist } from "zustand/middleware";
import { Chat, User } from "../types";
import { generateUUID } from "../utils";
const defaultChat: Chat = {
export const defaultChat: Chat = {
id: generateUUID(),
userId: "assistant-chatgpt",
assistantId: "assistant-dba",
isRequesting: false,
};
interface ChatState {
@ -21,9 +22,10 @@ export const useChatStore = create<ChatState>()(
chatList: [defaultChat],
currentChat: defaultChat,
createChat: (user: User) => {
const chat = {
const chat: Chat = {
id: generateUUID(),
userId: user.id,
assistantId: user.id,
isRequesting: false,
};
set((state) => ({
chatList: [...state.chatList, chat],

View File

@ -6,6 +6,7 @@ interface MessageState {
messageList: Message[];
getState: () => MessageState;
addMessage: (message: Message) => void;
clearMessage: (filter: (message: Message) => boolean) => void;
}
export const useMessageStore = create<MessageState>()(
@ -14,6 +15,7 @@ export const useMessageStore = create<MessageState>()(
messageList: [],
getState: () => get(),
addMessage: (message: Message) => set((state) => ({ messageList: [...state.messageList, message] })),
clearMessage: (filter: (message: Message) => boolean) => set((state) => ({ messageList: state.messageList.filter(filter) })),
}),
{
name: "message-storage",

View File

@ -1,17 +1,10 @@
import { create } from "zustand";
import { Id, User, UserRole } from "../types";
const assistantList: User[] = [
{
id: "assistant-chatgpt",
name: "Origin ChatGPT",
description: "",
avatar: "",
role: UserRole.Assistant,
},
export const assistantList: User[] = [
{
id: "assistant-dba",
name: "Great DBA Bot",
name: "Chat DBA",
description: "",
avatar: "",
role: UserRole.Assistant,

View File

@ -2,7 +2,11 @@
module.exports = {
content: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {},
extend: {
zIndex: {
1: "1",
},
},
},
plugins: [],
};

View File

@ -2,5 +2,6 @@ import { Id } from "./common";
export interface Chat {
id: string;
userId: Id;
assistantId: Id;
isRequesting: boolean;
}