home.tsx 11 KB

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