home.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. "use client";
  2. import { useState, useRef, useEffect, useLayoutEffect } from "react";
  3. import { useDebouncedCallback } from "use-debounce";
  4. import { IconButton } from "./button";
  5. import styles from "./home.module.scss";
  6. import SettingsIcon from "../icons/settings.svg";
  7. import GithubIcon from "../icons/github.svg";
  8. import ChatGptIcon from "../icons/chatgpt.svg";
  9. import SendWhiteIcon from "../icons/send-white.svg";
  10. import BrainIcon from "../icons/brain.svg";
  11. import ExportIcon from "../icons/export.svg";
  12. import BotIcon from "../icons/bot.svg";
  13. import AddIcon from "../icons/add.svg";
  14. import DeleteIcon from "../icons/delete.svg";
  15. import LoadingIcon from "../icons/three-dots.svg";
  16. import MenuIcon from "../icons/menu.svg";
  17. import CloseIcon from "../icons/close.svg";
  18. import CopyIcon from "../icons/copy.svg";
  19. import DownloadIcon from "../icons/download.svg";
  20. import { Message, SubmitKey, useChatStore, ChatSession } from "../store";
  21. import { showModal, showToast } from "./ui-lib";
  22. import {
  23. copyToClipboard,
  24. downloadAs,
  25. isIOS,
  26. isMobileScreen,
  27. selectOrCopy,
  28. } from "../utils";
  29. import Locale from "../locales";
  30. import dynamic from "next/dynamic";
  31. import { REPO_URL } from "../constant";
  32. import { ControllerPool } from "../requests";
  33. import { Prompt, usePromptStore } from "../store/prompt";
  34. export function Loading(props: { noLogo?: boolean }) {
  35. return (
  36. <div className={styles["loading-content"]}>
  37. {!props.noLogo && <BotIcon />}
  38. <LoadingIcon />
  39. </div>
  40. );
  41. }
  42. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  43. loading: () => <LoadingIcon />,
  44. });
  45. const Settings = dynamic(async () => (await import("./settings")).Settings, {
  46. loading: () => <Loading noLogo />,
  47. });
  48. const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, {
  49. loading: () => <LoadingIcon />,
  50. });
  51. export function Avatar(props: { role: Message["role"] }) {
  52. const config = useChatStore((state) => state.config);
  53. if (props.role === "assistant") {
  54. return <BotIcon className={styles["user-avtar"]} />;
  55. }
  56. return (
  57. <div className={styles["user-avtar"]}>
  58. <Emoji unified={config.avatar} size={18} />
  59. </div>
  60. );
  61. }
  62. export function ChatItem(props: {
  63. onClick?: () => void;
  64. onDelete?: () => void;
  65. title: string;
  66. count: number;
  67. time: string;
  68. selected: boolean;
  69. }) {
  70. return (
  71. <div
  72. className={`${styles["chat-item"]} ${
  73. props.selected && styles["chat-item-selected"]
  74. }`}
  75. onClick={props.onClick}
  76. >
  77. <div className={styles["chat-item-title"]}>{props.title}</div>
  78. <div className={styles["chat-item-info"]}>
  79. <div className={styles["chat-item-count"]}>
  80. {Locale.ChatItem.ChatItemCount(props.count)}
  81. </div>
  82. <div className={styles["chat-item-date"]}>{props.time}</div>
  83. </div>
  84. <div className={styles["chat-item-delete"]} onClick={props.onDelete}>
  85. <DeleteIcon />
  86. </div>
  87. </div>
  88. );
  89. }
  90. export function ChatList() {
  91. const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
  92. (state) => [
  93. state.sessions,
  94. state.currentSessionIndex,
  95. state.selectSession,
  96. state.removeSession,
  97. ],
  98. );
  99. return (
  100. <div className={styles["chat-list"]}>
  101. {sessions.map((item, i) => (
  102. <ChatItem
  103. title={item.topic}
  104. time={item.lastUpdate}
  105. count={item.messages.length}
  106. key={i}
  107. selected={i === selectedIndex}
  108. onClick={() => selectSession(i)}
  109. onDelete={() => confirm(Locale.Home.DeleteChat) && removeSession(i)}
  110. />
  111. ))}
  112. </div>
  113. );
  114. }
  115. function useSubmitHandler() {
  116. const config = useChatStore((state) => state.config);
  117. const submitKey = config.submitKey;
  118. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  119. if (e.key !== "Enter") return false;
  120. if (e.key === "Enter" && e.nativeEvent.isComposing) return false;
  121. return (
  122. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  123. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  124. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  125. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  126. (config.submitKey === SubmitKey.Enter &&
  127. !e.altKey &&
  128. !e.ctrlKey &&
  129. !e.shiftKey &&
  130. !e.metaKey)
  131. );
  132. };
  133. return {
  134. submitKey,
  135. shouldSubmit,
  136. };
  137. }
  138. export function PromptHints(props: {
  139. prompts: Prompt[];
  140. onPromptSelect: (prompt: Prompt) => void;
  141. }) {
  142. if (props.prompts.length === 0) return null;
  143. return (
  144. <div className={styles["prompt-hints"]}>
  145. {props.prompts.map((prompt, i) => (
  146. <div
  147. className={styles["prompt-hint"]}
  148. key={prompt.title + i.toString()}
  149. onClick={() => props.onPromptSelect(prompt)}
  150. >
  151. <div className={styles["hint-title"]}>{prompt.title}</div>
  152. <div className={styles["hint-content"]}>{prompt.content}</div>
  153. </div>
  154. ))}
  155. </div>
  156. );
  157. }
  158. export function Chat(props: {
  159. showSideBar?: () => void;
  160. sideBarShowing?: boolean;
  161. }) {
  162. type RenderMessage = Message & { preview?: boolean };
  163. const chatStore = useChatStore();
  164. const [session, sessionIndex] = useChatStore((state) => [
  165. state.currentSession(),
  166. state.currentSessionIndex,
  167. ]);
  168. const fontSize = useChatStore((state) => state.config.fontSize);
  169. const inputRef = useRef<HTMLTextAreaElement>(null);
  170. const [userInput, setUserInput] = useState("");
  171. const [isLoading, setIsLoading] = useState(false);
  172. const { submitKey, shouldSubmit } = useSubmitHandler();
  173. // prompt hints
  174. const promptStore = usePromptStore();
  175. const [promptHints, setPromptHints] = useState<Prompt[]>([]);
  176. const onSearch = useDebouncedCallback(
  177. (text: string) => {
  178. setPromptHints(promptStore.search(text));
  179. },
  180. 100,
  181. { leading: true, trailing: true },
  182. );
  183. const onPromptSelect = (prompt: Prompt) => {
  184. setUserInput(prompt.content);
  185. setPromptHints([]);
  186. inputRef.current?.focus();
  187. };
  188. const scrollInput = () => {
  189. const dom = inputRef.current;
  190. if (!dom) return;
  191. const paddingBottomNum: number = parseInt(
  192. window.getComputedStyle(dom).paddingBottom,
  193. 10,
  194. );
  195. dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
  196. };
  197. // only search prompts when user input is short
  198. const SEARCH_TEXT_LIMIT = 30;
  199. const onInput = (text: string) => {
  200. scrollInput();
  201. setUserInput(text);
  202. const n = text.trim().length;
  203. // clear search results
  204. if (n === 0) {
  205. setPromptHints([]);
  206. } else if (!chatStore.config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  207. // check if need to trigger auto completion
  208. if (text.startsWith("/") && text.length > 1) {
  209. onSearch(text.slice(1));
  210. }
  211. }
  212. };
  213. // submit user input
  214. const onUserSubmit = () => {
  215. if (userInput.length <= 0) return;
  216. setIsLoading(true);
  217. chatStore.onUserInput(userInput).then(() => setIsLoading(false));
  218. setUserInput("");
  219. setPromptHints([]);
  220. inputRef.current?.focus();
  221. };
  222. // stop response
  223. const onUserStop = (messageIndex: number) => {
  224. console.log(ControllerPool, sessionIndex, messageIndex);
  225. ControllerPool.stop(sessionIndex, messageIndex);
  226. };
  227. // check if should send message
  228. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  229. if (shouldSubmit(e)) {
  230. onUserSubmit();
  231. e.preventDefault();
  232. }
  233. };
  234. const onRightClick = (e: any, message: Message) => {
  235. // auto fill user input
  236. if (message.role === "user") {
  237. setUserInput(message.content);
  238. }
  239. // copy to clipboard
  240. if (selectOrCopy(e.currentTarget, message.content)) {
  241. e.preventDefault();
  242. }
  243. };
  244. const onResend = (botIndex: number) => {
  245. // find last user input message and resend
  246. for (let i = botIndex; i >= 0; i -= 1) {
  247. if (messages[i].role === "user") {
  248. setIsLoading(true);
  249. chatStore
  250. .onUserInput(messages[i].content)
  251. .then(() => setIsLoading(false));
  252. inputRef.current?.focus();
  253. return;
  254. }
  255. }
  256. };
  257. // for auto-scroll
  258. const latestMessageRef = useRef<HTMLDivElement>(null);
  259. const [autoScroll, setAutoScroll] = useState(true);
  260. // preview messages
  261. const messages = (session.messages as RenderMessage[])
  262. .concat(
  263. isLoading
  264. ? [
  265. {
  266. role: "assistant",
  267. content: "……",
  268. date: new Date().toLocaleString(),
  269. preview: true,
  270. },
  271. ]
  272. : [],
  273. )
  274. .concat(
  275. userInput.length > 0
  276. ? [
  277. {
  278. role: "user",
  279. content: userInput,
  280. date: new Date().toLocaleString(),
  281. preview: true,
  282. },
  283. ]
  284. : [],
  285. );
  286. // auto scroll
  287. useLayoutEffect(() => {
  288. setTimeout(() => {
  289. const dom = latestMessageRef.current;
  290. const inputDom = inputRef.current;
  291. // only scroll when input overlaped message body
  292. let shouldScroll = true;
  293. if (dom && inputDom) {
  294. const domRect = dom.getBoundingClientRect();
  295. const inputRect = inputDom.getBoundingClientRect();
  296. shouldScroll = domRect.top > inputRect.top;
  297. }
  298. if (dom && autoScroll && shouldScroll) {
  299. dom.scrollIntoView({
  300. block: "end",
  301. });
  302. }
  303. }, 500);
  304. });
  305. return (
  306. <div className={styles.chat} key={session.id}>
  307. <div className={styles["window-header"]}>
  308. <div
  309. className={styles["window-header-title"]}
  310. onClick={props?.showSideBar}
  311. >
  312. <div
  313. className={`${styles["window-header-main-title"]} ${styles["chat-body-title"]}`}
  314. onClick={() => {
  315. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  316. if (newTopic && newTopic !== session.topic) {
  317. chatStore.updateCurrentSession(
  318. (session) => (session.topic = newTopic!),
  319. );
  320. }
  321. }}
  322. >
  323. {session.topic}
  324. </div>
  325. <div className={styles["window-header-sub-title"]}>
  326. {Locale.Chat.SubTitle(session.messages.length)}
  327. </div>
  328. </div>
  329. <div className={styles["window-actions"]}>
  330. <div className={styles["window-action-button"] + " " + styles.mobile}>
  331. <IconButton
  332. icon={<MenuIcon />}
  333. bordered
  334. title={Locale.Chat.Actions.ChatList}
  335. onClick={props?.showSideBar}
  336. />
  337. </div>
  338. <div className={styles["window-action-button"]}>
  339. <IconButton
  340. icon={<BrainIcon />}
  341. bordered
  342. title={Locale.Chat.Actions.CompressedHistory}
  343. onClick={() => {
  344. showMemoryPrompt(session);
  345. }}
  346. />
  347. </div>
  348. <div className={styles["window-action-button"]}>
  349. <IconButton
  350. icon={<ExportIcon />}
  351. bordered
  352. title={Locale.Chat.Actions.Export}
  353. onClick={() => {
  354. exportMessages(session.messages, session.topic);
  355. }}
  356. />
  357. </div>
  358. </div>
  359. </div>
  360. <div className={styles["chat-body"]}>
  361. {messages.map((message, i) => {
  362. const isUser = message.role === "user";
  363. return (
  364. <div
  365. key={i}
  366. className={
  367. isUser ? styles["chat-message-user"] : styles["chat-message"]
  368. }
  369. >
  370. <div className={styles["chat-message-container"]}>
  371. <div className={styles["chat-message-avatar"]}>
  372. <Avatar role={message.role} />
  373. </div>
  374. {(message.preview || message.streaming) && (
  375. <div className={styles["chat-message-status"]}>
  376. {Locale.Chat.Typing}
  377. </div>
  378. )}
  379. <div className={styles["chat-message-item"]}>
  380. {!isUser &&
  381. !(message.preview || message.content.length === 0) && (
  382. <div className={styles["chat-message-top-actions"]}>
  383. {message.streaming ? (
  384. <div
  385. className={styles["chat-message-top-action"]}
  386. onClick={() => onUserStop(i)}
  387. >
  388. {Locale.Chat.Actions.Stop}
  389. </div>
  390. ) : (
  391. <div
  392. className={styles["chat-message-top-action"]}
  393. onClick={() => onResend(i)}
  394. >
  395. {Locale.Chat.Actions.Retry}
  396. </div>
  397. )}
  398. <div
  399. className={styles["chat-message-top-action"]}
  400. onClick={() => copyToClipboard(message.content)}
  401. >
  402. {Locale.Chat.Actions.Copy}
  403. </div>
  404. </div>
  405. )}
  406. {(message.preview || message.content.length === 0) &&
  407. !isUser ? (
  408. <LoadingIcon />
  409. ) : (
  410. <div
  411. className="markdown-body"
  412. style={{ fontSize: `${fontSize}px` }}
  413. onContextMenu={(e) => onRightClick(e, message)}
  414. onDoubleClickCapture={() => {
  415. if (!isMobileScreen()) return;
  416. setUserInput(message.content);
  417. }}
  418. >
  419. <Markdown content={message.content} />
  420. </div>
  421. )}
  422. </div>
  423. {!isUser && !message.preview && (
  424. <div className={styles["chat-message-actions"]}>
  425. <div className={styles["chat-message-action-date"]}>
  426. {message.date.toLocaleString()}
  427. </div>
  428. </div>
  429. )}
  430. </div>
  431. </div>
  432. );
  433. })}
  434. <div ref={latestMessageRef} style={{ opacity: 0, height: "1px" }}>
  435. -
  436. </div>
  437. </div>
  438. <div className={styles["chat-input-panel"]}>
  439. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  440. <div className={styles["chat-input-panel-inner"]}>
  441. <textarea
  442. ref={inputRef}
  443. className={styles["chat-input"]}
  444. placeholder={Locale.Chat.Input(submitKey)}
  445. rows={4}
  446. onInput={(e) => onInput(e.currentTarget.value)}
  447. value={userInput}
  448. onKeyDown={onInputKeyDown}
  449. onFocus={() => setAutoScroll(true)}
  450. onBlur={() => {
  451. setAutoScroll(false);
  452. setTimeout(() => setPromptHints([]), 500);
  453. }}
  454. autoFocus={!props?.sideBarShowing}
  455. />
  456. <IconButton
  457. icon={<SendWhiteIcon />}
  458. text={Locale.Chat.Send}
  459. className={styles["chat-input-send"] + " no-dark"}
  460. onClick={onUserSubmit}
  461. />
  462. </div>
  463. </div>
  464. </div>
  465. );
  466. }
  467. function useSwitchTheme() {
  468. const config = useChatStore((state) => state.config);
  469. useEffect(() => {
  470. document.body.classList.remove("light");
  471. document.body.classList.remove("dark");
  472. if (config.theme === "dark") {
  473. document.body.classList.add("dark");
  474. } else if (config.theme === "light") {
  475. document.body.classList.add("light");
  476. }
  477. const themeColor = getComputedStyle(document.body)
  478. .getPropertyValue("--theme-color")
  479. .trim();
  480. const metaDescription = document.querySelector('meta[name="theme-color"]');
  481. metaDescription?.setAttribute("content", themeColor);
  482. }, [config.theme]);
  483. }
  484. function exportMessages(messages: Message[], topic: string) {
  485. const mdText =
  486. `# ${topic}\n\n` +
  487. messages
  488. .map((m) => {
  489. return m.role === "user" ? `## ${m.content}` : m.content.trim();
  490. })
  491. .join("\n\n");
  492. const filename = `${topic}.md`;
  493. showModal({
  494. title: Locale.Export.Title,
  495. children: (
  496. <div className="markdown-body">
  497. <pre className={styles["export-content"]}>{mdText}</pre>
  498. </div>
  499. ),
  500. actions: [
  501. <IconButton
  502. key="copy"
  503. icon={<CopyIcon />}
  504. bordered
  505. text={Locale.Export.Copy}
  506. onClick={() => copyToClipboard(mdText)}
  507. />,
  508. <IconButton
  509. key="download"
  510. icon={<DownloadIcon />}
  511. bordered
  512. text={Locale.Export.Download}
  513. onClick={() => downloadAs(mdText, filename)}
  514. />,
  515. ],
  516. });
  517. }
  518. function showMemoryPrompt(session: ChatSession) {
  519. showModal({
  520. title: `${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`,
  521. children: (
  522. <div className="markdown-body">
  523. <pre className={styles["export-content"]}>
  524. {session.memoryPrompt || Locale.Memory.EmptyContent}
  525. </pre>
  526. </div>
  527. ),
  528. actions: [
  529. <IconButton
  530. key="copy"
  531. icon={<CopyIcon />}
  532. bordered
  533. text={Locale.Memory.Copy}
  534. onClick={() => copyToClipboard(session.memoryPrompt)}
  535. />,
  536. ],
  537. });
  538. }
  539. const useHasHydrated = () => {
  540. const [hasHydrated, setHasHydrated] = useState<boolean>(false);
  541. useEffect(() => {
  542. setHasHydrated(true);
  543. }, []);
  544. return hasHydrated;
  545. };
  546. export function Home() {
  547. const [createNewSession, currentIndex, removeSession] = useChatStore(
  548. (state) => [
  549. state.newSession,
  550. state.currentSessionIndex,
  551. state.removeSession,
  552. ],
  553. );
  554. const loading = !useHasHydrated();
  555. const [showSideBar, setShowSideBar] = useState(true);
  556. // setting
  557. const [openSettings, setOpenSettings] = useState(false);
  558. const config = useChatStore((state) => state.config);
  559. useSwitchTheme();
  560. if (loading) {
  561. return <Loading />;
  562. }
  563. return (
  564. <div
  565. className={`${
  566. config.tightBorder && !isMobileScreen()
  567. ? styles["tight-container"]
  568. : styles.container
  569. }`}
  570. >
  571. <div
  572. className={styles.sidebar + ` ${showSideBar && styles["sidebar-show"]}`}
  573. >
  574. <div className={styles["sidebar-header"]}>
  575. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  576. <div className={styles["sidebar-sub-title"]}>
  577. Build your own AI assistant.
  578. </div>
  579. <div className={styles["sidebar-logo"]}>
  580. <ChatGptIcon />
  581. </div>
  582. </div>
  583. <div
  584. className={styles["sidebar-body"]}
  585. onClick={() => {
  586. setOpenSettings(false);
  587. setShowSideBar(false);
  588. }}
  589. >
  590. <ChatList />
  591. </div>
  592. <div className={styles["sidebar-tail"]}>
  593. <div className={styles["sidebar-actions"]}>
  594. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  595. <IconButton
  596. icon={<CloseIcon />}
  597. onClick={() => {
  598. if (confirm(Locale.Home.DeleteChat)) {
  599. removeSession(currentIndex);
  600. }
  601. }}
  602. />
  603. </div>
  604. <div className={styles["sidebar-action"]}>
  605. <IconButton
  606. icon={<SettingsIcon />}
  607. onClick={() => {
  608. setOpenSettings(true);
  609. setShowSideBar(false);
  610. }}
  611. />
  612. </div>
  613. <div className={styles["sidebar-action"]}>
  614. <a href={REPO_URL} target="_blank">
  615. <IconButton icon={<GithubIcon />} />
  616. </a>
  617. </div>
  618. </div>
  619. <div>
  620. <IconButton
  621. icon={<AddIcon />}
  622. text={Locale.Home.NewChat}
  623. onClick={() => {
  624. createNewSession();
  625. setShowSideBar(false);
  626. }}
  627. />
  628. </div>
  629. </div>
  630. </div>
  631. <div className={styles["window-content"]}>
  632. {openSettings ? (
  633. <Settings
  634. closeSettings={() => {
  635. setOpenSettings(false);
  636. setShowSideBar(true);
  637. }}
  638. />
  639. ) : (
  640. <Chat
  641. key="chat"
  642. showSideBar={() => setShowSideBar(true)}
  643. sideBarShowing={showSideBar}
  644. />
  645. )}
  646. </div>
  647. </div>
  648. );
  649. }