chat.tsx 19 KB

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