home.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. const config = useChatStore((state) => state.config);
  266. useSwitchTheme();
  267. return (
  268. <div
  269. className={`${
  270. config.tightBorder ? styles["tight-container"] : styles.container
  271. }`}
  272. >
  273. <div className={styles.sidebar}>
  274. <div className={styles["sidebar-header"]}>
  275. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  276. <div className={styles["sidebar-sub-title"]}>
  277. Build your own AI assistant.
  278. </div>
  279. <div className={styles["sidebar-logo"]}>
  280. <ChatGptIcon />
  281. </div>
  282. </div>
  283. <div
  284. className={styles["sidebar-body"]}
  285. onClick={() => setOpenSettings(false)}
  286. >
  287. <ChatList />
  288. </div>
  289. <div className={styles["sidebar-tail"]}>
  290. <div className={styles["sidebar-actions"]}>
  291. <div className={styles["sidebar-action"]}>
  292. <IconButton
  293. icon={<SettingsIcon />}
  294. onClick={() => setOpenSettings(!openSettings)}
  295. />
  296. </div>
  297. <div className={styles["sidebar-action"]}>
  298. <a href="https://github.com/Yidadaa" target="_blank">
  299. <IconButton icon={<GithubIcon />} />
  300. </a>
  301. </div>
  302. </div>
  303. <div>
  304. <IconButton
  305. icon={<AddIcon />}
  306. text={"新的聊天"}
  307. onClick={createNewSession}
  308. />
  309. </div>
  310. </div>
  311. </div>
  312. <div className={styles["window-content"]}>
  313. {openSettings ? <Settings /> : <Chat key="chat" />}
  314. </div>
  315. </div>
  316. );
  317. }
  318. export function Settings() {
  319. const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  320. const [config, updateConfig, resetConfig] = useChatStore((state) => [
  321. state.config,
  322. state.updateConfig,
  323. state.resetConfig,
  324. ]);
  325. return (
  326. <>
  327. <div className={styles["window-header"]}>
  328. <div>
  329. <div className={styles["window-header-title"]}>设置</div>
  330. <div className={styles["window-header-sub-title"]}>设置选项</div>
  331. </div>
  332. <div className={styles["window-actions"]}>
  333. <div className={styles["window-action-button"]}>
  334. <IconButton
  335. icon={<ResetIcon />}
  336. onClick={resetConfig}
  337. bordered
  338. title="重置所有选项"
  339. />
  340. </div>
  341. </div>
  342. </div>
  343. <div className={styles["settings"]}>
  344. <List>
  345. <ListItem>
  346. <div className={styles["settings-title"]}>头像</div>
  347. <Popover
  348. onClose={() => setShowEmojiPicker(false)}
  349. content={
  350. <EmojiPicker
  351. lazyLoadEmojis
  352. theme={EmojiTheme.AUTO}
  353. onEmojiClick={(e) => {
  354. updateConfig((config) => (config.avatar = e.unified));
  355. setShowEmojiPicker(false);
  356. }}
  357. />
  358. }
  359. open={showEmojiPicker}
  360. >
  361. <div
  362. className={styles.avatar}
  363. onClick={() => setShowEmojiPicker(true)}
  364. >
  365. <Avatar role="user" />
  366. </div>
  367. </Popover>
  368. </ListItem>
  369. <ListItem>
  370. <div className={styles["settings-title"]}>发送键</div>
  371. <div className="">
  372. <select
  373. value={config.submitKey}
  374. onChange={(e) => {
  375. updateConfig(
  376. (config) =>
  377. (config.submitKey = e.target.value as any as SubmitKey)
  378. );
  379. }}
  380. >
  381. {Object.values(SubmitKey).map((v) => (
  382. <option value={v} key={v}>
  383. {v}
  384. </option>
  385. ))}
  386. </select>
  387. </div>
  388. </ListItem>
  389. <ListItem>
  390. <div className={styles["settings-title"]}>主题</div>
  391. <div className="">
  392. <select
  393. value={config.theme}
  394. onChange={(e) => {
  395. updateConfig(
  396. (config) => (config.theme = e.target.value as any as Theme)
  397. );
  398. }}
  399. >
  400. {Object.values(Theme).map((v) => (
  401. <option value={v} key={v}>
  402. {v}
  403. </option>
  404. ))}
  405. </select>
  406. </div>
  407. </ListItem>
  408. <ListItem>
  409. <div className={styles["settings-title"]}>紧凑边框</div>
  410. <input
  411. type="checkbox"
  412. checked={config.tightBorder}
  413. onChange={(e) =>
  414. updateConfig(
  415. (config) => (config.tightBorder = e.currentTarget.checked)
  416. )
  417. }
  418. ></input>
  419. </ListItem>
  420. </List>
  421. <List>
  422. <ListItem>
  423. <div className={styles["settings-title"]}>最大上下文消息数</div>
  424. <input
  425. type="range"
  426. title={config.historyMessageCount.toString()}
  427. value={config.historyMessageCount}
  428. min="5"
  429. max="20"
  430. step="5"
  431. onChange={(e) =>
  432. updateConfig(
  433. (config) =>
  434. (config.historyMessageCount = e.target.valueAsNumber)
  435. )
  436. }
  437. ></input>
  438. </ListItem>
  439. <ListItem>
  440. <div className={styles["settings-title"]}>
  441. 上下文中包含机器人消息
  442. </div>
  443. <input
  444. type="checkbox"
  445. checked={config.sendBotMessages}
  446. onChange={(e) =>
  447. updateConfig(
  448. (config) => (config.sendBotMessages = e.currentTarget.checked)
  449. )
  450. }
  451. ></input>
  452. </ListItem>
  453. </List>
  454. </div>
  455. </>
  456. );
  457. }