ChatGPT-Next-Web/app/components/home.tsx

655 lines
18 KiB
TypeScript
Raw Normal View History

2023-03-09 17:01:40 +00:00
"use client";
import { useState, useRef, useEffect, useLayoutEffect } from "react";
2023-03-28 17:30:11 +00:00
import { useDebouncedCallback } from "use-debounce";
2023-03-11 17:14:07 +00:00
2023-03-09 17:01:40 +00:00
import { IconButton } from "./button";
2023-03-12 19:06:21 +00:00
import styles from "./home.module.scss";
2023-03-09 17:01:40 +00:00
import SettingsIcon from "../icons/settings.svg";
import GithubIcon from "../icons/github.svg";
import ChatGptIcon from "../icons/chatgpt.svg";
import SendWhiteIcon from "../icons/send-white.svg";
import BrainIcon from "../icons/brain.svg";
import ExportIcon from "../icons/export.svg";
import BotIcon from "../icons/bot.svg";
import AddIcon from "../icons/add.svg";
2023-03-10 18:25:33 +00:00
import DeleteIcon from "../icons/delete.svg";
import LoadingIcon from "../icons/three-dots.svg";
2023-03-14 17:44:42 +00:00
import MenuIcon from "../icons/menu.svg";
import CloseIcon from "../icons/close.svg";
2023-03-15 17:24:03 +00:00
import CopyIcon from "../icons/copy.svg";
import DownloadIcon from "../icons/download.svg";
2023-03-10 18:25:33 +00:00
2023-03-19 16:09:30 +00:00
import { Message, SubmitKey, useChatStore, ChatSession } from "../store";
import { showModal, showToast } from "./ui-lib";
2023-03-21 14:56:27 +00:00
import { copyToClipboard, downloadAs, isIOS, selectOrCopy } from "../utils";
import Locale from "../locales";
2023-03-13 16:25:07 +00:00
import dynamic from "next/dynamic";
2023-03-23 16:01:00 +00:00
import { REPO_URL } from "../constant";
2023-03-26 10:59:09 +00:00
import { ControllerPool } from "../requests";
2023-03-28 17:30:11 +00:00
import { Prompt, usePromptStore } from "../store/prompt";
2023-03-21 14:56:27 +00:00
export function Loading(props: { noLogo?: boolean }) {
return (
<div className={styles["loading-content"]}>
{!props.noLogo && <BotIcon />}
<LoadingIcon />
</div>
);
}
2023-03-21 14:56:27 +00:00
const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
loading: () => <LoadingIcon />,
});
2023-03-21 14:56:27 +00:00
const Settings = dynamic(async () => (await import("./settings")).Settings, {
loading: () => <Loading noLogo />,
});
const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, {
2023-03-21 14:56:27 +00:00
loading: () => <LoadingIcon />,
});
2023-03-11 12:54:24 +00:00
2023-03-10 18:25:33 +00:00
export function Avatar(props: { role: Message["role"] }) {
2023-03-11 17:14:07 +00:00
const config = useChatStore((state) => state.config);
2023-03-10 18:25:33 +00:00
if (props.role === "assistant") {
return <BotIcon className={styles["user-avtar"]} />;
}
2023-03-11 17:14:07 +00:00
return (
<div className={styles["user-avtar"]}>
<Emoji unified={config.avatar} size={18} />
</div>
);
2023-03-10 18:25:33 +00:00
}
2023-03-09 17:01:40 +00:00
export function ChatItem(props: {
onClick?: () => void;
2023-03-10 18:25:33 +00:00
onDelete?: () => void;
2023-03-09 17:01:40 +00:00
title: string;
count: number;
time: string;
selected: boolean;
}) {
return (
<div
2023-03-21 14:56:27 +00:00
className={`${styles["chat-item"]} ${
props.selected && styles["chat-item-selected"]
}`}
2023-03-10 18:25:33 +00:00
onClick={props.onClick}
2023-03-09 17:01:40 +00:00
>
<div className={styles["chat-item-title"]}>{props.title}</div>
<div className={styles["chat-item-info"]}>
2023-03-21 14:56:27 +00:00
<div className={styles["chat-item-count"]}>
{Locale.ChatItem.ChatItemCount(props.count)}
</div>
2023-03-09 17:01:40 +00:00
<div className={styles["chat-item-date"]}>{props.time}</div>
</div>
2023-03-10 18:25:33 +00:00
<div className={styles["chat-item-delete"]} onClick={props.onDelete}>
<DeleteIcon />
</div>
2023-03-09 17:01:40 +00:00
</div>
);
}
export function ChatList() {
2023-03-10 18:25:33 +00:00
const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
(state) => [
state.sessions,
state.currentSessionIndex,
state.selectSession,
state.removeSession,
]
);
2023-03-09 17:01:40 +00:00
return (
<div className={styles["chat-list"]}>
2023-03-10 18:25:33 +00:00
{sessions.map((item, i) => (
<ChatItem
title={item.topic}
time={item.lastUpdate}
count={item.messages.length}
key={i}
selected={i === selectedIndex}
onClick={() => selectSession(i)}
onDelete={() => removeSession(i)}
/>
2023-03-09 17:01:40 +00:00
))}
</div>
);
}
2023-03-12 19:06:21 +00:00
function useSubmitHandler() {
const config = useChatStore((state) => state.config);
const submitKey = config.submitKey;
const shouldSubmit = (e: KeyboardEvent) => {
if (e.key !== "Enter") return false;
return (
(config.submitKey === SubmitKey.AltEnter && e.altKey) ||
(config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
(config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
(config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
(config.submitKey === SubmitKey.Enter &&
!e.altKey &&
!e.ctrlKey &&
2023-03-28 03:07:59 +00:00
!e.shiftKey &&
!e.metaKey)
2023-03-12 19:06:21 +00:00
);
};
return {
submitKey,
shouldSubmit,
};
}
2023-03-28 17:30:11 +00:00
export function PromptHints(props: {
prompts: Prompt[];
onPromptSelect: (prompt: Prompt) => void;
}) {
if (props.prompts.length === 0) return null;
return (
<div className={styles["prompt-hints"]}>
{props.prompts.map((prompt, i) => (
<div
className={styles["prompt-hint"]}
key={prompt.title + i.toString()}
onClick={() => props.onPromptSelect(prompt)}
>
<div className={styles["hint-title"]}>{prompt.title}</div>
<div className={styles["hint-content"]}>{prompt.content}</div>
</div>
))}
</div>
);
}
2023-03-14 17:44:42 +00:00
export function Chat(props: { showSideBar?: () => void }) {
2023-03-10 18:25:33 +00:00
type RenderMessage = Message & { preview?: boolean };
2023-03-28 17:30:11 +00:00
const chatStore = useChatStore();
2023-03-26 10:59:09 +00:00
const [session, sessionIndex] = useChatStore((state) => [
state.currentSession(),
state.currentSessionIndex,
]);
2023-03-28 17:30:11 +00:00
const inputRef = useRef<HTMLTextAreaElement>(null);
2023-03-10 18:25:33 +00:00
const [userInput, setUserInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
2023-03-12 19:06:21 +00:00
const { submitKey, shouldSubmit } = useSubmitHandler();
2023-03-10 18:25:33 +00:00
2023-03-28 17:30:11 +00:00
// prompt hints
const promptStore = usePromptStore();
const [promptHints, setPromptHints] = useState<Prompt[]>([]);
const onSearch = useDebouncedCallback(
(text: string) => {
if (chatStore.config.disablePromptHint) return;
setPromptHints(promptStore.search(text));
},
100,
{ leading: true, trailing: true }
);
const onPromptSelect = (prompt: Prompt) => {
setUserInput(prompt.content);
setPromptHints([]);
inputRef.current?.focus();
};
// only search prompts when user input is short
2023-03-28 18:19:20 +00:00
const SEARCH_TEXT_LIMIT = 30;
2023-03-28 17:30:11 +00:00
const onInput = (text: string) => {
setUserInput(text);
const n = text.trim().length;
if (n === 0 || n > SEARCH_TEXT_LIMIT) {
setPromptHints([]);
} else {
onSearch(text);
}
};
2023-03-26 10:59:09 +00:00
// submit user input
2023-03-10 18:25:33 +00:00
const onUserSubmit = () => {
if (userInput.length <= 0) return;
setIsLoading(true);
2023-03-28 17:30:11 +00:00
chatStore.onUserInput(userInput).then(() => setIsLoading(false));
2023-03-10 18:25:33 +00:00
setUserInput("");
inputRef.current?.focus();
2023-03-10 18:25:33 +00:00
};
2023-03-26 10:59:09 +00:00
// stop response
const onUserStop = (messageIndex: number) => {
console.log(ControllerPool, sessionIndex, messageIndex);
ControllerPool.stop(sessionIndex, messageIndex);
};
// check if should send message
2023-03-10 18:25:33 +00:00
const onInputKeyDown = (e: KeyboardEvent) => {
2023-03-12 19:06:21 +00:00
if (shouldSubmit(e)) {
2023-03-10 18:25:33 +00:00
onUserSubmit();
e.preventDefault();
}
};
2023-03-26 10:59:09 +00:00
const onRightClick = (e: any, message: Message) => {
// auto fill user input
if (message.role === "user") {
setUserInput(message.content);
}
// copy to clipboard
if (selectOrCopy(e.currentTarget, message.content)) {
e.preventDefault();
}
};
const onResend = (botIndex: number) => {
// find last user input message and resend
for (let i = botIndex; i >= 0; i -= 1) {
if (messages[i].role === "user") {
setIsLoading(true);
2023-03-28 17:30:11 +00:00
chatStore
.onUserInput(messages[i].content)
.then(() => setIsLoading(false));
2023-03-26 10:59:09 +00:00
return;
}
}
};
// for auto-scroll
2023-03-10 18:25:33 +00:00
const latestMessageRef = useRef<HTMLDivElement>(null);
2023-03-26 10:59:09 +00:00
// wont scroll while hovering messages
const [autoScroll, setAutoScroll] = useState(false);
2023-03-26 10:59:09 +00:00
// preview messages
2023-03-10 18:25:33 +00:00
const messages = (session.messages as RenderMessage[])
.concat(
isLoading
? [
2023-03-21 14:56:27 +00:00
{
role: "assistant",
content: "……",
date: new Date().toLocaleString(),
preview: true,
},
]
2023-03-10 18:25:33 +00:00
: []
)
.concat(
userInput.length > 0
? [
2023-03-21 14:56:27 +00:00
{
role: "user",
content: userInput,
date: new Date().toLocaleString(),
preview: true,
},
]
2023-03-10 18:25:33 +00:00
: []
);
2023-03-26 10:59:09 +00:00
// auto scroll
useLayoutEffect(() => {
setTimeout(() => {
const dom = latestMessageRef.current;
if (dom && !isIOS() && autoScroll) {
dom.scrollIntoView({
behavior: "smooth",
block: "end",
});
}
}, 500);
2023-03-10 18:25:33 +00:00
});
2023-03-09 17:01:40 +00:00
return (
2023-03-11 17:14:07 +00:00
<div className={styles.chat} key={session.id}>
<div className={styles["window-header"]}>
2023-03-21 14:56:27 +00:00
<div
className={styles["window-header-title"]}
onClick={props?.showSideBar}
>
<div className={styles["window-header-main-title"]}>
{session.topic}
</div>
2023-03-11 17:14:07 +00:00
<div className={styles["window-header-sub-title"]}>
2023-03-20 16:17:45 +00:00
{Locale.Chat.SubTitle(session.messages.length)}
2023-03-09 17:01:40 +00:00
</div>
</div>
2023-03-12 19:06:21 +00:00
<div className={styles["window-actions"]}>
2023-03-14 17:44:42 +00:00
<div className={styles["window-action-button"] + " " + styles.mobile}>
<IconButton
icon={<MenuIcon />}
bordered
2023-03-20 16:17:45 +00:00
title={Locale.Chat.Actions.ChatList}
2023-03-14 17:44:42 +00:00
onClick={props?.showSideBar}
/>
</div>
2023-03-12 19:06:21 +00:00
<div className={styles["window-action-button"]}>
<IconButton
icon={<BrainIcon />}
bordered
2023-03-20 16:17:45 +00:00
title={Locale.Chat.Actions.CompressedHistory}
2023-03-19 15:13:10 +00:00
onClick={() => {
2023-03-21 14:56:27 +00:00
showMemoryPrompt(session);
2023-03-19 15:13:10 +00:00
}}
2023-03-12 19:06:21 +00:00
/>
2023-03-09 17:01:40 +00:00
</div>
2023-03-12 19:06:21 +00:00
<div className={styles["window-action-button"]}>
<IconButton
icon={<ExportIcon />}
bordered
2023-03-20 16:17:45 +00:00
title={Locale.Chat.Actions.Export}
2023-03-15 17:24:03 +00:00
onClick={() => {
2023-03-21 14:56:27 +00:00
exportMessages(session.messages, session.topic);
2023-03-15 17:24:03 +00:00
}}
2023-03-12 19:06:21 +00:00
/>
2023-03-09 17:01:40 +00:00
</div>
</div>
</div>
<div className={styles["chat-body"]}>
2023-03-09 17:01:40 +00:00
{messages.map((message, i) => {
const isUser = message.role === "user";
return (
<div
key={i}
className={
2023-03-09 17:16:20 +00:00
isUser ? styles["chat-message-user"] : styles["chat-message"]
2023-03-09 17:01:40 +00:00
}
>
<div className={styles["chat-message-container"]}>
2023-03-10 18:25:33 +00:00
<div className={styles["chat-message-avatar"]}>
<Avatar role={message.role} />
2023-03-09 17:01:40 +00:00
</div>
2023-03-11 17:14:07 +00:00
{(message.preview || message.streaming) && (
2023-03-21 14:56:27 +00:00
<div className={styles["chat-message-status"]}>
{Locale.Chat.Typing}
</div>
2023-03-10 18:25:33 +00:00
)}
2023-03-09 17:01:40 +00:00
<div className={styles["chat-message-item"]}>
{!isUser && (
<div className={styles["chat-message-top-actions"]}>
2023-03-26 10:59:09 +00:00
{message.streaming ? (
<div
className={styles["chat-message-top-action"]}
2023-03-26 10:59:09 +00:00
onClick={() => onUserStop(i)}
>
{Locale.Chat.Actions.Stop}
</div>
2023-03-26 10:59:09 +00:00
) : (
<div
className={styles["chat-message-top-action"]}
onClick={() => onResend(i)}
>
{Locale.Chat.Actions.Retry}
</div>
)}
<div
className={styles["chat-message-top-action"]}
onClick={() => copyToClipboard(message.content)}
>
{Locale.Chat.Actions.Copy}
</div>
</div>
)}
2023-03-11 12:54:24 +00:00
{(message.preview || message.content.length === 0) &&
2023-03-21 14:56:27 +00:00
!isUser ? (
2023-03-10 18:25:33 +00:00
<LoadingIcon />
) : (
2023-03-21 14:56:27 +00:00
<div
className="markdown-body"
2023-03-26 10:59:09 +00:00
onContextMenu={(e) => onRightClick(e, message)}
2023-03-21 14:56:27 +00:00
>
2023-03-11 12:54:24 +00:00
<Markdown content={message.content} />
2023-03-10 18:25:33 +00:00
</div>
)}
2023-03-09 17:01:40 +00:00
</div>
2023-03-10 18:25:33 +00:00
{!isUser && !message.preview && (
2023-03-09 17:01:40 +00:00
<div className={styles["chat-message-actions"]}>
<div className={styles["chat-message-action-date"]}>
2023-03-10 18:25:33 +00:00
{message.date.toLocaleString()}
2023-03-09 17:01:40 +00:00
</div>
</div>
)}
</div>
</div>
);
})}
<div ref={latestMessageRef} style={{ opacity: 0, height: "2em" }}>
2023-03-10 18:25:33 +00:00
-
</div>
2023-03-09 17:01:40 +00:00
</div>
<div className={styles["chat-input-panel"]}>
2023-03-28 17:30:11 +00:00
<PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
2023-03-09 17:01:40 +00:00
<div className={styles["chat-input-panel-inner"]}>
<textarea
ref={inputRef}
2023-03-09 17:01:40 +00:00
className={styles["chat-input"]}
2023-03-20 16:17:45 +00:00
placeholder={Locale.Chat.Input(submitKey)}
2023-03-28 17:30:11 +00:00
rows={4}
onInput={(e) => onInput(e.currentTarget.value)}
2023-03-10 18:25:33 +00:00
value={userInput}
onKeyDown={(e) => onInputKeyDown(e as any)}
onFocus={() => setAutoScroll(true)}
2023-03-28 17:30:11 +00:00
onBlur={() => {
setAutoScroll(false);
setTimeout(() => setPromptHints([]), 100);
}}
autoFocus
2023-03-09 17:01:40 +00:00
/>
<IconButton
icon={<SendWhiteIcon />}
2023-03-20 16:17:45 +00:00
text={Locale.Chat.Send}
2023-03-12 19:06:21 +00:00
className={styles["chat-input-send"] + " no-dark"}
2023-03-10 18:25:33 +00:00
onClick={onUserSubmit}
2023-03-09 17:01:40 +00:00
/>
</div>
</div>
</div>
);
}
2023-03-12 19:06:21 +00:00
function useSwitchTheme() {
const config = useChatStore((state) => state.config);
useEffect(() => {
document.body.classList.remove("light");
document.body.classList.remove("dark");
2023-03-12 19:06:21 +00:00
if (config.theme === "dark") {
document.body.classList.add("dark");
} else if (config.theme === "light") {
document.body.classList.add("light");
}
2023-03-28 17:30:11 +00:00
const themeColor = getComputedStyle(document.body)
.getPropertyValue("--theme-color")
.trim();
const metaDescription = document.querySelector('meta[name="theme-color"]');
2023-03-28 17:30:11 +00:00
metaDescription?.setAttribute("content", themeColor);
}, [config.theme]);
2023-03-12 19:06:21 +00:00
}
2023-03-15 17:24:03 +00:00
function exportMessages(messages: Message[], topic: string) {
2023-03-21 14:56:27 +00:00
const mdText =
`# ${topic}\n\n` +
messages
.map((m) => {
return m.role === "user" ? `## ${m.content}` : m.content.trim();
})
.join("\n\n");
const filename = `${topic}.md`;
2023-03-15 17:24:03 +00:00
showModal({
2023-03-21 14:56:27 +00:00
title: Locale.Export.Title,
children: (
<div className="markdown-body">
<pre className={styles["export-content"]}>{mdText}</pre>
</div>
),
actions: [
<IconButton
key="copy"
icon={<CopyIcon />}
bordered
text={Locale.Export.Copy}
onClick={() => copyToClipboard(mdText)}
/>,
<IconButton
key="download"
icon={<DownloadIcon />}
bordered
text={Locale.Export.Download}
onClick={() => downloadAs(mdText, filename)}
/>,
],
});
2023-03-15 17:24:03 +00:00
}
2023-03-19 16:09:30 +00:00
function showMemoryPrompt(session: ChatSession) {
2023-03-19 15:13:10 +00:00
showModal({
2023-03-21 14:56:27 +00:00
title: `${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`,
children: (
<div className="markdown-body">
<pre className={styles["export-content"]}>
{session.memoryPrompt || Locale.Memory.EmptyContent}
</pre>
</div>
),
actions: [
<IconButton
key="copy"
icon={<CopyIcon />}
bordered
text={Locale.Memory.Copy}
onClick={() => copyToClipboard(session.memoryPrompt)}
/>,
],
});
2023-03-19 15:13:10 +00:00
}
2023-03-27 08:58:53 +00:00
const useHasHydrated = () => {
const [hasHydrated, setHasHydrated] = useState<boolean>(false);
useEffect(() => {
setHasHydrated(true);
}, []);
return hasHydrated;
};
2023-03-09 17:01:40 +00:00
export function Home() {
2023-03-21 14:56:27 +00:00
const [createNewSession, currentIndex, removeSession] = useChatStore(
(state) => [
state.newSession,
state.currentSessionIndex,
state.removeSession,
]
);
2023-03-27 08:58:53 +00:00
const loading = !useHasHydrated();
2023-03-14 17:44:42 +00:00
const [showSideBar, setShowSideBar] = useState(true);
2023-03-10 18:25:33 +00:00
2023-03-16 16:08:16 +00:00
// setting
2023-03-11 17:14:07 +00:00
const [openSettings, setOpenSettings] = useState(false);
2023-03-12 19:21:48 +00:00
const config = useChatStore((state) => state.config);
2023-03-11 17:14:07 +00:00
2023-03-12 19:06:21 +00:00
useSwitchTheme();
2023-03-13 16:25:07 +00:00
if (loading) {
return <Loading />;
2023-03-13 16:25:07 +00:00
}
2023-03-09 17:01:40 +00:00
return (
2023-03-12 19:21:48 +00:00
<div
2023-03-21 14:56:27 +00:00
className={`${
config.tightBorder ? styles["tight-container"] : styles.container
}`}
2023-03-12 19:21:48 +00:00
>
2023-03-14 17:44:42 +00:00
<div
className={styles.sidebar + ` ${showSideBar && styles["sidebar-show"]}`}
>
2023-03-09 17:01:40 +00:00
<div className={styles["sidebar-header"]}>
<div className={styles["sidebar-title"]}>ChatGPT Next</div>
<div className={styles["sidebar-sub-title"]}>
Build your own AI assistant.
</div>
<div className={styles["sidebar-logo"]}>
<ChatGptIcon />
</div>
</div>
2023-03-12 19:06:21 +00:00
<div
className={styles["sidebar-body"]}
2023-03-20 16:51:20 +00:00
onClick={() => {
2023-03-21 14:56:27 +00:00
setOpenSettings(false);
setShowSideBar(false);
2023-03-20 16:51:20 +00:00
}}
2023-03-12 19:06:21 +00:00
>
2023-03-09 17:01:40 +00:00
<ChatList />
</div>
<div className={styles["sidebar-tail"]}>
<div className={styles["sidebar-actions"]}>
2023-03-14 17:44:42 +00:00
<div className={styles["sidebar-action"] + " " + styles.mobile}>
<IconButton
icon={<CloseIcon />}
2023-03-20 16:51:20 +00:00
onClick={() => {
2023-03-21 14:56:27 +00:00
if (confirm(Locale.Home.DeleteChat)) {
removeSession(currentIndex);
2023-03-20 16:51:20 +00:00
}
}}
2023-03-14 17:44:42 +00:00
/>
</div>
2023-03-09 17:01:40 +00:00
<div className={styles["sidebar-action"]}>
2023-03-11 17:14:07 +00:00
<IconButton
icon={<SettingsIcon />}
onClick={() => {
2023-03-21 14:56:27 +00:00
setOpenSettings(true);
setShowSideBar(false);
}}
2023-03-11 17:14:07 +00:00
/>
2023-03-09 17:01:40 +00:00
</div>
<div className={styles["sidebar-action"]}>
2023-03-23 16:01:00 +00:00
<a href={REPO_URL} target="_blank">
2023-03-10 18:25:33 +00:00
<IconButton icon={<GithubIcon />} />
</a>
2023-03-09 17:01:40 +00:00
</div>
</div>
<div>
2023-03-10 18:25:33 +00:00
<IconButton
icon={<AddIcon />}
2023-03-20 16:17:45 +00:00
text={Locale.Home.NewChat}
2023-03-28 17:30:11 +00:00
onClick={() => {
createNewSession();
setShowSideBar(false);
}}
2023-03-10 18:25:33 +00:00
/>
2023-03-09 17:01:40 +00:00
</div>
</div>
</div>
2023-03-11 17:14:07 +00:00
<div className={styles["window-content"]}>
2023-03-14 17:44:42 +00:00
{openSettings ? (
2023-03-21 14:56:27 +00:00
<Settings
closeSettings={() => {
setOpenSettings(false);
setShowSideBar(true);
}}
/>
2023-03-14 17:44:42 +00:00
) : (
<Chat key="chat" showSideBar={() => setShowSideBar(true)} />
)}
2023-03-11 17:14:07 +00:00
</div>
2023-03-09 17:01:40 +00:00
</div>
);
}