feat: implement setting modal

This commit is contained in:
steven
2023-03-24 15:58:08 +08:00
parent f2c4e33be4
commit 0218a9c065
8 changed files with 164 additions and 22 deletions

View File

@ -1,3 +1,4 @@
import { head } from "lodash-es";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { toast } from "react-hot-toast"; import { toast } from "react-hot-toast";
import { getAssistantById, getPromptGeneratorOfAssistant, useChatStore, useMessageStore, useConnectionStore } from "@/store"; import { getAssistantById, getPromptGeneratorOfAssistant, useChatStore, useMessageStore, useConnectionStore } from "@/store";
@ -27,6 +28,17 @@ const ChatView = () => {
}); });
}, [currentChat, isRequesting]); }, [currentChat, isRequesting]);
useEffect(() => {
if (!connectionStore.currentConnectionCtx) {
return;
}
if (currentChat?.connectionId === connectionStore.currentConnectionCtx.connection.id) {
return;
}
const chatList = chatStore.chatList.filter((chat) => chat.connectionId === connectionStore.currentConnectionCtx?.connection.id);
chatStore.setCurrentChat(head(chatList));
}, [connectionStore.currentConnectionCtx]);
const sendMessageToCurrentChat = async () => { const sendMessageToCurrentChat = async () => {
if (!currentChat || !chatViewRef.current) { if (!currentChat || !chatViewRef.current) {
return; return;
@ -101,7 +113,11 @@ const ChatView = () => {
<main ref={chatViewRef} className="relative w-full h-full max-h-full flex flex-col justify-start items-start overflow-y-auto bg-white"> <main ref={chatViewRef} className="relative w-full h-full max-h-full flex flex-col justify-start items-start overflow-y-auto bg-white">
<Header /> <Header />
<div className="p-2 w-full h-auto grow max-w-3xl py-1 px-4 sm:px-8 mx-auto"> <div className="p-2 w-full h-auto grow max-w-3xl py-1 px-4 sm:px-8 mx-auto">
{messageList.length === 0 ? <EmptyView /> : messageList.map((message) => <MessageView key={message.id} message={message} />)} {messageList.length === 0 ? (
<EmptyView className="-mt-12" />
) : (
messageList.map((message) => <MessageView key={message.id} message={message} />)
)}
{isRequesting && ( {isRequesting && (
<div className="w-full pt-4 pb-8 flex justify-center items-center text-gray-600"> <div className="w-full pt-4 pb-8 flex justify-center items-center text-gray-600">
<Icon.Bi.BiLoader className="w-5 h-auto mr-2 animate-spin" /> Requesting... <Icon.Bi.BiLoader className="w-5 h-auto mr-2 animate-spin" /> Requesting...

View File

@ -0,0 +1,42 @@
import { toast } from "react-hot-toast";
import Icon from "./Icon";
interface Props {
close: () => void;
}
const ClearDataConfirmModal = (props: Props) => {
const { close } = props;
const handleClearData = () => {
window.localStorage.clear();
toast.success("Message cleared. The page will be reloaded.");
setTimeout(() => {
window.location.reload();
}, 1500);
};
return (
<div className="modal modal-middle modal-open">
<div className="modal-box relative">
<h3 className="font-bold text-lg">Clear all data</h3>
<button className="btn btn-sm btn-circle absolute right-4 top-4" onClick={close}>
<Icon.Io.IoMdClose className="w-5 h-auto" />
</button>
<div className="w-full flex flex-col justify-start items-start space-y-3 pt-4">
<p className="text-gray-500">SQLChat saves all of your data in localstorage. Please be sure to clear data.</p>
</div>
<div className="modal-action">
<button className="btn btn-outline" onClick={close}>
Close
</button>
<button className="btn btn-error" onClick={handleClearData}>
Clear data
</button>
</div>
</div>
</div>
);
};
export default ClearDataConfirmModal;

View File

@ -6,9 +6,11 @@ import { Connection } from "@/types";
import Icon from "./Icon"; import Icon from "./Icon";
import EngineIcon from "./EngineIcon"; import EngineIcon from "./EngineIcon";
import CreateConnectionModal from "./CreateConnectionModal"; import CreateConnectionModal from "./CreateConnectionModal";
import SettingModal from "./SettingModal";
interface State { interface State {
showCreateConnectionModal: boolean; showCreateConnectionModal: boolean;
showSettingModal: boolean;
} }
const ConnectionSidebar = () => { const ConnectionSidebar = () => {
@ -16,6 +18,7 @@ const ConnectionSidebar = () => {
const chatStore = useChatStore(); const chatStore = useChatStore();
const [state, setState] = useState<State>({ const [state, setState] = useState<State>({
showCreateConnectionModal: false, showCreateConnectionModal: false,
showSettingModal: false,
}); });
const connectionList = connectionStore.connectionList; const connectionList = connectionStore.connectionList;
const currentConnectionCtx = connectionStore.currentConnectionCtx; const currentConnectionCtx = connectionStore.currentConnectionCtx;
@ -24,12 +27,6 @@ const ConnectionSidebar = () => {
(chat) => chat.connectionId === currentConnectionCtx?.connection.id && chat.databaseName === currentConnectionCtx?.database?.name (chat) => chat.connectionId === currentConnectionCtx?.connection.id && chat.databaseName === currentConnectionCtx?.database?.name
); );
useEffect(() => {
if (connectionList.length > 0) {
handleConnectionSelect(connectionList[0]);
}
}, []);
const toggleCreateConnectionModal = (show = true) => { const toggleCreateConnectionModal = (show = true) => {
setState({ setState({
...state, ...state,
@ -37,6 +34,13 @@ const ConnectionSidebar = () => {
}); });
}; };
const toggleSettingModal = (show = true) => {
setState({
...state,
showSettingModal: show,
});
};
const handleConnectionSelect = async (connection: Connection) => { const handleConnectionSelect = async (connection: Connection) => {
const databaseList = await connectionStore.getOrFetchDatabaseList(connection); const databaseList = await connectionStore.getOrFetchDatabaseList(connection);
connectionStore.setCurrentConnectionCtx({ connectionStore.setCurrentConnectionCtx({
@ -86,6 +90,13 @@ const ConnectionSidebar = () => {
</button> </button>
</div> </div>
<div className="w-full flex flex-col justify-end items-center"> <div className="w-full flex flex-col justify-end items-center">
<button
className="tooltip tooltip-right w-10 h-10 p-1 rounded-full flex flex-row justify-center items-center hover:bg-gray-100"
data-tip="Setting"
onClick={() => toggleSettingModal(true)}
>
<Icon.Io.IoMdSettings className="text-gray-600 w-6 h-auto" />
</button>
<a <a
className="tooltip tooltip-right w-10 h-10 p-1 rounded-full flex flex-row justify-center items-center hover:bg-gray-100" className="tooltip tooltip-right w-10 h-10 p-1 rounded-full flex flex-row justify-center items-center hover:bg-gray-100"
href="https://github.com/bytebase/sqlchat" href="https://github.com/bytebase/sqlchat"
@ -98,7 +109,7 @@ const ConnectionSidebar = () => {
</div> </div>
<div className={`w-64 h-full overflow-y-auto bg-gray-100 px-4 pt-2 ${databaseList.length === 0 && "!pt-4"}`}> <div className={`w-64 h-full overflow-y-auto bg-gray-100 px-4 pt-2 ${databaseList.length === 0 && "!pt-4"}`}>
{databaseList.length > 0 && ( {databaseList.length > 0 && (
<div className="w-full sticky top-0 bg-gray-100 z-1"> <div className="w-full sticky top-0 bg-gray-100 z-1 mb-4">
<p className="text-sm leading-6 mb-1 text-gray-500">Select your database:</p> <p className="text-sm leading-6 mb-1 text-gray-500">Select your database:</p>
<select <select
className="w-full select select-bordered" className="w-full select select-bordered"
@ -143,6 +154,8 @@ const ConnectionSidebar = () => {
<CreateConnectionModal show={state.showCreateConnectionModal} close={() => toggleCreateConnectionModal(false)} />, <CreateConnectionModal show={state.showCreateConnectionModal} close={() => toggleCreateConnectionModal(false)} />,
document.body document.body
)} )}
{createPortal(<SettingModal show={state.showSettingModal} close={() => toggleSettingModal(false)} />, document.body)}
</> </>
); );
}; };

View File

@ -1,4 +1,4 @@
import { cloneDeep } from "lodash-es"; import { cloneDeep, head } from "lodash-es";
import { useState } from "react"; import { useState } from "react";
import { toast } from "react-hot-toast"; import { toast } from "react-hot-toast";
import { testConnection, useConnectionStore } from "@/store"; import { testConnection, useConnectionStore } from "@/store";
@ -41,7 +41,14 @@ const CreateConnectionModal = (props: Props) => {
toast.error("Failed to connect"); toast.error("Failed to connect");
return; return;
} }
connectionStore.createConnection(connectionCreate); const createdConnection = connectionStore.createConnection(connectionCreate);
// Set the created connection as the current connection.
const databaseList = await connectionStore.getOrFetchDatabaseList(createdConnection);
connectionStore.setCurrentConnectionCtx({
connection: createdConnection,
database: head(databaseList),
});
close();
}; };
return ( return (

View File

@ -1,8 +1,14 @@
import Icon from "./Icon"; import Icon from "./Icon";
const EmptyView = () => { interface Props {
className?: string;
}
const EmptyView = (props: Props) => {
const { className } = props;
return ( return (
<div className="w-full h-full flex flex-col justify-center items-center"> <div className={`${className || ""} w-full h-full flex flex-col justify-center items-center`}>
<p className=" text-5xl font-medium leading-loose mb-8">SQLChat</p> <p className=" text-5xl font-medium leading-loose mb-8">SQLChat</p>
<div className="w-full grid grid-cols-3 gap-4"> <div className="w-full grid grid-cols-3 gap-4">
<div className="w-full flex flex-col justify-start items-center"> <div className="w-full flex flex-col justify-start items-center">

View File

@ -0,0 +1,59 @@
import { useState } from "react";
import { createPortal } from "react-dom";
import Icon from "./Icon";
import ClearDataConfirmModal from "./ClearDataConfirmModal";
interface Props {
show: boolean;
close: () => void;
}
interface State {
showClearDataConfirmModal: boolean;
}
const SettingModal = (props: Props) => {
const { show, close } = props;
const [state, setState] = useState<State>({
showClearDataConfirmModal: false,
});
const toggleClearDataConfirmModal = (show = true) => {
setState({
...state,
showClearDataConfirmModal: show,
});
};
return (
<>
<div className={`modal modal-middle ${show && "modal-open"}`}>
<div className="modal-box relative">
<h3 className="font-bold text-lg">Setting</h3>
<button className="btn btn-sm btn-circle absolute right-4 top-4" onClick={close}>
<Icon.Io.IoMdClose className="w-5 h-auto" />
</button>
<div className="w-full flex flex-col justify-start items-start space-y-3 pt-4">
<h3>Danger Zone</h3>
<div className="w-full border border-red-200 p-4 rounded-lg">
<div className="w-full flex flex-row justify-between items-center gap-2">
<div>
<h4 className="leading-8">Clear all data</h4>
<p className="text-gray-500 text-sm">SQLChat saves all of your data in localstorage. Please be sure to clear data.</p>
</div>
<button className="btn btn-error btn-sm" onClick={() => toggleClearDataConfirmModal(true)}>
Clear data
</button>
</div>
</div>
</div>
</div>
</div>
{state.showClearDataConfirmModal &&
createPortal(<ClearDataConfirmModal close={() => toggleClearDataConfirmModal(false)} />, document.body)}
</>
);
};
export default SettingModal;

View File

@ -17,7 +17,7 @@ interface ChatState {
chatList: Chat[]; chatList: Chat[];
currentChat?: Chat; currentChat?: Chat;
createChat: (connectionId?: Id, databaseName?: string) => void; createChat: (connectionId?: Id, databaseName?: string) => void;
setCurrentChat: (chat: Chat) => void; setCurrentChat: (chat: Chat | undefined) => void;
} }
export const useChatStore = create<ChatState>()( export const useChatStore = create<ChatState>()(
@ -35,7 +35,7 @@ export const useChatStore = create<ChatState>()(
currentChat: chat, currentChat: chat,
})); }));
}, },
setCurrentChat: (chat: Chat) => set(() => ({ currentChat: chat })), setCurrentChat: (chat: Chat | undefined) => set(() => ({ currentChat: chat })),
}), }),
{ {
name: "chat-storage", name: "chat-storage",

View File

@ -35,7 +35,7 @@ interface ConnectionState {
connectionList: Connection[]; connectionList: Connection[];
databaseList: Database[]; databaseList: Database[];
currentConnectionCtx?: ConnectionContext; currentConnectionCtx?: ConnectionContext;
createConnection: (connection: Connection) => void; createConnection: (connection: Connection) => Connection;
setCurrentConnectionCtx: (connectionCtx: ConnectionContext) => void; setCurrentConnectionCtx: (connectionCtx: ConnectionContext) => void;
getOrFetchDatabaseList: (connection: Connection) => Promise<Database[]>; getOrFetchDatabaseList: (connection: Connection) => Promise<Database[]>;
getOrFetchDatabaseSchema: (database: Database) => Promise<Table[]>; getOrFetchDatabaseSchema: (database: Database) => Promise<Table[]>;
@ -47,16 +47,15 @@ export const useConnectionStore = create<ConnectionState>()(
connectionList: [], connectionList: [],
databaseList: [], databaseList: [],
createConnection: (connection: Connection) => { createConnection: (connection: Connection) => {
set((state) => ({ const createdConnection = {
...state,
connectionList: [
...state.connectionList,
{
...connection, ...connection,
id: generateUUID(), id: generateUUID(),
}, };
], set((state) => ({
...state,
connectionList: [...state.connectionList, createdConnection],
})); }));
return createdConnection;
}, },
setCurrentConnectionCtx: (connectionCtx: ConnectionContext) => setCurrentConnectionCtx: (connectionCtx: ConnectionContext) =>
set((state) => ({ set((state) => ({