chat.tsx 19 KB

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