home.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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, ChatSession } from "../store";
  25. import { Settings } from "./settings";
  26. import { showModal } from "./ui-lib";
  27. import { copyToClipboard, downloadAs, isIOS } 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. const dom = latestMessageRef.current
  160. if (dom && !isIOS()) {
  161. dom.scrollIntoView({
  162. behavior: "smooth",
  163. block: "end"
  164. });
  165. }
  166. });
  167. return (
  168. <div className={styles.chat} key={session.id}>
  169. <div className={styles["window-header"]}>
  170. <div className={styles["window-header-title"]}>
  171. <div className={styles["window-header-main-title"]}>{session.topic}</div>
  172. <div className={styles["window-header-sub-title"]}>
  173. 与 ChatGPT 的 {session.messages.length} 条对话
  174. </div>
  175. </div>
  176. <div className={styles["window-actions"]}>
  177. <div className={styles["window-action-button"] + " " + styles.mobile}>
  178. <IconButton
  179. icon={<MenuIcon />}
  180. bordered
  181. title="查看消息列表"
  182. onClick={props?.showSideBar}
  183. />
  184. </div>
  185. <div className={styles["window-action-button"]}>
  186. <IconButton
  187. icon={<BrainIcon />}
  188. bordered
  189. title="查看压缩后的历史 Prompt"
  190. onClick={() => {
  191. showMemoryPrompt(session)
  192. }}
  193. />
  194. </div>
  195. <div className={styles["window-action-button"]}>
  196. <IconButton
  197. icon={<ExportIcon />}
  198. bordered
  199. title="导出聊天记录"
  200. onClick={() => {
  201. exportMessages(session.messages, session.topic)
  202. }}
  203. />
  204. </div>
  205. </div>
  206. </div>
  207. <div className={styles["chat-body"]}>
  208. {messages.map((message, i) => {
  209. const isUser = message.role === "user";
  210. return (
  211. <div
  212. key={i}
  213. className={
  214. isUser ? styles["chat-message-user"] : styles["chat-message"]
  215. }
  216. >
  217. <div className={styles["chat-message-container"]}>
  218. <div className={styles["chat-message-avatar"]}>
  219. <Avatar role={message.role} />
  220. </div>
  221. {(message.preview || message.streaming) && (
  222. <div className={styles["chat-message-status"]}>正在输入…</div>
  223. )}
  224. <div className={styles["chat-message-item"]}>
  225. {(message.preview || message.content.length === 0) &&
  226. !isUser ? (
  227. <LoadingIcon />
  228. ) : (
  229. <div className="markdown-body">
  230. <Markdown content={message.content} />
  231. </div>
  232. )}
  233. </div>
  234. {!isUser && !message.preview && (
  235. <div className={styles["chat-message-actions"]}>
  236. <div className={styles["chat-message-action-date"]}>
  237. {message.date.toLocaleString()}
  238. </div>
  239. </div>
  240. )}
  241. </div>
  242. </div>
  243. );
  244. })}
  245. <span ref={latestMessageRef} style={{ opacity: 0 }}>
  246. -
  247. </span>
  248. </div>
  249. <div className={styles["chat-input-panel"]}>
  250. <div className={styles["chat-input-panel-inner"]}>
  251. <textarea
  252. className={styles["chat-input"]}
  253. placeholder={`输入消息,${submitKey} 发送`}
  254. rows={3}
  255. onInput={(e) => setUserInput(e.currentTarget.value)}
  256. value={userInput}
  257. onKeyDown={(e) => onInputKeyDown(e as any)}
  258. />
  259. <IconButton
  260. icon={<SendWhiteIcon />}
  261. text={"发送"}
  262. className={styles["chat-input-send"] + " no-dark"}
  263. onClick={onUserSubmit}
  264. />
  265. </div>
  266. </div>
  267. </div>
  268. );
  269. }
  270. function useSwitchTheme() {
  271. const config = useChatStore((state) => state.config);
  272. useEffect(() => {
  273. document.body.classList.remove("light");
  274. document.body.classList.remove("dark");
  275. if (config.theme === "dark") {
  276. document.body.classList.add("dark");
  277. } else if (config.theme === "light") {
  278. document.body.classList.add("light");
  279. }
  280. }, [config.theme]);
  281. }
  282. function exportMessages(messages: Message[], topic: string) {
  283. const mdText = `# ${topic}\n\n` + messages.map(m => {
  284. return m.role === 'user' ? `## ${m.content}` : m.content.trim()
  285. }).join('\n\n')
  286. const filename = `${topic}.md`
  287. showModal({
  288. title: "导出聊天记录为 Markdown", children: <div className="markdown-body">
  289. <pre className={styles['export-content']}>{mdText}</pre>
  290. </div>, actions: [
  291. <IconButton key="copy" icon={<CopyIcon />} bordered text="全部复制" onClick={() => copyToClipboard(mdText)} />,
  292. <IconButton key="download" icon={<DownloadIcon />} bordered text="下载文件" onClick={() => downloadAs(mdText, filename)} />
  293. ]
  294. })
  295. }
  296. function showMemoryPrompt(session: ChatSession) {
  297. showModal({
  298. title: `上下文记忆 Prompt (${session.lastSummarizeIndex} of ${session.messages.length})`, children: <div className="markdown-body">
  299. <pre className={styles['export-content']}>{session.memoryPrompt || '无'}</pre>
  300. </div>, actions: [
  301. <IconButton key="copy" icon={<CopyIcon />} bordered text="全部复制" onClick={() => copyToClipboard(session.memoryPrompt)} />,
  302. ]
  303. })
  304. }
  305. export function Home() {
  306. const [createNewSession] = useChatStore((state) => [state.newSession]);
  307. const loading = !useChatStore?.persist?.hasHydrated();
  308. const [showSideBar, setShowSideBar] = useState(true);
  309. // setting
  310. const [openSettings, setOpenSettings] = useState(false);
  311. const config = useChatStore((state) => state.config);
  312. useSwitchTheme();
  313. if (loading) {
  314. return (
  315. <div>
  316. <Avatar role="assistant"></Avatar>
  317. <LoadingIcon />
  318. </div>
  319. );
  320. }
  321. return (
  322. <div
  323. className={`${config.tightBorder ? styles["tight-container"] : styles.container
  324. }`}
  325. >
  326. <div
  327. className={styles.sidebar + ` ${showSideBar && styles["sidebar-show"]}`}
  328. onClick={() => setShowSideBar(false)}
  329. >
  330. <div className={styles["sidebar-header"]}>
  331. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  332. <div className={styles["sidebar-sub-title"]}>
  333. Build your own AI assistant.
  334. </div>
  335. <div className={styles["sidebar-logo"]}>
  336. <ChatGptIcon />
  337. </div>
  338. </div>
  339. <div
  340. className={styles["sidebar-body"]}
  341. onClick={() => setOpenSettings(false)}
  342. >
  343. <ChatList />
  344. </div>
  345. <div className={styles["sidebar-tail"]}>
  346. <div className={styles["sidebar-actions"]}>
  347. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  348. <IconButton
  349. icon={<CloseIcon />}
  350. onClick={() => setShowSideBar(!showSideBar)}
  351. />
  352. </div>
  353. <div className={styles["sidebar-action"]}>
  354. <IconButton
  355. icon={<SettingsIcon />}
  356. onClick={() => setOpenSettings(!openSettings)}
  357. />
  358. </div>
  359. <div className={styles["sidebar-action"]}>
  360. <a href="https://github.com/Yidadaa" target="_blank">
  361. <IconButton icon={<GithubIcon />} />
  362. </a>
  363. </div>
  364. </div>
  365. <div>
  366. <IconButton
  367. icon={<AddIcon />}
  368. text={"新的聊天"}
  369. onClick={createNewSession}
  370. />
  371. </div>
  372. </div>
  373. </div>
  374. <div className={styles["window-content"]}>
  375. {openSettings ? (
  376. <Settings closeSettings={() => setOpenSettings(false)} />
  377. ) : (
  378. <Chat key="chat" showSideBar={() => setShowSideBar(true)} />
  379. )}
  380. </div>
  381. </div>
  382. );
  383. }