chat.tsx 20 KB

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