home.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 Locale from '../locales'
  23. import dynamic from "next/dynamic";
  24. export function Loading(props: {
  25. noLogo?: boolean
  26. }) {
  27. return <div className={styles['loading-content']}>
  28. {!props.noLogo && <BotIcon />}
  29. <LoadingIcon />
  30. </div>
  31. }
  32. const Markdown = dynamic(async () => (await import('./markdown')).Markdown, {
  33. loading: () => <LoadingIcon />
  34. })
  35. const Settings = dynamic(async () => (await import('./settings')).Settings, {
  36. loading: () => <Loading noLogo />
  37. })
  38. const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, {
  39. loading: () => <LoadingIcon />
  40. })
  41. export function Avatar(props: { role: Message["role"] }) {
  42. const config = useChatStore((state) => state.config);
  43. if (props.role === "assistant") {
  44. return <BotIcon className={styles["user-avtar"]} />;
  45. }
  46. return (
  47. <div className={styles["user-avtar"]}>
  48. <Emoji unified={config.avatar} size={18} />
  49. </div>
  50. );
  51. }
  52. export function ChatItem(props: {
  53. onClick?: () => void;
  54. onDelete?: () => void;
  55. title: string;
  56. count: number;
  57. time: string;
  58. selected: boolean;
  59. }) {
  60. return (
  61. <div
  62. className={`${styles["chat-item"]} ${props.selected && styles["chat-item-selected"]
  63. }`}
  64. onClick={props.onClick}
  65. >
  66. <div className={styles["chat-item-title"]}>{props.title}</div>
  67. <div className={styles["chat-item-info"]}>
  68. <div className={styles["chat-item-count"]}>{Locale.ChatItem.ChatItemCount(props.count)}</div>
  69. <div className={styles["chat-item-date"]}>{props.time}</div>
  70. </div>
  71. <div className={styles["chat-item-delete"]} onClick={props.onDelete}>
  72. <DeleteIcon />
  73. </div>
  74. </div>
  75. );
  76. }
  77. export function ChatList() {
  78. const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
  79. (state) => [
  80. state.sessions,
  81. state.currentSessionIndex,
  82. state.selectSession,
  83. state.removeSession,
  84. ]
  85. );
  86. return (
  87. <div className={styles["chat-list"]}>
  88. {sessions.map((item, i) => (
  89. <ChatItem
  90. title={item.topic}
  91. time={item.lastUpdate}
  92. count={item.messages.length}
  93. key={i}
  94. selected={i === selectedIndex}
  95. onClick={() => selectSession(i)}
  96. onDelete={() => removeSession(i)}
  97. />
  98. ))}
  99. </div>
  100. );
  101. }
  102. function useSubmitHandler() {
  103. const config = useChatStore((state) => state.config);
  104. const submitKey = config.submitKey;
  105. const shouldSubmit = (e: KeyboardEvent) => {
  106. if (e.key !== "Enter") return false;
  107. return (
  108. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  109. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  110. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  111. config.submitKey === SubmitKey.Enter
  112. );
  113. };
  114. return {
  115. submitKey,
  116. shouldSubmit,
  117. };
  118. }
  119. export function Chat(props: { showSideBar?: () => void }) {
  120. type RenderMessage = Message & { preview?: boolean };
  121. const session = useChatStore((state) => state.currentSession());
  122. const [userInput, setUserInput] = useState("");
  123. const [isLoading, setIsLoading] = useState(false);
  124. const { submitKey, shouldSubmit } = useSubmitHandler();
  125. const onUserInput = useChatStore((state) => state.onUserInput);
  126. const onUserSubmit = () => {
  127. if (userInput.length <= 0) return;
  128. setIsLoading(true);
  129. onUserInput(userInput).then(() => setIsLoading(false));
  130. setUserInput("");
  131. };
  132. const onInputKeyDown = (e: KeyboardEvent) => {
  133. if (shouldSubmit(e)) {
  134. onUserSubmit();
  135. e.preventDefault();
  136. }
  137. };
  138. const latestMessageRef = useRef<HTMLDivElement>(null);
  139. const messages = (session.messages as RenderMessage[])
  140. .concat(
  141. isLoading
  142. ? [
  143. {
  144. role: "assistant",
  145. content: "……",
  146. date: new Date().toLocaleString(),
  147. preview: true,
  148. },
  149. ]
  150. : []
  151. )
  152. .concat(
  153. userInput.length > 0
  154. ? [
  155. {
  156. role: "user",
  157. content: userInput,
  158. date: new Date().toLocaleString(),
  159. preview: true,
  160. },
  161. ]
  162. : []
  163. );
  164. useEffect(() => {
  165. const dom = latestMessageRef.current
  166. if (dom && !isIOS()) {
  167. dom.scrollIntoView({
  168. behavior: "smooth",
  169. block: "end"
  170. });
  171. }
  172. });
  173. return (
  174. <div className={styles.chat} key={session.id}>
  175. <div className={styles["window-header"]}>
  176. <div className={styles["window-header-title"]}>
  177. <div className={styles["window-header-main-title"]}>{session.topic}</div>
  178. <div className={styles["window-header-sub-title"]}>
  179. {Locale.Chat.SubTitle(session.messages.length)}
  180. </div>
  181. </div>
  182. <div className={styles["window-actions"]}>
  183. <div className={styles["window-action-button"] + " " + styles.mobile}>
  184. <IconButton
  185. icon={<MenuIcon />}
  186. bordered
  187. title={Locale.Chat.Actions.ChatList}
  188. onClick={props?.showSideBar}
  189. />
  190. </div>
  191. <div className={styles["window-action-button"]}>
  192. <IconButton
  193. icon={<BrainIcon />}
  194. bordered
  195. title={Locale.Chat.Actions.CompressedHistory}
  196. onClick={() => {
  197. showMemoryPrompt(session)
  198. }}
  199. />
  200. </div>
  201. <div className={styles["window-action-button"]}>
  202. <IconButton
  203. icon={<ExportIcon />}
  204. bordered
  205. title={Locale.Chat.Actions.Export}
  206. onClick={() => {
  207. exportMessages(session.messages, session.topic)
  208. }}
  209. />
  210. </div>
  211. </div>
  212. </div>
  213. <div className={styles["chat-body"]}>
  214. {messages.map((message, i) => {
  215. const isUser = message.role === "user";
  216. return (
  217. <div
  218. key={i}
  219. className={
  220. isUser ? styles["chat-message-user"] : styles["chat-message"]
  221. }
  222. >
  223. <div className={styles["chat-message-container"]}>
  224. <div className={styles["chat-message-avatar"]}>
  225. <Avatar role={message.role} />
  226. </div>
  227. {(message.preview || message.streaming) && (
  228. <div className={styles["chat-message-status"]}>{Locale.Chat.Typing}</div>
  229. )}
  230. <div className={styles["chat-message-item"]}>
  231. {(message.preview || message.content.length === 0) &&
  232. !isUser ? (
  233. <LoadingIcon />
  234. ) : (
  235. <div className="markdown-body">
  236. <Markdown content={message.content} />
  237. </div>
  238. )}
  239. </div>
  240. {!isUser && !message.preview && (
  241. <div className={styles["chat-message-actions"]}>
  242. <div className={styles["chat-message-action-date"]}>
  243. {message.date.toLocaleString()}
  244. </div>
  245. </div>
  246. )}
  247. </div>
  248. </div>
  249. );
  250. })}
  251. <span ref={latestMessageRef} style={{ opacity: 0 }}>
  252. -
  253. </span>
  254. </div>
  255. <div className={styles["chat-input-panel"]}>
  256. <div className={styles["chat-input-panel-inner"]}>
  257. <textarea
  258. className={styles["chat-input"]}
  259. placeholder={Locale.Chat.Input(submitKey)}
  260. rows={3}
  261. onInput={(e) => setUserInput(e.currentTarget.value)}
  262. value={userInput}
  263. onKeyDown={(e) => onInputKeyDown(e as any)}
  264. />
  265. <IconButton
  266. icon={<SendWhiteIcon />}
  267. text={Locale.Chat.Send}
  268. className={styles["chat-input-send"] + " no-dark"}
  269. onClick={onUserSubmit}
  270. />
  271. </div>
  272. </div>
  273. </div>
  274. );
  275. }
  276. function useSwitchTheme() {
  277. const config = useChatStore((state) => state.config);
  278. useEffect(() => {
  279. document.body.classList.remove("light");
  280. document.body.classList.remove("dark");
  281. if (config.theme === "dark") {
  282. document.body.classList.add("dark");
  283. } else if (config.theme === "light") {
  284. document.body.classList.add("light");
  285. }
  286. }, [config.theme]);
  287. }
  288. function exportMessages(messages: Message[], topic: string) {
  289. const mdText = `# ${topic}\n\n` + messages.map(m => {
  290. return m.role === 'user' ? `## ${m.content}` : m.content.trim()
  291. }).join('\n\n')
  292. const filename = `${topic}.md`
  293. showModal({
  294. title: Locale.Export.Title, children: <div className="markdown-body">
  295. <pre className={styles['export-content']}>{mdText}</pre>
  296. </div>, actions: [
  297. <IconButton key="copy" icon={<CopyIcon />} bordered text={Locale.Export.Copy} onClick={() => copyToClipboard(mdText)} />,
  298. <IconButton key="download" icon={<DownloadIcon />} bordered text={Locale.Export.Download} onClick={() => downloadAs(mdText, filename)} />
  299. ]
  300. })
  301. }
  302. function showMemoryPrompt(session: ChatSession) {
  303. showModal({
  304. title: `${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`, children: <div className="markdown-body">
  305. <pre className={styles['export-content']}>{session.memoryPrompt || Locale.Memory.EmptyContent}</pre>
  306. </div>, actions: [
  307. <IconButton key="copy" icon={<CopyIcon />} bordered text={Locale.Memory.Copy} onClick={() => copyToClipboard(session.memoryPrompt)} />,
  308. ]
  309. })
  310. }
  311. export function Home() {
  312. const [createNewSession] = useChatStore((state) => [state.newSession]);
  313. const loading = !useChatStore?.persist?.hasHydrated();
  314. const [showSideBar, setShowSideBar] = useState(true);
  315. // setting
  316. const [openSettings, setOpenSettings] = useState(false);
  317. const config = useChatStore((state) => state.config);
  318. useSwitchTheme();
  319. if (loading) {
  320. return <Loading />;
  321. }
  322. return (
  323. <div
  324. className={`${config.tightBorder ? styles["tight-container"] : styles.container
  325. }`}
  326. >
  327. <div
  328. className={styles.sidebar + ` ${showSideBar && styles["sidebar-show"]}`}
  329. onClick={() => setShowSideBar(false)}
  330. >
  331. <div className={styles["sidebar-header"]}>
  332. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  333. <div className={styles["sidebar-sub-title"]}>
  334. Build your own AI assistant.
  335. </div>
  336. <div className={styles["sidebar-logo"]}>
  337. <ChatGptIcon />
  338. </div>
  339. </div>
  340. <div
  341. className={styles["sidebar-body"]}
  342. onClick={() => setOpenSettings(false)}
  343. >
  344. <ChatList />
  345. </div>
  346. <div className={styles["sidebar-tail"]}>
  347. <div className={styles["sidebar-actions"]}>
  348. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  349. <IconButton
  350. icon={<CloseIcon />}
  351. onClick={() => setShowSideBar(!showSideBar)}
  352. />
  353. </div>
  354. <div className={styles["sidebar-action"]}>
  355. <IconButton
  356. icon={<SettingsIcon />}
  357. onClick={() => setOpenSettings(!openSettings)}
  358. />
  359. </div>
  360. <div className={styles["sidebar-action"]}>
  361. <a href="https://github.com/Yidadaa" target="_blank">
  362. <IconButton icon={<GithubIcon />} />
  363. </a>
  364. </div>
  365. </div>
  366. <div>
  367. <IconButton
  368. icon={<AddIcon />}
  369. text={Locale.Home.NewChat}
  370. onClick={createNewSession}
  371. />
  372. </div>
  373. </div>
  374. </div>
  375. <div className={styles["window-content"]}>
  376. {openSettings ? (
  377. <Settings closeSettings={() => setOpenSettings(false)} />
  378. ) : (
  379. <Chat key="chat" showSideBar={() => setShowSideBar(true)} />
  380. )}
  381. </div>
  382. </div>
  383. );
  384. }