home.tsx 11 KB

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