home.tsx 19 KB

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