chat.tsx 19 KB

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