chat.tsx 18 KB

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