home.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. "use client";
  2. import { useState, useRef, useEffect } from "react";
  3. import ReactMarkdown from "react-markdown";
  4. import "katex/dist/katex.min.css";
  5. import RemarkMath from "remark-math";
  6. import RehypeKatex from "rehype-katex";
  7. import { Emoji } from "emoji-picker-react";
  8. import { IconButton } from "./button";
  9. import styles from "./home.module.scss";
  10. import SettingsIcon from "../icons/settings.svg";
  11. import GithubIcon from "../icons/github.svg";
  12. import ChatGptIcon from "../icons/chatgpt.svg";
  13. import SendWhiteIcon from "../icons/send-white.svg";
  14. import BrainIcon from "../icons/brain.svg";
  15. import ExportIcon from "../icons/export.svg";
  16. import BotIcon from "../icons/bot.svg";
  17. import AddIcon from "../icons/add.svg";
  18. import DeleteIcon from "../icons/delete.svg";
  19. import LoadingIcon from "../icons/three-dots.svg";
  20. import MenuIcon from "../icons/menu.svg";
  21. import CloseIcon from "../icons/close.svg";
  22. import { Message, SubmitKey, useChatStore, Theme } from "../store";
  23. import { Settings } from "./settings";
  24. import dynamic from "next/dynamic";
  25. export function Markdown(props: { content: string }) {
  26. return (
  27. <ReactMarkdown remarkPlugins={[RemarkMath]} rehypePlugins={[RehypeKatex]}>
  28. {props.content}
  29. </ReactMarkdown>
  30. );
  31. }
  32. export function Avatar(props: { role: Message["role"] }) {
  33. const config = useChatStore((state) => state.config);
  34. if (props.role === "assistant") {
  35. return <BotIcon className={styles["user-avtar"]} />;
  36. }
  37. return (
  38. <div className={styles["user-avtar"]}>
  39. <Emoji unified={config.avatar} size={18} />
  40. </div>
  41. );
  42. }
  43. export function ChatItem(props: {
  44. onClick?: () => void;
  45. onDelete?: () => void;
  46. title: string;
  47. count: number;
  48. time: string;
  49. selected: boolean;
  50. }) {
  51. return (
  52. <div
  53. className={`${styles["chat-item"]} ${
  54. props.selected && styles["chat-item-selected"]
  55. }`}
  56. onClick={props.onClick}
  57. >
  58. <div className={styles["chat-item-title"]}>{props.title}</div>
  59. <div className={styles["chat-item-info"]}>
  60. <div className={styles["chat-item-count"]}>{props.count} 条对话</div>
  61. <div className={styles["chat-item-date"]}>{props.time}</div>
  62. </div>
  63. <div className={styles["chat-item-delete"]} onClick={props.onDelete}>
  64. <DeleteIcon />
  65. </div>
  66. </div>
  67. );
  68. }
  69. export function ChatList() {
  70. const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
  71. (state) => [
  72. state.sessions,
  73. state.currentSessionIndex,
  74. state.selectSession,
  75. state.removeSession,
  76. ]
  77. );
  78. return (
  79. <div className={styles["chat-list"]}>
  80. {sessions.map((item, i) => (
  81. <ChatItem
  82. title={item.topic}
  83. time={item.lastUpdate}
  84. count={item.messages.length}
  85. key={i}
  86. selected={i === selectedIndex}
  87. onClick={() => selectSession(i)}
  88. onDelete={() => removeSession(i)}
  89. />
  90. ))}
  91. </div>
  92. );
  93. }
  94. function useSubmitHandler() {
  95. const config = useChatStore((state) => state.config);
  96. const submitKey = config.submitKey;
  97. const shouldSubmit = (e: KeyboardEvent) => {
  98. if (e.key !== "Enter") return false;
  99. return (
  100. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  101. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  102. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  103. config.submitKey === SubmitKey.Enter
  104. );
  105. };
  106. return {
  107. submitKey,
  108. shouldSubmit,
  109. };
  110. }
  111. export function Chat(props: { showSideBar?: () => void }) {
  112. type RenderMessage = Message & { preview?: boolean };
  113. const session = useChatStore((state) => state.currentSession());
  114. const [userInput, setUserInput] = useState("");
  115. const [isLoading, setIsLoading] = useState(false);
  116. const { submitKey, shouldSubmit } = useSubmitHandler();
  117. const onUserInput = useChatStore((state) => state.onUserInput);
  118. const onUserSubmit = () => {
  119. if (userInput.length <= 0) return;
  120. setIsLoading(true);
  121. onUserInput(userInput).then(() => setIsLoading(false));
  122. setUserInput("");
  123. };
  124. const onInputKeyDown = (e: KeyboardEvent) => {
  125. if (shouldSubmit(e)) {
  126. onUserSubmit();
  127. e.preventDefault();
  128. }
  129. };
  130. const latestMessageRef = useRef<HTMLDivElement>(null);
  131. const messages = (session.messages as RenderMessage[])
  132. .concat(
  133. isLoading
  134. ? [
  135. {
  136. role: "assistant",
  137. content: "……",
  138. date: new Date().toLocaleString(),
  139. preview: true,
  140. },
  141. ]
  142. : []
  143. )
  144. .concat(
  145. userInput.length > 0
  146. ? [
  147. {
  148. role: "user",
  149. content: userInput,
  150. date: new Date().toLocaleString(),
  151. preview: true,
  152. },
  153. ]
  154. : []
  155. );
  156. useEffect(() => {
  157. latestMessageRef.current?.scrollIntoView({
  158. behavior: "smooth",
  159. block: "end",
  160. });
  161. });
  162. return (
  163. <div className={styles.chat} key={session.id}>
  164. <div className={styles["window-header"]}>
  165. <div>
  166. <div className={styles["window-header-title"]}>{session.topic}</div>
  167. <div className={styles["window-header-sub-title"]}>
  168. 与 ChatGPT 的 {session.messages.length} 条对话
  169. </div>
  170. </div>
  171. <div className={styles["window-actions"]}>
  172. <div className={styles["window-action-button"] + " " + styles.mobile}>
  173. <IconButton
  174. icon={<MenuIcon />}
  175. bordered
  176. title="查看消息列表"
  177. onClick={props?.showSideBar}
  178. />
  179. </div>
  180. <div className={styles["window-action-button"]}>
  181. <IconButton
  182. icon={<BrainIcon />}
  183. bordered
  184. title="查看压缩后的历史 Prompt(开发中)"
  185. />
  186. </div>
  187. <div className={styles["window-action-button"]}>
  188. <IconButton
  189. icon={<ExportIcon />}
  190. bordered
  191. title="导出聊天记录为 Markdown(开发中)"
  192. />
  193. </div>
  194. </div>
  195. </div>
  196. <div className={styles["chat-body"]}>
  197. {messages.map((message, i) => {
  198. const isUser = message.role === "user";
  199. return (
  200. <div
  201. key={i}
  202. className={
  203. isUser ? styles["chat-message-user"] : styles["chat-message"]
  204. }
  205. >
  206. <div className={styles["chat-message-container"]}>
  207. <div className={styles["chat-message-avatar"]}>
  208. <Avatar role={message.role} />
  209. </div>
  210. {(message.preview || message.streaming) && (
  211. <div className={styles["chat-message-status"]}>正在输入…</div>
  212. )}
  213. <div className={styles["chat-message-item"]}>
  214. {(message.preview || message.content.length === 0) &&
  215. !isUser ? (
  216. <LoadingIcon />
  217. ) : (
  218. <div className="markdown-body">
  219. <Markdown content={message.content} />
  220. </div>
  221. )}
  222. </div>
  223. {!isUser && !message.preview && (
  224. <div className={styles["chat-message-actions"]}>
  225. <div className={styles["chat-message-action-date"]}>
  226. {message.date.toLocaleString()}
  227. </div>
  228. </div>
  229. )}
  230. </div>
  231. </div>
  232. );
  233. })}
  234. <span ref={latestMessageRef} style={{ opacity: 0 }}>
  235. -
  236. </span>
  237. </div>
  238. <div className={styles["chat-input-panel"]}>
  239. <div className={styles["chat-input-panel-inner"]}>
  240. <textarea
  241. className={styles["chat-input"]}
  242. placeholder={`输入消息,${submitKey} 发送`}
  243. rows={3}
  244. onInput={(e) => setUserInput(e.currentTarget.value)}
  245. value={userInput}
  246. onKeyDown={(e) => onInputKeyDown(e as any)}
  247. />
  248. <IconButton
  249. icon={<SendWhiteIcon />}
  250. text={"发送"}
  251. className={styles["chat-input-send"] + " no-dark"}
  252. onClick={onUserSubmit}
  253. />
  254. </div>
  255. </div>
  256. </div>
  257. );
  258. }
  259. function useSwitchTheme() {
  260. const config = useChatStore((state) => state.config);
  261. useEffect(() => {
  262. document.body.classList.remove("light");
  263. document.body.classList.remove("dark");
  264. if (config.theme === "dark") {
  265. document.body.classList.add("dark");
  266. } else if (config.theme === "light") {
  267. document.body.classList.add("light");
  268. }
  269. }, [config.theme]);
  270. }
  271. export function Home() {
  272. const [createNewSession] = useChatStore((state) => [state.newSession]);
  273. const loading = !useChatStore?.persist?.hasHydrated();
  274. const [showSideBar, setShowSideBar] = useState(true);
  275. // settings
  276. const [openSettings, setOpenSettings] = useState(false);
  277. const config = useChatStore((state) => state.config);
  278. useSwitchTheme();
  279. if (loading) {
  280. return (
  281. <div>
  282. <Avatar role="assistant"></Avatar>
  283. <LoadingIcon />
  284. </div>
  285. );
  286. }
  287. return (
  288. <div
  289. className={`${
  290. config.tightBorder ? styles["tight-container"] : styles.container
  291. }`}
  292. >
  293. <div
  294. className={styles.sidebar + ` ${showSideBar && styles["sidebar-show"]}`}
  295. >
  296. <div className={styles["sidebar-header"]}>
  297. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  298. <div className={styles["sidebar-sub-title"]}>
  299. Build your own AI assistant.
  300. </div>
  301. <div className={styles["sidebar-logo"]}>
  302. <ChatGptIcon />
  303. </div>
  304. </div>
  305. <div
  306. className={styles["sidebar-body"]}
  307. onClick={() => setOpenSettings(false)}
  308. >
  309. <ChatList />
  310. </div>
  311. <div className={styles["sidebar-tail"]}>
  312. <div className={styles["sidebar-actions"]}>
  313. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  314. <IconButton
  315. icon={<CloseIcon />}
  316. onClick={() => setShowSideBar(!showSideBar)}
  317. />
  318. </div>
  319. <div className={styles["sidebar-action"]}>
  320. <IconButton
  321. icon={<SettingsIcon />}
  322. onClick={() => setOpenSettings(!openSettings)}
  323. />
  324. </div>
  325. <div className={styles["sidebar-action"]}>
  326. <a href="https://github.com/Yidadaa" target="_blank">
  327. <IconButton icon={<GithubIcon />} />
  328. </a>
  329. </div>
  330. </div>
  331. <div>
  332. <IconButton
  333. icon={<AddIcon />}
  334. text={"新的聊天"}
  335. onClick={createNewSession}
  336. />
  337. </div>
  338. </div>
  339. </div>
  340. <div className={styles["window-content"]}>
  341. {openSettings ? (
  342. <Settings closeSettings={() => setOpenSettings(false)} />
  343. ) : (
  344. <Chat key="chat" showSideBar={() => setShowSideBar(true)} />
  345. )}
  346. </div>
  347. </div>
  348. );
  349. }