chat.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. import { useDebounce, useDebouncedCallback } from "use-debounce";
  2. import { memo, useState, useRef, useEffect, useLayoutEffect } from "react";
  3. import SendWhiteIcon from "../icons/send-white.svg";
  4. import BrainIcon from "../icons/brain.svg";
  5. import ExportIcon from "../icons/export.svg";
  6. import ReturnIcon from "../icons/return.svg";
  7. import CopyIcon from "../icons/copy.svg";
  8. import DownloadIcon from "../icons/download.svg";
  9. import LoadingIcon from "../icons/three-dots.svg";
  10. import BotIcon from "../icons/bot.svg";
  11. import AddIcon from "../icons/add.svg";
  12. import DeleteIcon from "../icons/delete.svg";
  13. import {
  14. Message,
  15. SubmitKey,
  16. useChatStore,
  17. BOT_HELLO,
  18. ROLES,
  19. createMessage,
  20. } from "../store";
  21. import {
  22. copyToClipboard,
  23. downloadAs,
  24. getEmojiUrl,
  25. isMobileScreen,
  26. selectOrCopy,
  27. autoGrowTextArea,
  28. } from "../utils";
  29. import dynamic from "next/dynamic";
  30. import { ControllerPool } from "../requests";
  31. import { Prompt, usePromptStore } from "../store/prompt";
  32. import Locale from "../locales";
  33. import { IconButton } from "./button";
  34. import styles from "./home.module.scss";
  35. import chatStyle from "./chat.module.scss";
  36. import { Input, Modal, showModal } from "./ui-lib";
  37. const Markdown = dynamic(
  38. async () => memo((await import("./markdown")).Markdown),
  39. {
  40. loading: () => <LoadingIcon />,
  41. },
  42. );
  43. const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, {
  44. loading: () => <LoadingIcon />,
  45. });
  46. export function Avatar(props: { role: Message["role"] }) {
  47. const config = useChatStore((state) => state.config);
  48. if (props.role !== "user") {
  49. return <BotIcon className={styles["user-avtar"]} />;
  50. }
  51. return (
  52. <div className={styles["user-avtar"]}>
  53. <Emoji unified={config.avatar} size={18} getEmojiUrl={getEmojiUrl} />
  54. </div>
  55. );
  56. }
  57. function exportMessages(messages: Message[], topic: string) {
  58. const mdText =
  59. `# ${topic}\n\n` +
  60. messages
  61. .map((m) => {
  62. return m.role === "user"
  63. ? `## ${Locale.Export.MessageFromYou}:\n${m.content}`
  64. : `## ${Locale.Export.MessageFromChatGPT}:\n${m.content.trim()}`;
  65. })
  66. .join("\n\n");
  67. const filename = `${topic}.md`;
  68. showModal({
  69. title: Locale.Export.Title,
  70. children: (
  71. <div className="markdown-body">
  72. <pre className={styles["export-content"]}>{mdText}</pre>
  73. </div>
  74. ),
  75. actions: [
  76. <IconButton
  77. key="copy"
  78. icon={<CopyIcon />}
  79. bordered
  80. text={Locale.Export.Copy}
  81. onClick={() => copyToClipboard(mdText)}
  82. />,
  83. <IconButton
  84. key="download"
  85. icon={<DownloadIcon />}
  86. bordered
  87. text={Locale.Export.Download}
  88. onClick={() => downloadAs(mdText, filename)}
  89. />,
  90. ],
  91. });
  92. }
  93. function PromptToast(props: {
  94. showToast?: boolean;
  95. showModal?: boolean;
  96. setShowModal: (_: boolean) => void;
  97. }) {
  98. const chatStore = useChatStore();
  99. const session = chatStore.currentSession();
  100. const context = session.context;
  101. const addContextPrompt = (prompt: Message) => {
  102. chatStore.updateCurrentSession((session) => {
  103. session.context.push(prompt);
  104. });
  105. };
  106. const removeContextPrompt = (i: number) => {
  107. chatStore.updateCurrentSession((session) => {
  108. session.context.splice(i, 1);
  109. });
  110. };
  111. const updateContextPrompt = (i: number, prompt: Message) => {
  112. chatStore.updateCurrentSession((session) => {
  113. session.context[i] = prompt;
  114. });
  115. };
  116. return (
  117. <div className={chatStyle["prompt-toast"]} key="prompt-toast">
  118. {props.showToast && (
  119. <div
  120. className={chatStyle["prompt-toast-inner"] + " clickable"}
  121. role="button"
  122. onClick={() => props.setShowModal(true)}
  123. >
  124. <BrainIcon />
  125. <span className={chatStyle["prompt-toast-content"]}>
  126. {Locale.Context.Toast(context.length)}
  127. </span>
  128. </div>
  129. )}
  130. {props.showModal && (
  131. <div className="modal-mask">
  132. <Modal
  133. title={Locale.Context.Edit}
  134. onClose={() => props.setShowModal(false)}
  135. actions={[
  136. <IconButton
  137. key="reset"
  138. icon={<CopyIcon />}
  139. bordered
  140. text={Locale.Memory.Reset}
  141. onClick={() =>
  142. confirm(Locale.Memory.ResetConfirm) &&
  143. chatStore.resetSession()
  144. }
  145. />,
  146. <IconButton
  147. key="copy"
  148. icon={<CopyIcon />}
  149. bordered
  150. text={Locale.Memory.Copy}
  151. onClick={() => copyToClipboard(session.memoryPrompt)}
  152. />,
  153. ]}
  154. >
  155. <>
  156. <div className={chatStyle["context-prompt"]}>
  157. {context.map((c, i) => (
  158. <div className={chatStyle["context-prompt-row"]} key={i}>
  159. <select
  160. value={c.role}
  161. className={chatStyle["context-role"]}
  162. onChange={(e) =>
  163. updateContextPrompt(i, {
  164. ...c,
  165. role: e.target.value as any,
  166. })
  167. }
  168. >
  169. {ROLES.map((r) => (
  170. <option key={r} value={r}>
  171. {r}
  172. </option>
  173. ))}
  174. </select>
  175. <Input
  176. value={c.content}
  177. type="text"
  178. className={chatStyle["context-content"]}
  179. rows={1}
  180. onInput={(e) =>
  181. updateContextPrompt(i, {
  182. ...c,
  183. content: e.currentTarget.value as any,
  184. })
  185. }
  186. />
  187. <IconButton
  188. icon={<DeleteIcon />}
  189. className={chatStyle["context-delete-button"]}
  190. onClick={() => removeContextPrompt(i)}
  191. bordered
  192. />
  193. </div>
  194. ))}
  195. <div className={chatStyle["context-prompt-row"]}>
  196. <IconButton
  197. icon={<AddIcon />}
  198. text={Locale.Context.Add}
  199. bordered
  200. className={chatStyle["context-prompt-button"]}
  201. onClick={() =>
  202. addContextPrompt({
  203. role: "system",
  204. content: "",
  205. date: "",
  206. })
  207. }
  208. />
  209. </div>
  210. </div>
  211. <div className={chatStyle["memory-prompt"]}>
  212. <div className={chatStyle["memory-prompt-title"]}>
  213. <span>
  214. {Locale.Memory.Title} ({session.lastSummarizeIndex} of{" "}
  215. {session.messages.length})
  216. </span>
  217. <label className={chatStyle["memory-prompt-action"]}>
  218. {Locale.Memory.Send}
  219. <input
  220. type="checkbox"
  221. checked={session.sendMemory}
  222. onChange={() =>
  223. chatStore.updateCurrentSession(
  224. (session) =>
  225. (session.sendMemory = !session.sendMemory),
  226. )
  227. }
  228. ></input>
  229. </label>
  230. </div>
  231. <div className={chatStyle["memory-prompt-content"]}>
  232. {session.memoryPrompt || Locale.Memory.EmptyContent}
  233. </div>
  234. </div>
  235. </>
  236. </Modal>
  237. </div>
  238. )}
  239. </div>
  240. );
  241. }
  242. function useSubmitHandler() {
  243. const config = useChatStore((state) => state.config);
  244. const submitKey = config.submitKey;
  245. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  246. if (e.key !== "Enter") return false;
  247. if (e.key === "Enter" && e.nativeEvent.isComposing) return false;
  248. return (
  249. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  250. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  251. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  252. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  253. (config.submitKey === SubmitKey.Enter &&
  254. !e.altKey &&
  255. !e.ctrlKey &&
  256. !e.shiftKey &&
  257. !e.metaKey)
  258. );
  259. };
  260. return {
  261. submitKey,
  262. shouldSubmit,
  263. };
  264. }
  265. export function PromptHints(props: {
  266. prompts: Prompt[];
  267. onPromptSelect: (prompt: Prompt) => void;
  268. }) {
  269. if (props.prompts.length === 0) return null;
  270. return (
  271. <div className={styles["prompt-hints"]}>
  272. {props.prompts.map((prompt, i) => (
  273. <div
  274. className={styles["prompt-hint"]}
  275. key={prompt.title + i.toString()}
  276. onClick={() => props.onPromptSelect(prompt)}
  277. >
  278. <div className={styles["hint-title"]}>{prompt.title}</div>
  279. <div className={styles["hint-content"]}>{prompt.content}</div>
  280. </div>
  281. ))}
  282. </div>
  283. );
  284. }
  285. function useScrollToBottom() {
  286. // for auto-scroll
  287. const scrollRef = useRef<HTMLDivElement>(null);
  288. const [autoScroll, setAutoScroll] = useState(true);
  289. // auto scroll
  290. useLayoutEffect(() => {
  291. const dom = scrollRef.current;
  292. if (dom && autoScroll) {
  293. setTimeout(() => (dom.scrollTop = dom.scrollHeight), 1);
  294. }
  295. });
  296. return {
  297. scrollRef,
  298. autoScroll,
  299. setAutoScroll,
  300. };
  301. }
  302. export function Chat(props: {
  303. showSideBar?: () => void;
  304. sideBarShowing?: boolean;
  305. }) {
  306. type RenderMessage = Message & { preview?: boolean };
  307. const chatStore = useChatStore();
  308. const [session, sessionIndex] = useChatStore((state) => [
  309. state.currentSession(),
  310. state.currentSessionIndex,
  311. ]);
  312. const fontSize = useChatStore((state) => state.config.fontSize);
  313. const inputRef = useRef<HTMLTextAreaElement>(null);
  314. const [userInput, setUserInput] = useState("");
  315. const [beforeInput, setBeforeInput] = useState("");
  316. const [isLoading, setIsLoading] = useState(false);
  317. const { submitKey, shouldSubmit } = useSubmitHandler();
  318. const { scrollRef, setAutoScroll } = useScrollToBottom();
  319. const [hitBottom, setHitBottom] = useState(false);
  320. const onChatBodyScroll = (e: HTMLElement) => {
  321. const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 20;
  322. setHitBottom(isTouchBottom);
  323. };
  324. // prompt hints
  325. const promptStore = usePromptStore();
  326. const [promptHints, setPromptHints] = useState<Prompt[]>([]);
  327. const onSearch = useDebouncedCallback(
  328. (text: string) => {
  329. setPromptHints(promptStore.search(text));
  330. },
  331. 100,
  332. { leading: true, trailing: true },
  333. );
  334. const onPromptSelect = (prompt: Prompt) => {
  335. setUserInput(prompt.content);
  336. setPromptHints([]);
  337. inputRef.current?.focus();
  338. };
  339. const scrollInput = () => {
  340. const dom = inputRef.current;
  341. if (!dom) return;
  342. const paddingBottomNum: number = parseInt(
  343. window.getComputedStyle(dom).paddingBottom,
  344. 10,
  345. );
  346. dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
  347. };
  348. // auto grow input
  349. const [inputRows, setInputRows] = useState(2);
  350. const measure = useDebouncedCallback(
  351. () => {
  352. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  353. const inputRows = Math.min(
  354. 5,
  355. Math.max(2 + Number(!isMobileScreen()), rows),
  356. );
  357. setInputRows(inputRows);
  358. },
  359. 100,
  360. {
  361. leading: true,
  362. trailing: true,
  363. },
  364. );
  365. // eslint-disable-next-line react-hooks/exhaustive-deps
  366. useEffect(measure, [userInput]);
  367. // only search prompts when user input is short
  368. const SEARCH_TEXT_LIMIT = 30;
  369. const onInput = (text: string) => {
  370. scrollInput();
  371. setUserInput(text);
  372. const n = text.trim().length;
  373. // clear search results
  374. if (n === 0) {
  375. setPromptHints([]);
  376. } else if (!chatStore.config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  377. // check if need to trigger auto completion
  378. if (text.startsWith("/")) {
  379. let searchText = text.slice(1);
  380. if (searchText.length === 0) {
  381. searchText = " ";
  382. }
  383. onSearch(searchText);
  384. }
  385. }
  386. };
  387. // submit user input
  388. const onUserSubmit = () => {
  389. if (userInput.length <= 0) return;
  390. setIsLoading(true);
  391. chatStore.onUserInput(userInput).then(() => setIsLoading(false));
  392. setBeforeInput(userInput);
  393. setUserInput("");
  394. setPromptHints([]);
  395. if (!isMobileScreen()) inputRef.current?.focus();
  396. setAutoScroll(true);
  397. };
  398. // stop response
  399. const onUserStop = (messageId: number) => {
  400. ControllerPool.stop(sessionIndex, messageId);
  401. };
  402. // check if should send message
  403. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  404. // if ArrowUp and no userInput
  405. if (e.key === "ArrowUp" && userInput.length <= 0) {
  406. setUserInput(beforeInput);
  407. e.preventDefault();
  408. return;
  409. }
  410. if (shouldSubmit(e)) {
  411. onUserSubmit();
  412. e.preventDefault();
  413. }
  414. };
  415. const onRightClick = (e: any, message: Message) => {
  416. // auto fill user input
  417. if (message.role === "user") {
  418. setUserInput(message.content);
  419. }
  420. // copy to clipboard
  421. if (selectOrCopy(e.currentTarget, message.content)) {
  422. e.preventDefault();
  423. }
  424. };
  425. const onResend = (botIndex: number) => {
  426. // find last user input message and resend
  427. for (let i = botIndex; i >= 0; i -= 1) {
  428. if (messages[i].role === "user") {
  429. setIsLoading(true);
  430. chatStore
  431. .onUserInput(messages[i].content)
  432. .then(() => setIsLoading(false));
  433. chatStore.updateCurrentSession((session) =>
  434. session.messages.splice(i, 2),
  435. );
  436. inputRef.current?.focus();
  437. return;
  438. }
  439. }
  440. };
  441. const config = useChatStore((state) => state.config);
  442. const context: RenderMessage[] = session.context.slice();
  443. if (
  444. context.length === 0 &&
  445. session.messages.at(0)?.content !== BOT_HELLO.content
  446. ) {
  447. context.push(BOT_HELLO);
  448. }
  449. // preview messages
  450. const messages = context
  451. .concat(session.messages as RenderMessage[])
  452. .concat(
  453. isLoading
  454. ? [
  455. {
  456. ...createMessage({
  457. role: "assistant",
  458. content: "……",
  459. }),
  460. preview: true,
  461. },
  462. ]
  463. : [],
  464. )
  465. .concat(
  466. userInput.length > 0 && config.sendPreviewBubble
  467. ? [
  468. {
  469. ...createMessage({
  470. role: "user",
  471. content: userInput,
  472. }),
  473. preview: true,
  474. },
  475. ]
  476. : [],
  477. );
  478. const [showPromptModal, setShowPromptModal] = useState(false);
  479. // Auto focus
  480. useEffect(() => {
  481. if (props.sideBarShowing && isMobileScreen()) return;
  482. inputRef.current?.focus();
  483. // eslint-disable-next-line react-hooks/exhaustive-deps
  484. }, []);
  485. return (
  486. <div className={styles.chat} key={session.id}>
  487. <div className={styles["window-header"]}>
  488. <div className={styles["window-header-title"]}>
  489. <div
  490. className={`${styles["window-header-main-title"]} ${styles["chat-body-title"]}`}
  491. onClickCapture={() => {
  492. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  493. if (newTopic && newTopic !== session.topic) {
  494. chatStore.updateCurrentSession(
  495. (session) => (session.topic = newTopic!),
  496. );
  497. }
  498. }}
  499. >
  500. {session.topic}
  501. </div>
  502. <div className={styles["window-header-sub-title"]}>
  503. {Locale.Chat.SubTitle(session.messages.length)}
  504. </div>
  505. </div>
  506. <div className={styles["window-actions"]}>
  507. <div className={styles["window-action-button"] + " " + styles.mobile}>
  508. <IconButton
  509. icon={<ReturnIcon />}
  510. bordered
  511. title={Locale.Chat.Actions.ChatList}
  512. onClick={props?.showSideBar}
  513. />
  514. </div>
  515. <div className={styles["window-action-button"]}>
  516. <IconButton
  517. icon={<BrainIcon />}
  518. bordered
  519. title={Locale.Chat.Actions.CompressedHistory}
  520. onClick={() => {
  521. setShowPromptModal(true);
  522. }}
  523. />
  524. </div>
  525. <div className={styles["window-action-button"]}>
  526. <IconButton
  527. icon={<ExportIcon />}
  528. bordered
  529. title={Locale.Chat.Actions.Export}
  530. onClick={() => {
  531. exportMessages(
  532. session.messages.filter((msg) => !msg.isError),
  533. session.topic,
  534. );
  535. }}
  536. />
  537. </div>
  538. </div>
  539. <PromptToast
  540. showToast={!hitBottom}
  541. showModal={showPromptModal}
  542. setShowModal={setShowPromptModal}
  543. />
  544. </div>
  545. <div
  546. className={styles["chat-body"]}
  547. ref={scrollRef}
  548. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  549. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  550. onTouchStart={() => {
  551. inputRef.current?.blur();
  552. setAutoScroll(false);
  553. }}
  554. >
  555. {messages.map((message, i) => {
  556. const isUser = message.role === "user";
  557. return (
  558. <div
  559. key={i}
  560. className={
  561. isUser ? styles["chat-message-user"] : styles["chat-message"]
  562. }
  563. >
  564. <div className={styles["chat-message-container"]}>
  565. <div className={styles["chat-message-avatar"]}>
  566. <Avatar role={message.role} />
  567. </div>
  568. {(message.preview || message.streaming) && (
  569. <div className={styles["chat-message-status"]}>
  570. {Locale.Chat.Typing}
  571. </div>
  572. )}
  573. <div className={styles["chat-message-item"]}>
  574. {!isUser &&
  575. !(message.preview || message.content.length === 0) && (
  576. <div className={styles["chat-message-top-actions"]}>
  577. {message.streaming ? (
  578. <div
  579. className={styles["chat-message-top-action"]}
  580. onClick={() => onUserStop(message.id ?? i)}
  581. >
  582. {Locale.Chat.Actions.Stop}
  583. </div>
  584. ) : (
  585. <div
  586. className={styles["chat-message-top-action"]}
  587. onClick={() => onResend(i)}
  588. >
  589. {Locale.Chat.Actions.Retry}
  590. </div>
  591. )}
  592. <div
  593. className={styles["chat-message-top-action"]}
  594. onClick={() => copyToClipboard(message.content)}
  595. >
  596. {Locale.Chat.Actions.Copy}
  597. </div>
  598. </div>
  599. )}
  600. {(message.preview || message.content.length === 0) &&
  601. !isUser ? (
  602. <LoadingIcon />
  603. ) : (
  604. <div
  605. className="markdown-body"
  606. style={{ fontSize: `${fontSize}px` }}
  607. onContextMenu={(e) => onRightClick(e, message)}
  608. onDoubleClickCapture={() => {
  609. if (!isMobileScreen()) return;
  610. setUserInput(message.content);
  611. }}
  612. >
  613. <Markdown content={message.content} />
  614. </div>
  615. )}
  616. </div>
  617. {!isUser && !message.preview && (
  618. <div className={styles["chat-message-actions"]}>
  619. <div className={styles["chat-message-action-date"]}>
  620. {message.date.toLocaleString()}
  621. </div>
  622. </div>
  623. )}
  624. </div>
  625. </div>
  626. );
  627. })}
  628. </div>
  629. <div className={styles["chat-input-panel"]}>
  630. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  631. <div className={styles["chat-input-panel-inner"]}>
  632. <textarea
  633. ref={inputRef}
  634. className={styles["chat-input"]}
  635. placeholder={Locale.Chat.Input(submitKey)}
  636. onInput={(e) => onInput(e.currentTarget.value)}
  637. value={userInput}
  638. onKeyDown={onInputKeyDown}
  639. onFocus={() => setAutoScroll(true)}
  640. onBlur={() => {
  641. setAutoScroll(false);
  642. setTimeout(() => setPromptHints([]), 500);
  643. }}
  644. autoFocus={!props?.sideBarShowing}
  645. rows={inputRows}
  646. />
  647. <IconButton
  648. icon={<SendWhiteIcon />}
  649. text={Locale.Chat.Send}
  650. className={styles["chat-input-send"]}
  651. noDark
  652. onClick={onUserSubmit}
  653. />
  654. </div>
  655. </div>
  656. </div>
  657. );
  658. }