home.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 { Message, SubmitKey, useChatStore, Theme } from "../store";
  21. import { Settings } from "./settings";
  22. import dynamic from "next/dynamic";
  23. export const LazySettings = dynamic(
  24. async () => await (await import("./settings")).Settings,
  25. {
  26. loading: () => (
  27. <div className="">
  28. <LoadingIcon />
  29. </div>
  30. ),
  31. }
  32. );
  33. export function Markdown(props: { content: string }) {
  34. return (
  35. <ReactMarkdown remarkPlugins={[RemarkMath]} rehypePlugins={[RehypeKatex]}>
  36. {props.content}
  37. </ReactMarkdown>
  38. );
  39. }
  40. export function Avatar(props: { role: Message["role"] }) {
  41. const config = useChatStore((state) => state.config);
  42. if (props.role === "assistant") {
  43. return <BotIcon className={styles["user-avtar"]} />;
  44. }
  45. return (
  46. <div className={styles["user-avtar"]}>
  47. <Emoji unified={config.avatar} size={18} />
  48. </div>
  49. );
  50. }
  51. export function ChatItem(props: {
  52. onClick?: () => void;
  53. onDelete?: () => void;
  54. title: string;
  55. count: number;
  56. time: string;
  57. selected: boolean;
  58. }) {
  59. return (
  60. <div
  61. className={`${styles["chat-item"]} ${
  62. props.selected && styles["chat-item-selected"]
  63. }`}
  64. onClick={props.onClick}
  65. >
  66. <div className={styles["chat-item-title"]}>{props.title}</div>
  67. <div className={styles["chat-item-info"]}>
  68. <div className={styles["chat-item-count"]}>{props.count} 条对话</div>
  69. <div className={styles["chat-item-date"]}>{props.time}</div>
  70. </div>
  71. <div className={styles["chat-item-delete"]} onClick={props.onDelete}>
  72. <DeleteIcon />
  73. </div>
  74. </div>
  75. );
  76. }
  77. export function ChatList() {
  78. const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
  79. (state) => [
  80. state.sessions,
  81. state.currentSessionIndex,
  82. state.selectSession,
  83. state.removeSession,
  84. ]
  85. );
  86. return (
  87. <div className={styles["chat-list"]}>
  88. {sessions.map((item, i) => (
  89. <ChatItem
  90. title={item.topic}
  91. time={item.lastUpdate}
  92. count={item.messages.length}
  93. key={i}
  94. selected={i === selectedIndex}
  95. onClick={() => selectSession(i)}
  96. onDelete={() => removeSession(i)}
  97. />
  98. ))}
  99. </div>
  100. );
  101. }
  102. function useSubmitHandler() {
  103. const config = useChatStore((state) => state.config);
  104. const submitKey = config.submitKey;
  105. const shouldSubmit = (e: KeyboardEvent) => {
  106. if (e.key !== "Enter") return false;
  107. return (
  108. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  109. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  110. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  111. config.submitKey === SubmitKey.Enter
  112. );
  113. };
  114. return {
  115. submitKey,
  116. shouldSubmit,
  117. };
  118. }
  119. export function Chat() {
  120. type RenderMessage = Message & { preview?: boolean };
  121. const session = useChatStore((state) => state.currentSession());
  122. const [userInput, setUserInput] = useState("");
  123. const [isLoading, setIsLoading] = useState(false);
  124. const { submitKey, shouldSubmit } = useSubmitHandler();
  125. const onUserInput = useChatStore((state) => state.onUserInput);
  126. const onUserSubmit = () => {
  127. if (userInput.length <= 0) return;
  128. setIsLoading(true);
  129. onUserInput(userInput).then(() => setIsLoading(false));
  130. setUserInput("");
  131. };
  132. const onInputKeyDown = (e: KeyboardEvent) => {
  133. if (shouldSubmit(e)) {
  134. onUserSubmit();
  135. e.preventDefault();
  136. }
  137. };
  138. const latestMessageRef = useRef<HTMLDivElement>(null);
  139. const messages = (session.messages as RenderMessage[])
  140. .concat(
  141. isLoading
  142. ? [
  143. {
  144. role: "assistant",
  145. content: "……",
  146. date: new Date().toLocaleString(),
  147. preview: true,
  148. },
  149. ]
  150. : []
  151. )
  152. .concat(
  153. userInput.length > 0
  154. ? [
  155. {
  156. role: "user",
  157. content: userInput,
  158. date: new Date().toLocaleString(),
  159. preview: true,
  160. },
  161. ]
  162. : []
  163. );
  164. useEffect(() => {
  165. latestMessageRef.current?.scrollIntoView({
  166. behavior: "smooth",
  167. block: "end",
  168. });
  169. });
  170. return (
  171. <div className={styles.chat} key={session.id}>
  172. <div className={styles["window-header"]}>
  173. <div>
  174. <div className={styles["window-header-title"]}>{session.topic}</div>
  175. <div className={styles["window-header-sub-title"]}>
  176. 与 ChatGPT 的 {session.messages.length} 条对话
  177. </div>
  178. </div>
  179. <div className={styles["window-actions"]}>
  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. // 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={`${
  289. config.tightBorder ? styles["tight-container"] : styles.container
  290. }`}
  291. >
  292. <div className={styles.sidebar}>
  293. <div className={styles["sidebar-header"]}>
  294. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  295. <div className={styles["sidebar-sub-title"]}>
  296. Build your own AI assistant.
  297. </div>
  298. <div className={styles["sidebar-logo"]}>
  299. <ChatGptIcon />
  300. </div>
  301. </div>
  302. <div
  303. className={styles["sidebar-body"]}
  304. onClick={() => setOpenSettings(false)}
  305. >
  306. <ChatList />
  307. </div>
  308. <div className={styles["sidebar-tail"]}>
  309. <div className={styles["sidebar-actions"]}>
  310. <div className={styles["sidebar-action"]}>
  311. <IconButton
  312. icon={<SettingsIcon />}
  313. onClick={() => setOpenSettings(!openSettings)}
  314. />
  315. </div>
  316. <div className={styles["sidebar-action"]}>
  317. <a href="https://github.com/Yidadaa" target="_blank">
  318. <IconButton icon={<GithubIcon />} />
  319. </a>
  320. </div>
  321. </div>
  322. <div>
  323. <IconButton
  324. icon={<AddIcon />}
  325. text={"新的聊天"}
  326. onClick={createNewSession}
  327. />
  328. </div>
  329. </div>
  330. </div>
  331. <div className={styles["window-content"]}>
  332. {openSettings ? <LazySettings /> : <Chat key="chat" />}
  333. </div>
  334. </div>
  335. );
  336. }