home.tsx 20 KB

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