home.tsx 12 KB

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