home.tsx 14 KB

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