home.tsx 17 KB

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