home.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. "use client";
  2. import { useState, useRef, useEffect } from "react";
  3. import { IconButton } from "./button";
  4. import styles from "./home.module.scss";
  5. import SettingsIcon from "../icons/settings.svg";
  6. import GithubIcon from "../icons/github.svg";
  7. import ChatGptIcon from "../icons/chatgpt.svg";
  8. import SendWhiteIcon from "../icons/send-white.svg";
  9. import BrainIcon from "../icons/brain.svg";
  10. import ExportIcon from "../icons/export.svg";
  11. import BotIcon from "../icons/bot.svg";
  12. import AddIcon from "../icons/add.svg";
  13. import DeleteIcon from "../icons/delete.svg";
  14. import LoadingIcon from "../icons/three-dots.svg";
  15. import MenuIcon from "../icons/menu.svg";
  16. import CloseIcon from "../icons/close.svg";
  17. import CopyIcon from "../icons/copy.svg";
  18. import DownloadIcon from "../icons/download.svg";
  19. import { Message, SubmitKey, useChatStore, ChatSession } from "../store";
  20. import { showModal } from "./ui-lib";
  21. import { copyToClipboard, downloadAs, isIOS } from "../utils";
  22. import dynamic from "next/dynamic";
  23. export function Loading(props: {
  24. noLogo?: boolean
  25. }) {
  26. return <div className={styles['loading-content']}>
  27. {!props.noLogo && <BotIcon />}
  28. <LoadingIcon />
  29. </div>
  30. }
  31. const Markdown = dynamic(async () => (await import('./markdown')).Markdown, {
  32. loading: () => <LoadingIcon />
  33. })
  34. const Settings = dynamic(async () => (await import('./settings')).Settings, {
  35. loading: () => <Loading noLogo />
  36. })
  37. const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, {
  38. loading: () => <LoadingIcon />
  39. })
  40. export function Avatar(props: { role: Message["role"] }) {
  41. const config = useChatStore((state) => state.config);
  42. if (props.role === "assistant") {
  43. return <BotIcon className={styles["user-avtar"]} />;
  44. }
  45. return (
  46. <div className={styles["user-avtar"]}>
  47. <Emoji unified={config.avatar} size={18} />
  48. </div>
  49. );
  50. }
  51. export function ChatItem(props: {
  52. onClick?: () => void;
  53. onDelete?: () => void;
  54. title: string;
  55. count: number;
  56. time: string;
  57. selected: boolean;
  58. }) {
  59. return (
  60. <div
  61. className={`${styles["chat-item"]} ${props.selected && styles["chat-item-selected"]
  62. }`}
  63. onClick={props.onClick}
  64. >
  65. <div className={styles["chat-item-title"]}>{props.title}</div>
  66. <div className={styles["chat-item-info"]}>
  67. <div className={styles["chat-item-count"]}>{props.count} 条对话</div>
  68. <div className={styles["chat-item-date"]}>{props.time}</div>
  69. </div>
  70. <div className={styles["chat-item-delete"]} onClick={props.onDelete}>
  71. <DeleteIcon />
  72. </div>
  73. </div>
  74. );
  75. }
  76. export function ChatList() {
  77. const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
  78. (state) => [
  79. state.sessions,
  80. state.currentSessionIndex,
  81. state.selectSession,
  82. state.removeSession,
  83. ]
  84. );
  85. return (
  86. <div className={styles["chat-list"]}>
  87. {sessions.map((item, i) => (
  88. <ChatItem
  89. title={item.topic}
  90. time={item.lastUpdate}
  91. count={item.messages.length}
  92. key={i}
  93. selected={i === selectedIndex}
  94. onClick={() => selectSession(i)}
  95. onDelete={() => removeSession(i)}
  96. />
  97. ))}
  98. </div>
  99. );
  100. }
  101. function useSubmitHandler() {
  102. const config = useChatStore((state) => state.config);
  103. const submitKey = config.submitKey;
  104. const shouldSubmit = (e: KeyboardEvent) => {
  105. if (e.key !== "Enter") return false;
  106. return (
  107. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  108. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  109. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  110. config.submitKey === SubmitKey.Enter
  111. );
  112. };
  113. return {
  114. submitKey,
  115. shouldSubmit,
  116. };
  117. }
  118. export function Chat(props: { showSideBar?: () => void }) {
  119. type RenderMessage = Message & { preview?: boolean };
  120. const session = useChatStore((state) => state.currentSession());
  121. const [userInput, setUserInput] = useState("");
  122. const [isLoading, setIsLoading] = useState(false);
  123. const { submitKey, shouldSubmit } = useSubmitHandler();
  124. const onUserInput = useChatStore((state) => state.onUserInput);
  125. const onUserSubmit = () => {
  126. if (userInput.length <= 0) return;
  127. setIsLoading(true);
  128. onUserInput(userInput).then(() => setIsLoading(false));
  129. setUserInput("");
  130. };
  131. const onInputKeyDown = (e: KeyboardEvent) => {
  132. if (shouldSubmit(e)) {
  133. onUserSubmit();
  134. e.preventDefault();
  135. }
  136. };
  137. const latestMessageRef = useRef<HTMLDivElement>(null);
  138. const messages = (session.messages as RenderMessage[])
  139. .concat(
  140. isLoading
  141. ? [
  142. {
  143. role: "assistant",
  144. content: "……",
  145. date: new Date().toLocaleString(),
  146. preview: true,
  147. },
  148. ]
  149. : []
  150. )
  151. .concat(
  152. userInput.length > 0
  153. ? [
  154. {
  155. role: "user",
  156. content: userInput,
  157. date: new Date().toLocaleString(),
  158. preview: true,
  159. },
  160. ]
  161. : []
  162. );
  163. useEffect(() => {
  164. const dom = latestMessageRef.current
  165. if (dom && !isIOS()) {
  166. dom.scrollIntoView({
  167. behavior: "smooth",
  168. block: "end"
  169. });
  170. }
  171. });
  172. return (
  173. <div className={styles.chat} key={session.id}>
  174. <div className={styles["window-header"]}>
  175. <div className={styles["window-header-title"]}>
  176. <div className={styles["window-header-main-title"]}>{session.topic}</div>
  177. <div className={styles["window-header-sub-title"]}>
  178. 与 ChatGPT 的 {session.messages.length} 条对话
  179. </div>
  180. </div>
  181. <div className={styles["window-actions"]}>
  182. <div className={styles["window-action-button"] + " " + styles.mobile}>
  183. <IconButton
  184. icon={<MenuIcon />}
  185. bordered
  186. title="查看消息列表"
  187. onClick={props?.showSideBar}
  188. />
  189. </div>
  190. <div className={styles["window-action-button"]}>
  191. <IconButton
  192. icon={<BrainIcon />}
  193. bordered
  194. title="查看压缩后的历史 Prompt"
  195. onClick={() => {
  196. showMemoryPrompt(session)
  197. }}
  198. />
  199. </div>
  200. <div className={styles["window-action-button"]}>
  201. <IconButton
  202. icon={<ExportIcon />}
  203. bordered
  204. title="导出聊天记录"
  205. onClick={() => {
  206. exportMessages(session.messages, session.topic)
  207. }}
  208. />
  209. </div>
  210. </div>
  211. </div>
  212. <div className={styles["chat-body"]}>
  213. {messages.map((message, i) => {
  214. const isUser = message.role === "user";
  215. return (
  216. <div
  217. key={i}
  218. className={
  219. isUser ? styles["chat-message-user"] : styles["chat-message"]
  220. }
  221. >
  222. <div className={styles["chat-message-container"]}>
  223. <div className={styles["chat-message-avatar"]}>
  224. <Avatar role={message.role} />
  225. </div>
  226. {(message.preview || message.streaming) && (
  227. <div className={styles["chat-message-status"]}>正在输入…</div>
  228. )}
  229. <div className={styles["chat-message-item"]}>
  230. {(message.preview || message.content.length === 0) &&
  231. !isUser ? (
  232. <LoadingIcon />
  233. ) : (
  234. <div className="markdown-body">
  235. <Markdown content={message.content} />
  236. </div>
  237. )}
  238. </div>
  239. {!isUser && !message.preview && (
  240. <div className={styles["chat-message-actions"]}>
  241. <div className={styles["chat-message-action-date"]}>
  242. {message.date.toLocaleString()}
  243. </div>
  244. </div>
  245. )}
  246. </div>
  247. </div>
  248. );
  249. })}
  250. <span ref={latestMessageRef} style={{ opacity: 0 }}>
  251. -
  252. </span>
  253. </div>
  254. <div className={styles["chat-input-panel"]}>
  255. <div className={styles["chat-input-panel-inner"]}>
  256. <textarea
  257. className={styles["chat-input"]}
  258. placeholder={`输入消息,${submitKey} 发送`}
  259. rows={3}
  260. onInput={(e) => setUserInput(e.currentTarget.value)}
  261. value={userInput}
  262. onKeyDown={(e) => onInputKeyDown(e as any)}
  263. />
  264. <IconButton
  265. icon={<SendWhiteIcon />}
  266. text={"发送"}
  267. className={styles["chat-input-send"] + " no-dark"}
  268. onClick={onUserSubmit}
  269. />
  270. </div>
  271. </div>
  272. </div>
  273. );
  274. }
  275. function useSwitchTheme() {
  276. const config = useChatStore((state) => state.config);
  277. useEffect(() => {
  278. document.body.classList.remove("light");
  279. document.body.classList.remove("dark");
  280. if (config.theme === "dark") {
  281. document.body.classList.add("dark");
  282. } else if (config.theme === "light") {
  283. document.body.classList.add("light");
  284. }
  285. }, [config.theme]);
  286. }
  287. function exportMessages(messages: Message[], topic: string) {
  288. const mdText = `# ${topic}\n\n` + messages.map(m => {
  289. return m.role === 'user' ? `## ${m.content}` : m.content.trim()
  290. }).join('\n\n')
  291. const filename = `${topic}.md`
  292. showModal({
  293. title: "导出聊天记录为 Markdown", children: <div className="markdown-body">
  294. <pre className={styles['export-content']}>{mdText}</pre>
  295. </div>, actions: [
  296. <IconButton key="copy" icon={<CopyIcon />} bordered text="全部复制" onClick={() => copyToClipboard(mdText)} />,
  297. <IconButton key="download" icon={<DownloadIcon />} bordered text="下载文件" onClick={() => downloadAs(mdText, filename)} />
  298. ]
  299. })
  300. }
  301. function showMemoryPrompt(session: ChatSession) {
  302. showModal({
  303. title: `上下文记忆 Prompt (${session.lastSummarizeIndex} of ${session.messages.length})`, children: <div className="markdown-body">
  304. <pre className={styles['export-content']}>{session.memoryPrompt || '无'}</pre>
  305. </div>, actions: [
  306. <IconButton key="copy" icon={<CopyIcon />} bordered text="全部复制" onClick={() => copyToClipboard(session.memoryPrompt)} />,
  307. ]
  308. })
  309. }
  310. export function Home() {
  311. const [createNewSession] = useChatStore((state) => [state.newSession]);
  312. const loading = !useChatStore?.persist?.hasHydrated();
  313. const [showSideBar, setShowSideBar] = useState(true);
  314. // setting
  315. const [openSettings, setOpenSettings] = useState(false);
  316. const config = useChatStore((state) => state.config);
  317. useSwitchTheme();
  318. if (loading) {
  319. return <Loading />;
  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. }