home.tsx 20 KB

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