home.tsx 12 KB

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