home.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 EmojiPicker, { Emoji, Theme as EmojiTheme } 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 ResetIcon from "../icons/reload.svg";
  21. import { Message, SubmitKey, useChatStore, Theme } from "../store";
  22. import { Card, List, ListItem, Popover } from "./ui-lib";
  23. export function Markdown(props: { content: string }) {
  24. return (
  25. <ReactMarkdown remarkPlugins={[RemarkMath]} rehypePlugins={[RehypeKatex]}>
  26. {props.content}
  27. </ReactMarkdown>
  28. );
  29. }
  30. export function Avatar(props: { role: Message["role"] }) {
  31. const config = useChatStore((state) => state.config);
  32. if (props.role === "assistant") {
  33. return <BotIcon className={styles["user-avtar"]} />;
  34. }
  35. return (
  36. <div className={styles["user-avtar"]}>
  37. <Emoji unified={config.avatar} size={18} />
  38. </div>
  39. );
  40. }
  41. export function ChatItem(props: {
  42. onClick?: () => void;
  43. onDelete?: () => void;
  44. title: string;
  45. count: number;
  46. time: string;
  47. selected: boolean;
  48. }) {
  49. return (
  50. <div
  51. className={`${styles["chat-item"]} ${
  52. props.selected && styles["chat-item-selected"]
  53. }`}
  54. onClick={props.onClick}
  55. >
  56. <div className={styles["chat-item-title"]}>{props.title}</div>
  57. <div className={styles["chat-item-info"]}>
  58. <div className={styles["chat-item-count"]}>{props.count} 条对话</div>
  59. <div className={styles["chat-item-date"]}>{props.time}</div>
  60. </div>
  61. <div className={styles["chat-item-delete"]} onClick={props.onDelete}>
  62. <DeleteIcon />
  63. </div>
  64. </div>
  65. );
  66. }
  67. export function ChatList() {
  68. const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
  69. (state) => [
  70. state.sessions,
  71. state.currentSessionIndex,
  72. state.selectSession,
  73. state.removeSession,
  74. ]
  75. );
  76. return (
  77. <div className={styles["chat-list"]}>
  78. {sessions.map((item, i) => (
  79. <ChatItem
  80. title={item.topic}
  81. time={item.lastUpdate}
  82. count={item.messages.length}
  83. key={i}
  84. selected={i === selectedIndex}
  85. onClick={() => selectSession(i)}
  86. onDelete={() => removeSession(i)}
  87. />
  88. ))}
  89. </div>
  90. );
  91. }
  92. function useSubmitHandler() {
  93. const config = useChatStore((state) => state.config);
  94. const submitKey = config.submitKey;
  95. const shouldSubmit = (e: KeyboardEvent) => {
  96. if (e.key !== "Enter") return false;
  97. return (
  98. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  99. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  100. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  101. config.submitKey === SubmitKey.Enter
  102. );
  103. };
  104. return {
  105. submitKey,
  106. shouldSubmit,
  107. };
  108. }
  109. export function Chat() {
  110. type RenderMessage = Message & { preview?: boolean };
  111. const session = useChatStore((state) => state.currentSession());
  112. const [userInput, setUserInput] = useState("");
  113. const [isLoading, setIsLoading] = useState(false);
  114. const { submitKey, shouldSubmit } = useSubmitHandler();
  115. const onUserInput = useChatStore((state) => state.onUserInput);
  116. const onUserSubmit = () => {
  117. if (userInput.length <= 0) return;
  118. setIsLoading(true);
  119. onUserInput(userInput).then(() => setIsLoading(false));
  120. setUserInput("");
  121. };
  122. const onInputKeyDown = (e: KeyboardEvent) => {
  123. if (shouldSubmit(e)) {
  124. onUserSubmit();
  125. e.preventDefault();
  126. }
  127. };
  128. const latestMessageRef = useRef<HTMLDivElement>(null);
  129. const messages = (session.messages as RenderMessage[])
  130. .concat(
  131. isLoading
  132. ? [
  133. {
  134. role: "assistant",
  135. content: "……",
  136. date: new Date().toLocaleString(),
  137. preview: true,
  138. },
  139. ]
  140. : []
  141. )
  142. .concat(
  143. userInput.length > 0
  144. ? [
  145. {
  146. role: "user",
  147. content: userInput,
  148. date: new Date().toLocaleString(),
  149. preview: true,
  150. },
  151. ]
  152. : []
  153. );
  154. useEffect(() => {
  155. latestMessageRef.current?.scrollIntoView({
  156. behavior: "smooth",
  157. block: "end",
  158. });
  159. });
  160. return (
  161. <div className={styles.chat} key={session.id}>
  162. <div className={styles["window-header"]}>
  163. <div>
  164. <div className={styles["window-header-title"]}>{session.topic}</div>
  165. <div className={styles["window-header-sub-title"]}>
  166. 与 ChatGPT 的 {session.messages.length} 条对话
  167. </div>
  168. </div>
  169. <div className={styles["window-actions"]}>
  170. <div className={styles["window-action-button"]}>
  171. <IconButton
  172. icon={<BrainIcon />}
  173. bordered
  174. title="查看压缩后的历史 Prompt(开发中)"
  175. />
  176. </div>
  177. <div className={styles["window-action-button"]}>
  178. <IconButton
  179. icon={<ExportIcon />}
  180. bordered
  181. title="导出聊天记录为 Markdown(开发中)"
  182. />
  183. </div>
  184. </div>
  185. </div>
  186. <div className={styles["chat-body"]}>
  187. {messages.map((message, i) => {
  188. const isUser = message.role === "user";
  189. return (
  190. <div
  191. key={i}
  192. className={
  193. isUser ? styles["chat-message-user"] : styles["chat-message"]
  194. }
  195. >
  196. <div className={styles["chat-message-container"]}>
  197. <div className={styles["chat-message-avatar"]}>
  198. <Avatar role={message.role} />
  199. </div>
  200. {(message.preview || message.streaming) && (
  201. <div className={styles["chat-message-status"]}>正在输入…</div>
  202. )}
  203. <div className={styles["chat-message-item"]}>
  204. {(message.preview || message.content.length === 0) &&
  205. !isUser ? (
  206. <LoadingIcon />
  207. ) : (
  208. <div className="markdown-body">
  209. <Markdown content={message.content} />
  210. </div>
  211. )}
  212. </div>
  213. {!isUser && !message.preview && (
  214. <div className={styles["chat-message-actions"]}>
  215. <div className={styles["chat-message-action-date"]}>
  216. {message.date.toLocaleString()}
  217. </div>
  218. </div>
  219. )}
  220. </div>
  221. </div>
  222. );
  223. })}
  224. <span ref={latestMessageRef} style={{ opacity: 0 }}>
  225. -
  226. </span>
  227. </div>
  228. <div className={styles["chat-input-panel"]}>
  229. <div className={styles["chat-input-panel-inner"]}>
  230. <textarea
  231. className={styles["chat-input"]}
  232. placeholder={`输入消息,${submitKey} 发送`}
  233. rows={3}
  234. onInput={(e) => setUserInput(e.currentTarget.value)}
  235. value={userInput}
  236. onKeyDown={(e) => onInputKeyDown(e as any)}
  237. />
  238. <IconButton
  239. icon={<SendWhiteIcon />}
  240. text={"发送"}
  241. className={styles["chat-input-send"] + " no-dark"}
  242. onClick={onUserSubmit}
  243. />
  244. </div>
  245. </div>
  246. </div>
  247. );
  248. }
  249. function useSwitchTheme() {
  250. const config = useChatStore((state) => state.config);
  251. useEffect(() => {
  252. document.body.classList.remove("light");
  253. document.body.classList.remove("dark");
  254. if (config.theme === "dark") {
  255. document.body.classList.add("dark");
  256. } else if (config.theme === "light") {
  257. document.body.classList.add("light");
  258. }
  259. }, [config.theme]);
  260. }
  261. export function Home() {
  262. const [createNewSession] = useChatStore((state) => [state.newSession]);
  263. // settings
  264. const [openSettings, setOpenSettings] = useState(false);
  265. useSwitchTheme();
  266. return (
  267. <div className={styles.container}>
  268. <div className={styles.sidebar}>
  269. <div className={styles["sidebar-header"]}>
  270. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  271. <div className={styles["sidebar-sub-title"]}>
  272. Build your own AI assistant.
  273. </div>
  274. <div className={styles["sidebar-logo"]}>
  275. <ChatGptIcon />
  276. </div>
  277. </div>
  278. <div
  279. className={styles["sidebar-body"]}
  280. onClick={() => setOpenSettings(false)}
  281. >
  282. <ChatList />
  283. </div>
  284. <div className={styles["sidebar-tail"]}>
  285. <div className={styles["sidebar-actions"]}>
  286. <div className={styles["sidebar-action"]}>
  287. <IconButton
  288. icon={<SettingsIcon />}
  289. onClick={() => setOpenSettings(!openSettings)}
  290. />
  291. </div>
  292. <div className={styles["sidebar-action"]}>
  293. <a href="https://github.com/Yidadaa" target="_blank">
  294. <IconButton icon={<GithubIcon />} />
  295. </a>
  296. </div>
  297. </div>
  298. <div>
  299. <IconButton
  300. icon={<AddIcon />}
  301. text={"新的聊天"}
  302. onClick={createNewSession}
  303. />
  304. </div>
  305. </div>
  306. </div>
  307. <div className={styles["window-content"]}>
  308. {openSettings ? <Settings /> : <Chat key="chat" />}
  309. </div>
  310. </div>
  311. );
  312. }
  313. export function Settings() {
  314. const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  315. const [config, updateConfig] = useChatStore((state) => [
  316. state.config,
  317. state.updateConfig,
  318. ]);
  319. return (
  320. <>
  321. <div className={styles["window-header"]}>
  322. <div>
  323. <div className={styles["window-header-title"]}>设置</div>
  324. <div className={styles["window-header-sub-title"]}>设置选项</div>
  325. </div>
  326. <div className={styles["window-actions"]}>
  327. <div className={styles["window-action-button"]}>
  328. <IconButton icon={<ResetIcon />} bordered title="重置所有选项" />
  329. </div>
  330. </div>
  331. </div>
  332. <div className={styles["settings"]}>
  333. <List>
  334. <ListItem>
  335. <div className={styles["settings-title"]}>头像</div>
  336. <Popover
  337. onClose={() => setShowEmojiPicker(false)}
  338. content={
  339. <EmojiPicker
  340. lazyLoadEmojis
  341. theme={EmojiTheme.AUTO}
  342. onEmojiClick={(e) => {
  343. updateConfig((config) => (config.avatar = e.unified));
  344. setShowEmojiPicker(false);
  345. }}
  346. />
  347. }
  348. open={showEmojiPicker}
  349. >
  350. <div
  351. className={styles.avatar}
  352. onClick={() => setShowEmojiPicker(true)}
  353. >
  354. <Avatar role="user" />
  355. </div>
  356. </Popover>
  357. </ListItem>
  358. <ListItem>
  359. <div className={styles["settings-title"]}>发送键</div>
  360. <div className="">
  361. <select
  362. value={config.submitKey}
  363. onChange={(e) => {
  364. updateConfig(
  365. (config) =>
  366. (config.submitKey = e.target.value as any as SubmitKey)
  367. );
  368. }}
  369. >
  370. {Object.values(SubmitKey).map((v) => (
  371. <option value={v} key={v}>
  372. {v}
  373. </option>
  374. ))}
  375. </select>
  376. </div>
  377. </ListItem>
  378. <ListItem>
  379. <div className={styles["settings-title"]}>主题</div>
  380. <div className="">
  381. <select
  382. value={config.theme}
  383. onChange={(e) => {
  384. updateConfig(
  385. (config) => (config.theme = e.target.value as any as Theme)
  386. );
  387. }}
  388. >
  389. {Object.values(Theme).map((v) => (
  390. <option value={v} key={v}>
  391. {v}
  392. </option>
  393. ))}
  394. </select>
  395. </div>
  396. </ListItem>
  397. </List>
  398. <List>
  399. <ListItem>
  400. <div className={styles["settings-title"]}>最大上下文消息数</div>
  401. <input
  402. type="range"
  403. title={config.historyMessageCount.toString()}
  404. value={config.historyMessageCount}
  405. min="5"
  406. max="20"
  407. step="5"
  408. onChange={(e) =>
  409. updateConfig(
  410. (config) =>
  411. (config.historyMessageCount = e.target.valueAsNumber)
  412. )
  413. }
  414. ></input>
  415. </ListItem>
  416. <ListItem>
  417. <div className={styles["settings-title"]}>
  418. 上下文中包含机器人消息
  419. </div>
  420. <input
  421. type="checkbox"
  422. checked={config.sendBotMessages}
  423. onChange={(e) =>
  424. updateConfig(
  425. (config) => (config.sendBotMessages = e.currentTarget.checked)
  426. )
  427. }
  428. ></input>
  429. </ListItem>
  430. </List>
  431. </div>
  432. </>
  433. );
  434. }