home.tsx 12 KB

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