home.tsx 20 KB

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