home.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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, showToast } 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 [hoveringMessage, setHoveringMessage] = useState(false);
  147. const messages = (session.messages as RenderMessage[])
  148. .concat(
  149. isLoading
  150. ? [
  151. {
  152. role: "assistant",
  153. content: "……",
  154. date: new Date().toLocaleString(),
  155. preview: true,
  156. },
  157. ]
  158. : []
  159. )
  160. .concat(
  161. userInput.length > 0
  162. ? [
  163. {
  164. role: "user",
  165. content: userInput,
  166. date: new Date().toLocaleString(),
  167. preview: true,
  168. },
  169. ]
  170. : []
  171. );
  172. useLayoutEffect(() => {
  173. setTimeout(() => {
  174. const dom = latestMessageRef.current;
  175. if (dom && !isIOS() && !hoveringMessage) {
  176. dom.scrollIntoView({
  177. behavior: "smooth",
  178. block: "end",
  179. });
  180. }
  181. }, 500);
  182. });
  183. return (
  184. <div className={styles.chat} key={session.id}>
  185. <div className={styles["window-header"]}>
  186. <div
  187. className={styles["window-header-title"]}
  188. onClick={props?.showSideBar}
  189. >
  190. <div className={styles["window-header-main-title"]}>
  191. {session.topic}
  192. </div>
  193. <div className={styles["window-header-sub-title"]}>
  194. {Locale.Chat.SubTitle(session.messages.length)}
  195. </div>
  196. </div>
  197. <div className={styles["window-actions"]}>
  198. <div className={styles["window-action-button"] + " " + styles.mobile}>
  199. <IconButton
  200. icon={<MenuIcon />}
  201. bordered
  202. title={Locale.Chat.Actions.ChatList}
  203. onClick={props?.showSideBar}
  204. />
  205. </div>
  206. <div className={styles["window-action-button"]}>
  207. <IconButton
  208. icon={<BrainIcon />}
  209. bordered
  210. title={Locale.Chat.Actions.CompressedHistory}
  211. onClick={() => {
  212. showMemoryPrompt(session);
  213. }}
  214. />
  215. </div>
  216. <div className={styles["window-action-button"]}>
  217. <IconButton
  218. icon={<ExportIcon />}
  219. bordered
  220. title={Locale.Chat.Actions.Export}
  221. onClick={() => {
  222. exportMessages(session.messages, session.topic);
  223. }}
  224. />
  225. </div>
  226. </div>
  227. </div>
  228. <div
  229. className={styles["chat-body"]}
  230. onMouseOver={() => {
  231. setHoveringMessage(true);
  232. }}
  233. onMouseOut={() => {
  234. setHoveringMessage(false);
  235. }}
  236. >
  237. {messages.map((message, i) => {
  238. const isUser = message.role === "user";
  239. return (
  240. <div
  241. key={i}
  242. className={
  243. isUser ? styles["chat-message-user"] : styles["chat-message"]
  244. }
  245. >
  246. <div className={styles["chat-message-container"]}>
  247. <div className={styles["chat-message-avatar"]}>
  248. <Avatar role={message.role} />
  249. </div>
  250. {(message.preview || message.streaming) && (
  251. <div className={styles["chat-message-status"]}>
  252. {Locale.Chat.Typing}
  253. </div>
  254. )}
  255. <div className={styles["chat-message-item"]}>
  256. {!isUser && (
  257. <div className={styles["chat-message-top-actions"]}>
  258. {message.streaming && (
  259. <div
  260. className={styles["chat-message-top-action"]}
  261. onClick={() => showToast(Locale.WIP)}
  262. >
  263. {Locale.Chat.Actions.Stop}
  264. </div>
  265. )}
  266. <div
  267. className={styles["chat-message-top-action"]}
  268. onClick={() => copyToClipboard(message.content)}
  269. >
  270. {Locale.Chat.Actions.Copy}
  271. </div>
  272. </div>
  273. )}
  274. {(message.preview || message.content.length === 0) &&
  275. !isUser ? (
  276. <LoadingIcon />
  277. ) : (
  278. <div
  279. className="markdown-body"
  280. onContextMenu={(e) => {
  281. if (selectOrCopy(e.currentTarget, message.content)) {
  282. e.preventDefault();
  283. }
  284. }}
  285. >
  286. <Markdown content={message.content} />
  287. </div>
  288. )}
  289. </div>
  290. {!isUser && !message.preview && (
  291. <div className={styles["chat-message-actions"]}>
  292. <div className={styles["chat-message-action-date"]}>
  293. {message.date.toLocaleString()}
  294. </div>
  295. </div>
  296. )}
  297. </div>
  298. </div>
  299. );
  300. })}
  301. <div ref={latestMessageRef} style={{ opacity: 0, height: "2em" }}>
  302. -
  303. </div>
  304. </div>
  305. <div className={styles["chat-input-panel"]}>
  306. <div className={styles["chat-input-panel-inner"]}>
  307. <textarea
  308. className={styles["chat-input"]}
  309. placeholder={Locale.Chat.Input(submitKey)}
  310. rows={3}
  311. onInput={(e) => setUserInput(e.currentTarget.value)}
  312. value={userInput}
  313. onKeyDown={(e) => onInputKeyDown(e as any)}
  314. />
  315. <IconButton
  316. icon={<SendWhiteIcon />}
  317. text={Locale.Chat.Send}
  318. className={styles["chat-input-send"] + " no-dark"}
  319. onClick={onUserSubmit}
  320. />
  321. </div>
  322. </div>
  323. </div>
  324. );
  325. }
  326. function useSwitchTheme() {
  327. const config = useChatStore((state) => state.config);
  328. useEffect(() => {
  329. document.body.classList.remove("light");
  330. document.body.classList.remove("dark");
  331. if (config.theme === "dark") {
  332. document.body.classList.add("dark");
  333. } else if (config.theme === "light") {
  334. document.body.classList.add("light");
  335. }
  336. }, [config.theme]);
  337. }
  338. function exportMessages(messages: Message[], topic: string) {
  339. const mdText =
  340. `# ${topic}\n\n` +
  341. messages
  342. .map((m) => {
  343. return m.role === "user" ? `## ${m.content}` : m.content.trim();
  344. })
  345. .join("\n\n");
  346. const filename = `${topic}.md`;
  347. showModal({
  348. title: Locale.Export.Title,
  349. children: (
  350. <div className="markdown-body">
  351. <pre className={styles["export-content"]}>{mdText}</pre>
  352. </div>
  353. ),
  354. actions: [
  355. <IconButton
  356. key="copy"
  357. icon={<CopyIcon />}
  358. bordered
  359. text={Locale.Export.Copy}
  360. onClick={() => copyToClipboard(mdText)}
  361. />,
  362. <IconButton
  363. key="download"
  364. icon={<DownloadIcon />}
  365. bordered
  366. text={Locale.Export.Download}
  367. onClick={() => downloadAs(mdText, filename)}
  368. />,
  369. ],
  370. });
  371. }
  372. function showMemoryPrompt(session: ChatSession) {
  373. showModal({
  374. title: `${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`,
  375. children: (
  376. <div className="markdown-body">
  377. <pre className={styles["export-content"]}>
  378. {session.memoryPrompt || Locale.Memory.EmptyContent}
  379. </pre>
  380. </div>
  381. ),
  382. actions: [
  383. <IconButton
  384. key="copy"
  385. icon={<CopyIcon />}
  386. bordered
  387. text={Locale.Memory.Copy}
  388. onClick={() => copyToClipboard(session.memoryPrompt)}
  389. />,
  390. ],
  391. });
  392. }
  393. export function Home() {
  394. const [createNewSession, currentIndex, removeSession] = useChatStore(
  395. (state) => [
  396. state.newSession,
  397. state.currentSessionIndex,
  398. state.removeSession,
  399. ]
  400. );
  401. const loading = !useChatStore?.persist?.hasHydrated();
  402. const [showSideBar, setShowSideBar] = useState(true);
  403. // setting
  404. const [openSettings, setOpenSettings] = useState(false);
  405. const config = useChatStore((state) => state.config);
  406. useSwitchTheme();
  407. if (loading) {
  408. return <Loading />;
  409. }
  410. return (
  411. <div
  412. className={`${
  413. config.tightBorder ? styles["tight-container"] : styles.container
  414. }`}
  415. >
  416. <div
  417. className={styles.sidebar + ` ${showSideBar && styles["sidebar-show"]}`}
  418. >
  419. <div className={styles["sidebar-header"]}>
  420. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  421. <div className={styles["sidebar-sub-title"]}>
  422. Build your own AI assistant.
  423. </div>
  424. <div className={styles["sidebar-logo"]}>
  425. <ChatGptIcon />
  426. </div>
  427. </div>
  428. <div
  429. className={styles["sidebar-body"]}
  430. onClick={() => {
  431. setOpenSettings(false);
  432. setShowSideBar(false);
  433. }}
  434. >
  435. <ChatList />
  436. </div>
  437. <div className={styles["sidebar-tail"]}>
  438. <div className={styles["sidebar-actions"]}>
  439. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  440. <IconButton
  441. icon={<CloseIcon />}
  442. onClick={() => {
  443. if (confirm(Locale.Home.DeleteChat)) {
  444. removeSession(currentIndex);
  445. }
  446. }}
  447. />
  448. </div>
  449. <div className={styles["sidebar-action"]}>
  450. <IconButton
  451. icon={<SettingsIcon />}
  452. onClick={() => {
  453. setOpenSettings(true);
  454. setShowSideBar(false);
  455. }}
  456. />
  457. </div>
  458. <div className={styles["sidebar-action"]}>
  459. <a href={REPO_URL} target="_blank">
  460. <IconButton icon={<GithubIcon />} />
  461. </a>
  462. </div>
  463. </div>
  464. <div>
  465. <IconButton
  466. icon={<AddIcon />}
  467. text={Locale.Home.NewChat}
  468. onClick={createNewSession}
  469. />
  470. </div>
  471. </div>
  472. </div>
  473. <div className={styles["window-content"]}>
  474. {openSettings ? (
  475. <Settings
  476. closeSettings={() => {
  477. setOpenSettings(false);
  478. setShowSideBar(true);
  479. }}
  480. />
  481. ) : (
  482. <Chat key="chat" showSideBar={() => setShowSideBar(true)} />
  483. )}
  484. </div>
  485. </div>
  486. );
  487. }