home.tsx 20 KB

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