home.tsx 16 KB

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