home.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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.MetaEnter && e.metaKey) ||
  117. (config.submitKey === SubmitKey.Enter &&
  118. !e.altKey &&
  119. !e.ctrlKey &&
  120. !e.shiftKey &&
  121. !e.metaKey)
  122. );
  123. };
  124. return {
  125. submitKey,
  126. shouldSubmit,
  127. };
  128. }
  129. export function Chat(props: { showSideBar?: () => void }) {
  130. type RenderMessage = Message & { preview?: boolean };
  131. const [session, sessionIndex] = useChatStore((state) => [
  132. state.currentSession(),
  133. state.currentSessionIndex,
  134. ]);
  135. const [userInput, setUserInput] = useState("");
  136. const [isLoading, setIsLoading] = useState(false);
  137. const { submitKey, shouldSubmit } = useSubmitHandler();
  138. const onUserInput = useChatStore((state) => state.onUserInput);
  139. // submit user input
  140. const onUserSubmit = () => {
  141. if (userInput.length <= 0) return;
  142. setIsLoading(true);
  143. onUserInput(userInput).then(() => setIsLoading(false));
  144. setUserInput("");
  145. };
  146. // stop response
  147. const onUserStop = (messageIndex: number) => {
  148. console.log(ControllerPool, sessionIndex, messageIndex);
  149. ControllerPool.stop(sessionIndex, messageIndex);
  150. };
  151. // check if should send message
  152. const onInputKeyDown = (e: KeyboardEvent) => {
  153. if (shouldSubmit(e)) {
  154. onUserSubmit();
  155. e.preventDefault();
  156. }
  157. };
  158. const onRightClick = (e: any, message: Message) => {
  159. // auto fill user input
  160. if (message.role === "user") {
  161. setUserInput(message.content);
  162. }
  163. // copy to clipboard
  164. if (selectOrCopy(e.currentTarget, message.content)) {
  165. e.preventDefault();
  166. }
  167. };
  168. const onResend = (botIndex: number) => {
  169. // find last user input message and resend
  170. for (let i = botIndex; i >= 0; i -= 1) {
  171. if (messages[i].role === "user") {
  172. setIsLoading(true);
  173. onUserInput(messages[i].content).then(() => setIsLoading(false));
  174. return;
  175. }
  176. }
  177. };
  178. // for auto-scroll
  179. const latestMessageRef = useRef<HTMLDivElement>(null);
  180. const inputPanelRef = useRef<HTMLDivElement>(null);
  181. // wont scroll while hovering messages
  182. const [autoScroll, setAutoScroll] = useState(false);
  183. useEffect(() => {
  184. const handleMouseDown = (e: MouseEvent) => {
  185. // check if click on input panel
  186. setAutoScroll(
  187. !!inputPanelRef.current &&
  188. inputPanelRef.current.contains(e.target as HTMLElement)
  189. );
  190. };
  191. document.addEventListener("mousedown", handleMouseDown);
  192. return () => document.removeEventListener("mousedown", handleMouseDown);
  193. });
  194. // preview messages
  195. const messages = (session.messages as RenderMessage[])
  196. .concat(
  197. isLoading
  198. ? [
  199. {
  200. role: "assistant",
  201. content: "……",
  202. date: new Date().toLocaleString(),
  203. preview: true,
  204. },
  205. ]
  206. : []
  207. )
  208. .concat(
  209. userInput.length > 0
  210. ? [
  211. {
  212. role: "user",
  213. content: userInput,
  214. date: new Date().toLocaleString(),
  215. preview: true,
  216. },
  217. ]
  218. : []
  219. );
  220. // auto scroll
  221. useLayoutEffect(() => {
  222. setTimeout(() => {
  223. const dom = latestMessageRef.current;
  224. if (dom && !isIOS() && autoScroll) {
  225. dom.scrollIntoView({
  226. behavior: "smooth",
  227. block: "end",
  228. });
  229. }
  230. }, 500);
  231. });
  232. return (
  233. <div className={styles.chat} key={session.id}>
  234. <div className={styles["window-header"]}>
  235. <div
  236. className={styles["window-header-title"]}
  237. onClick={props?.showSideBar}
  238. >
  239. <div className={styles["window-header-main-title"]}>
  240. {session.topic}
  241. </div>
  242. <div className={styles["window-header-sub-title"]}>
  243. {Locale.Chat.SubTitle(session.messages.length)}
  244. </div>
  245. </div>
  246. <div className={styles["window-actions"]}>
  247. <div className={styles["window-action-button"] + " " + styles.mobile}>
  248. <IconButton
  249. icon={<MenuIcon />}
  250. bordered
  251. title={Locale.Chat.Actions.ChatList}
  252. onClick={props?.showSideBar}
  253. />
  254. </div>
  255. <div className={styles["window-action-button"]}>
  256. <IconButton
  257. icon={<BrainIcon />}
  258. bordered
  259. title={Locale.Chat.Actions.CompressedHistory}
  260. onClick={() => {
  261. showMemoryPrompt(session);
  262. }}
  263. />
  264. </div>
  265. <div className={styles["window-action-button"]}>
  266. <IconButton
  267. icon={<ExportIcon />}
  268. bordered
  269. title={Locale.Chat.Actions.Export}
  270. onClick={() => {
  271. exportMessages(session.messages, session.topic);
  272. }}
  273. />
  274. </div>
  275. </div>
  276. </div>
  277. <div className={styles["chat-body"]}>
  278. {messages.map((message, i) => {
  279. const isUser = message.role === "user";
  280. return (
  281. <div
  282. key={i}
  283. className={
  284. isUser ? styles["chat-message-user"] : styles["chat-message"]
  285. }
  286. >
  287. <div className={styles["chat-message-container"]}>
  288. <div className={styles["chat-message-avatar"]}>
  289. <Avatar role={message.role} />
  290. </div>
  291. {(message.preview || message.streaming) && (
  292. <div className={styles["chat-message-status"]}>
  293. {Locale.Chat.Typing}
  294. </div>
  295. )}
  296. <div className={styles["chat-message-item"]}>
  297. {!isUser && (
  298. <div className={styles["chat-message-top-actions"]}>
  299. {message.streaming ? (
  300. <div
  301. className={styles["chat-message-top-action"]}
  302. onClick={() => onUserStop(i)}
  303. >
  304. {Locale.Chat.Actions.Stop}
  305. </div>
  306. ) : (
  307. <div
  308. className={styles["chat-message-top-action"]}
  309. onClick={() => onResend(i)}
  310. >
  311. {Locale.Chat.Actions.Retry}
  312. </div>
  313. )}
  314. <div
  315. className={styles["chat-message-top-action"]}
  316. onClick={() => copyToClipboard(message.content)}
  317. >
  318. {Locale.Chat.Actions.Copy}
  319. </div>
  320. </div>
  321. )}
  322. {(message.preview || message.content.length === 0) &&
  323. !isUser ? (
  324. <LoadingIcon />
  325. ) : (
  326. <div
  327. className="markdown-body"
  328. onContextMenu={(e) => onRightClick(e, message)}
  329. >
  330. <Markdown content={message.content} />
  331. </div>
  332. )}
  333. </div>
  334. {!isUser && !message.preview && (
  335. <div className={styles["chat-message-actions"]}>
  336. <div className={styles["chat-message-action-date"]}>
  337. {message.date.toLocaleString()}
  338. </div>
  339. </div>
  340. )}
  341. </div>
  342. </div>
  343. );
  344. })}
  345. <div ref={latestMessageRef} style={{ opacity: 0, height: "2em" }}>
  346. -
  347. </div>
  348. </div>
  349. <div className={styles["chat-input-panel"]} ref={inputPanelRef}>
  350. <div className={styles["chat-input-panel-inner"]}>
  351. <textarea
  352. className={styles["chat-input"]}
  353. placeholder={Locale.Chat.Input(submitKey)}
  354. rows={3}
  355. onInput={(e) => setUserInput(e.currentTarget.value)}
  356. value={userInput}
  357. onKeyDown={(e) => onInputKeyDown(e as any)}
  358. autoFocus
  359. />
  360. <IconButton
  361. icon={<SendWhiteIcon />}
  362. text={Locale.Chat.Send}
  363. className={styles["chat-input-send"] + " no-dark"}
  364. onClick={onUserSubmit}
  365. />
  366. </div>
  367. </div>
  368. </div>
  369. );
  370. }
  371. function useSwitchTheme() {
  372. const config = useChatStore((state) => state.config);
  373. useEffect(() => {
  374. document.body.classList.remove("light");
  375. document.body.classList.remove("dark");
  376. if (config.theme === "dark") {
  377. document.body.classList.add("dark");
  378. } else if (config.theme === "light") {
  379. document.body.classList.add("light");
  380. }
  381. const themeColor = getComputedStyle(document.body).getPropertyValue("--theme-color").trim();
  382. const metaDescription = document.querySelector('meta[name="theme-color"]');
  383. metaDescription?.setAttribute('content', themeColor);
  384. }, [config.theme]);
  385. }
  386. function exportMessages(messages: Message[], topic: string) {
  387. const mdText =
  388. `# ${topic}\n\n` +
  389. messages
  390. .map((m) => {
  391. return m.role === "user" ? `## ${m.content}` : m.content.trim();
  392. })
  393. .join("\n\n");
  394. const filename = `${topic}.md`;
  395. showModal({
  396. title: Locale.Export.Title,
  397. children: (
  398. <div className="markdown-body">
  399. <pre className={styles["export-content"]}>{mdText}</pre>
  400. </div>
  401. ),
  402. actions: [
  403. <IconButton
  404. key="copy"
  405. icon={<CopyIcon />}
  406. bordered
  407. text={Locale.Export.Copy}
  408. onClick={() => copyToClipboard(mdText)}
  409. />,
  410. <IconButton
  411. key="download"
  412. icon={<DownloadIcon />}
  413. bordered
  414. text={Locale.Export.Download}
  415. onClick={() => downloadAs(mdText, filename)}
  416. />,
  417. ],
  418. });
  419. }
  420. function showMemoryPrompt(session: ChatSession) {
  421. showModal({
  422. title: `${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`,
  423. children: (
  424. <div className="markdown-body">
  425. <pre className={styles["export-content"]}>
  426. {session.memoryPrompt || Locale.Memory.EmptyContent}
  427. </pre>
  428. </div>
  429. ),
  430. actions: [
  431. <IconButton
  432. key="copy"
  433. icon={<CopyIcon />}
  434. bordered
  435. text={Locale.Memory.Copy}
  436. onClick={() => copyToClipboard(session.memoryPrompt)}
  437. />,
  438. ],
  439. });
  440. }
  441. const useHasHydrated = () => {
  442. const [hasHydrated, setHasHydrated] = useState<boolean>(false);
  443. useEffect(() => {
  444. setHasHydrated(true);
  445. }, []);
  446. return hasHydrated;
  447. };
  448. export function Home() {
  449. const [createNewSession, currentIndex, removeSession] = useChatStore(
  450. (state) => [
  451. state.newSession,
  452. state.currentSessionIndex,
  453. state.removeSession,
  454. ]
  455. );
  456. const loading = !useHasHydrated();
  457. const [showSideBar, setShowSideBar] = useState(true);
  458. // setting
  459. const [openSettings, setOpenSettings] = useState(false);
  460. const config = useChatStore((state) => state.config);
  461. useSwitchTheme();
  462. if (loading) {
  463. return <Loading />;
  464. }
  465. return (
  466. <div
  467. className={`${
  468. config.tightBorder ? styles["tight-container"] : styles.container
  469. }`}
  470. >
  471. <div
  472. className={styles.sidebar + ` ${showSideBar && styles["sidebar-show"]}`}
  473. >
  474. <div className={styles["sidebar-header"]}>
  475. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  476. <div className={styles["sidebar-sub-title"]}>
  477. Build your own AI assistant.
  478. </div>
  479. <div className={styles["sidebar-logo"]}>
  480. <ChatGptIcon />
  481. </div>
  482. </div>
  483. <div
  484. className={styles["sidebar-body"]}
  485. onClick={() => {
  486. setOpenSettings(false);
  487. setShowSideBar(false);
  488. }}
  489. >
  490. <ChatList />
  491. </div>
  492. <div className={styles["sidebar-tail"]}>
  493. <div className={styles["sidebar-actions"]}>
  494. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  495. <IconButton
  496. icon={<CloseIcon />}
  497. onClick={() => {
  498. if (confirm(Locale.Home.DeleteChat)) {
  499. removeSession(currentIndex);
  500. }
  501. }}
  502. />
  503. </div>
  504. <div className={styles["sidebar-action"]}>
  505. <IconButton
  506. icon={<SettingsIcon />}
  507. onClick={() => {
  508. setOpenSettings(true);
  509. setShowSideBar(false);
  510. }}
  511. />
  512. </div>
  513. <div className={styles["sidebar-action"]}>
  514. <a href={REPO_URL} target="_blank">
  515. <IconButton icon={<GithubIcon />} />
  516. </a>
  517. </div>
  518. </div>
  519. <div>
  520. <IconButton
  521. icon={<AddIcon />}
  522. text={Locale.Home.NewChat}
  523. onClick={()=>{
  524. createNewSession();
  525. setShowSideBar(false);
  526. }}
  527. />
  528. </div>
  529. </div>
  530. </div>
  531. <div className={styles["window-content"]}>
  532. {openSettings ? (
  533. <Settings
  534. closeSettings={() => {
  535. setOpenSettings(false);
  536. setShowSideBar(true);
  537. }}
  538. />
  539. ) : (
  540. <Chat key="chat" showSideBar={() => setShowSideBar(true)} />
  541. )}
  542. </div>
  543. </div>
  544. );
  545. }