chat.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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. onSearch(searchText);
  381. }
  382. }
  383. };
  384. // submit user input
  385. const onUserSubmit = () => {
  386. if (userInput.length <= 0) return;
  387. setIsLoading(true);
  388. chatStore.onUserInput(userInput).then(() => setIsLoading(false));
  389. setBeforeInput(userInput);
  390. setUserInput("");
  391. setPromptHints([]);
  392. if (!isMobileScreen()) inputRef.current?.focus();
  393. setAutoScroll(true);
  394. };
  395. // stop response
  396. const onUserStop = (messageId: number) => {
  397. ControllerPool.stop(sessionIndex, messageId);
  398. };
  399. // check if should send message
  400. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  401. // if ArrowUp and no userInput
  402. if (e.key === "ArrowUp" && userInput.length <= 0) {
  403. setUserInput(beforeInput);
  404. e.preventDefault();
  405. return;
  406. }
  407. if (shouldSubmit(e)) {
  408. onUserSubmit();
  409. e.preventDefault();
  410. }
  411. };
  412. const onRightClick = (e: any, message: Message) => {
  413. // auto fill user input
  414. if (message.role === "user") {
  415. setUserInput(message.content);
  416. }
  417. // copy to clipboard
  418. if (selectOrCopy(e.currentTarget, message.content)) {
  419. e.preventDefault();
  420. }
  421. };
  422. const onResend = (botIndex: number) => {
  423. // find last user input message and resend
  424. for (let i = botIndex; i >= 0; i -= 1) {
  425. if (messages[i].role === "user") {
  426. setIsLoading(true);
  427. chatStore
  428. .onUserInput(messages[i].content)
  429. .then(() => setIsLoading(false));
  430. chatStore.updateCurrentSession((session) =>
  431. session.messages.splice(i, 2),
  432. );
  433. inputRef.current?.focus();
  434. return;
  435. }
  436. }
  437. };
  438. const config = useChatStore((state) => state.config);
  439. const context: RenderMessage[] = session.context.slice();
  440. if (
  441. context.length === 0 &&
  442. session.messages.at(0)?.content !== BOT_HELLO.content
  443. ) {
  444. context.push(BOT_HELLO);
  445. }
  446. // preview messages
  447. const messages = context
  448. .concat(session.messages as RenderMessage[])
  449. .concat(
  450. isLoading
  451. ? [
  452. {
  453. ...createMessage({
  454. role: "assistant",
  455. content: "……",
  456. }),
  457. preview: true,
  458. },
  459. ]
  460. : [],
  461. )
  462. .concat(
  463. userInput.length > 0 && config.sendPreviewBubble
  464. ? [
  465. {
  466. ...createMessage({
  467. role: "user",
  468. content: userInput,
  469. }),
  470. preview: true,
  471. },
  472. ]
  473. : [],
  474. );
  475. const [showPromptModal, setShowPromptModal] = useState(false);
  476. // Auto focus
  477. useEffect(() => {
  478. if (props.sideBarShowing && isMobileScreen()) return;
  479. inputRef.current?.focus();
  480. // eslint-disable-next-line react-hooks/exhaustive-deps
  481. }, []);
  482. return (
  483. <div className={styles.chat} key={session.id}>
  484. <div className={styles["window-header"]}>
  485. <div className={styles["window-header-title"]}>
  486. <div
  487. className={`${styles["window-header-main-title"]} ${styles["chat-body-title"]}`}
  488. onClickCapture={() => {
  489. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  490. if (newTopic && newTopic !== session.topic) {
  491. chatStore.updateCurrentSession(
  492. (session) => (session.topic = newTopic!),
  493. );
  494. }
  495. }}
  496. >
  497. {session.topic}
  498. </div>
  499. <div className={styles["window-header-sub-title"]}>
  500. {Locale.Chat.SubTitle(session.messages.length)}
  501. </div>
  502. </div>
  503. <div className={styles["window-actions"]}>
  504. <div className={styles["window-action-button"] + " " + styles.mobile}>
  505. <IconButton
  506. icon={<ReturnIcon />}
  507. bordered
  508. title={Locale.Chat.Actions.ChatList}
  509. onClick={props?.showSideBar}
  510. />
  511. </div>
  512. <div className={styles["window-action-button"]}>
  513. <IconButton
  514. icon={<BrainIcon />}
  515. bordered
  516. title={Locale.Chat.Actions.CompressedHistory}
  517. onClick={() => {
  518. setShowPromptModal(true);
  519. }}
  520. />
  521. </div>
  522. <div className={styles["window-action-button"]}>
  523. <IconButton
  524. icon={<ExportIcon />}
  525. bordered
  526. title={Locale.Chat.Actions.Export}
  527. onClick={() => {
  528. exportMessages(
  529. session.messages.filter((msg) => !msg.isError),
  530. session.topic,
  531. );
  532. }}
  533. />
  534. </div>
  535. </div>
  536. <PromptToast
  537. showToast={!hitBottom}
  538. showModal={showPromptModal}
  539. setShowModal={setShowPromptModal}
  540. />
  541. </div>
  542. <div
  543. className={styles["chat-body"]}
  544. ref={scrollRef}
  545. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  546. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  547. onTouchStart={() => {
  548. inputRef.current?.blur();
  549. setAutoScroll(false);
  550. }}
  551. >
  552. {messages.map((message, i) => {
  553. const isUser = message.role === "user";
  554. return (
  555. <div
  556. key={i}
  557. className={
  558. isUser ? styles["chat-message-user"] : styles["chat-message"]
  559. }
  560. >
  561. <div className={styles["chat-message-container"]}>
  562. <div className={styles["chat-message-avatar"]}>
  563. <Avatar role={message.role} />
  564. </div>
  565. {(message.preview || message.streaming) && (
  566. <div className={styles["chat-message-status"]}>
  567. {Locale.Chat.Typing}
  568. </div>
  569. )}
  570. <div className={styles["chat-message-item"]}>
  571. {!isUser &&
  572. !(message.preview || message.content.length === 0) && (
  573. <div className={styles["chat-message-top-actions"]}>
  574. {message.streaming ? (
  575. <div
  576. className={styles["chat-message-top-action"]}
  577. onClick={() => onUserStop(message.id ?? i)}
  578. >
  579. {Locale.Chat.Actions.Stop}
  580. </div>
  581. ) : (
  582. <div
  583. className={styles["chat-message-top-action"]}
  584. onClick={() => onResend(i)}
  585. >
  586. {Locale.Chat.Actions.Retry}
  587. </div>
  588. )}
  589. <div
  590. className={styles["chat-message-top-action"]}
  591. onClick={() => copyToClipboard(message.content)}
  592. >
  593. {Locale.Chat.Actions.Copy}
  594. </div>
  595. </div>
  596. )}
  597. {(message.preview || message.content.length === 0) &&
  598. !isUser ? (
  599. <LoadingIcon />
  600. ) : (
  601. <div
  602. className="markdown-body"
  603. style={{ fontSize: `${fontSize}px` }}
  604. onContextMenu={(e) => onRightClick(e, message)}
  605. onDoubleClickCapture={() => {
  606. if (!isMobileScreen()) return;
  607. setUserInput(message.content);
  608. }}
  609. >
  610. <Markdown content={message.content} />
  611. </div>
  612. )}
  613. </div>
  614. {!isUser && !message.preview && (
  615. <div className={styles["chat-message-actions"]}>
  616. <div className={styles["chat-message-action-date"]}>
  617. {message.date.toLocaleString()}
  618. </div>
  619. </div>
  620. )}
  621. </div>
  622. </div>
  623. );
  624. })}
  625. </div>
  626. <div className={styles["chat-input-panel"]}>
  627. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  628. <div className={styles["chat-input-panel-inner"]}>
  629. <textarea
  630. ref={inputRef}
  631. className={styles["chat-input"]}
  632. placeholder={Locale.Chat.Input(submitKey)}
  633. onInput={(e) => onInput(e.currentTarget.value)}
  634. value={userInput}
  635. onKeyDown={onInputKeyDown}
  636. onFocus={() => setAutoScroll(true)}
  637. onBlur={() => {
  638. setAutoScroll(false);
  639. setTimeout(() => setPromptHints([]), 500);
  640. }}
  641. autoFocus={!props?.sideBarShowing}
  642. rows={inputRows}
  643. />
  644. <IconButton
  645. icon={<SendWhiteIcon />}
  646. text={Locale.Chat.Send}
  647. className={styles["chat-input-send"]}
  648. noDark
  649. onClick={onUserSubmit}
  650. />
  651. </div>
  652. </div>
  653. </div>
  654. );
  655. }