home.tsx 20 KB

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