home.tsx 17 KB

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