chat.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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 RenameIcon from "../icons/rename.svg";
  6. import ExportIcon from "../icons/share.svg";
  7. import ReturnIcon from "../icons/return.svg";
  8. import CopyIcon from "../icons/copy.svg";
  9. import DownloadIcon from "../icons/download.svg";
  10. import LoadingIcon from "../icons/three-dots.svg";
  11. import PromptIcon from "../icons/prompt.svg";
  12. import MaskIcon from "../icons/mask.svg";
  13. import MaxIcon from "../icons/max.svg";
  14. import MinIcon from "../icons/min.svg";
  15. import ResetIcon from "../icons/reload.svg";
  16. import LightIcon from "../icons/light.svg";
  17. import DarkIcon from "../icons/dark.svg";
  18. import AutoIcon from "../icons/auto.svg";
  19. import BottomIcon from "../icons/bottom.svg";
  20. import StopIcon from "../icons/pause.svg";
  21. import {
  22. ChatMessage,
  23. SubmitKey,
  24. useChatStore,
  25. BOT_HELLO,
  26. createMessage,
  27. useAccessStore,
  28. Theme,
  29. useAppConfig,
  30. DEFAULT_TOPIC,
  31. } from "../store";
  32. import {
  33. copyToClipboard,
  34. downloadAs,
  35. selectOrCopy,
  36. autoGrowTextArea,
  37. useMobileScreen,
  38. } from "../utils";
  39. import dynamic from "next/dynamic";
  40. import { ChatControllerPool } from "../client/controller";
  41. import { Prompt, usePromptStore } from "../store/prompt";
  42. import Locale from "../locales";
  43. import { IconButton } from "./button";
  44. import styles from "./home.module.scss";
  45. import chatStyle from "./chat.module.scss";
  46. import { ListItem, Modal, showModal } from "./ui-lib";
  47. import { useLocation, useNavigate } from "react-router-dom";
  48. import { LAST_INPUT_KEY, Path, REQUEST_TIMEOUT_MS } from "../constant";
  49. import { Avatar } from "./emoji";
  50. import { MaskAvatar, MaskConfig } from "./mask";
  51. import { useMaskStore } from "../store/mask";
  52. import { useCommand } from "../command";
  53. import { prettyObject } from "../utils/format";
  54. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  55. loading: () => <LoadingIcon />,
  56. });
  57. function exportMessages(messages: ChatMessage[], topic: string) {
  58. const mdText =
  59. `# ${topic}\n\n` +
  60. messages
  61. .map((m) => {
  62. return m.role === "user"
  63. ? `## ${Locale.Export.MessageFromYou}:\n${m.content}`
  64. : `## ${Locale.Export.MessageFromChatGPT}:\n${m.content.trim()}`;
  65. })
  66. .join("\n\n");
  67. const filename = `${topic}.md`;
  68. showModal({
  69. title: Locale.Export.Title,
  70. children: (
  71. <div className="markdown-body">
  72. <pre className={styles["export-content"]}>{mdText}</pre>
  73. </div>
  74. ),
  75. actions: [
  76. <IconButton
  77. key="copy"
  78. icon={<CopyIcon />}
  79. bordered
  80. text={Locale.Export.Copy}
  81. onClick={() => copyToClipboard(mdText)}
  82. />,
  83. <IconButton
  84. key="download"
  85. icon={<DownloadIcon />}
  86. bordered
  87. text={Locale.Export.Download}
  88. onClick={() => downloadAs(mdText, filename)}
  89. />,
  90. ],
  91. });
  92. }
  93. export function SessionConfigModel(props: { onClose: () => void }) {
  94. const chatStore = useChatStore();
  95. const session = chatStore.currentSession();
  96. const maskStore = useMaskStore();
  97. const navigate = useNavigate();
  98. return (
  99. <div className="modal-mask">
  100. <Modal
  101. title={Locale.Context.Edit}
  102. onClose={() => props.onClose()}
  103. actions={[
  104. <IconButton
  105. key="reset"
  106. icon={<ResetIcon />}
  107. bordered
  108. text={Locale.Chat.Config.Reset}
  109. onClick={() =>
  110. confirm(Locale.Memory.ResetConfirm) && chatStore.resetSession()
  111. }
  112. />,
  113. <IconButton
  114. key="copy"
  115. icon={<CopyIcon />}
  116. bordered
  117. text={Locale.Chat.Config.SaveAs}
  118. onClick={() => {
  119. navigate(Path.Masks);
  120. setTimeout(() => {
  121. maskStore.create(session.mask);
  122. }, 500);
  123. }}
  124. />,
  125. ]}
  126. >
  127. <MaskConfig
  128. mask={session.mask}
  129. updateMask={(updater) => {
  130. const mask = { ...session.mask };
  131. updater(mask);
  132. chatStore.updateCurrentSession((session) => (session.mask = mask));
  133. }}
  134. shouldSyncFromGlobal
  135. extraListItems={
  136. session.mask.modelConfig.sendMemory ? (
  137. <ListItem
  138. title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`}
  139. subTitle={session.memoryPrompt || Locale.Memory.EmptyContent}
  140. ></ListItem>
  141. ) : (
  142. <></>
  143. )
  144. }
  145. ></MaskConfig>
  146. </Modal>
  147. </div>
  148. );
  149. }
  150. function PromptToast(props: {
  151. showToast?: boolean;
  152. showModal?: boolean;
  153. setShowModal: (_: boolean) => void;
  154. }) {
  155. const chatStore = useChatStore();
  156. const session = chatStore.currentSession();
  157. const context = session.mask.context;
  158. return (
  159. <div className={chatStyle["prompt-toast"]} key="prompt-toast">
  160. {props.showToast && (
  161. <div
  162. className={chatStyle["prompt-toast-inner"] + " clickable"}
  163. role="button"
  164. onClick={() => props.setShowModal(true)}
  165. >
  166. <BrainIcon />
  167. <span className={chatStyle["prompt-toast-content"]}>
  168. {Locale.Context.Toast(context.length)}
  169. </span>
  170. </div>
  171. )}
  172. {props.showModal && (
  173. <SessionConfigModel onClose={() => props.setShowModal(false)} />
  174. )}
  175. </div>
  176. );
  177. }
  178. function useSubmitHandler() {
  179. const config = useAppConfig();
  180. const submitKey = config.submitKey;
  181. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  182. if (e.key !== "Enter") return false;
  183. if (e.key === "Enter" && e.nativeEvent.isComposing) return false;
  184. return (
  185. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  186. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  187. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  188. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  189. (config.submitKey === SubmitKey.Enter &&
  190. !e.altKey &&
  191. !e.ctrlKey &&
  192. !e.shiftKey &&
  193. !e.metaKey)
  194. );
  195. };
  196. return {
  197. submitKey,
  198. shouldSubmit,
  199. };
  200. }
  201. export function PromptHints(props: {
  202. prompts: Prompt[];
  203. onPromptSelect: (prompt: Prompt) => void;
  204. }) {
  205. const noPrompts = props.prompts.length === 0;
  206. const [selectIndex, setSelectIndex] = useState(0);
  207. const selectedRef = useRef<HTMLDivElement>(null);
  208. useEffect(() => {
  209. setSelectIndex(0);
  210. }, [props.prompts.length]);
  211. useEffect(() => {
  212. const onKeyDown = (e: KeyboardEvent) => {
  213. if (noPrompts) return;
  214. if (e.metaKey || e.altKey || e.ctrlKey) {
  215. return;
  216. }
  217. // arrow up / down to select prompt
  218. const changeIndex = (delta: number) => {
  219. e.stopPropagation();
  220. e.preventDefault();
  221. const nextIndex = Math.max(
  222. 0,
  223. Math.min(props.prompts.length - 1, selectIndex + delta),
  224. );
  225. setSelectIndex(nextIndex);
  226. selectedRef.current?.scrollIntoView({
  227. block: "center",
  228. });
  229. };
  230. if (e.key === "ArrowUp") {
  231. changeIndex(1);
  232. } else if (e.key === "ArrowDown") {
  233. changeIndex(-1);
  234. } else if (e.key === "Enter") {
  235. const selectedPrompt = props.prompts.at(selectIndex);
  236. if (selectedPrompt) {
  237. props.onPromptSelect(selectedPrompt);
  238. }
  239. }
  240. };
  241. window.addEventListener("keydown", onKeyDown);
  242. return () => window.removeEventListener("keydown", onKeyDown);
  243. // eslint-disable-next-line react-hooks/exhaustive-deps
  244. }, [noPrompts, selectIndex]);
  245. if (noPrompts) return null;
  246. return (
  247. <div className={styles["prompt-hints"]}>
  248. {props.prompts.map((prompt, i) => (
  249. <div
  250. ref={i === selectIndex ? selectedRef : null}
  251. className={
  252. styles["prompt-hint"] +
  253. ` ${i === selectIndex ? styles["prompt-hint-selected"] : ""}`
  254. }
  255. key={prompt.title + i.toString()}
  256. onClick={() => props.onPromptSelect(prompt)}
  257. onMouseEnter={() => setSelectIndex(i)}
  258. >
  259. <div className={styles["hint-title"]}>{prompt.title}</div>
  260. <div className={styles["hint-content"]}>{prompt.content}</div>
  261. </div>
  262. ))}
  263. </div>
  264. );
  265. }
  266. function useScrollToBottom() {
  267. // for auto-scroll
  268. const scrollRef = useRef<HTMLDivElement>(null);
  269. const [autoScroll, setAutoScroll] = useState(true);
  270. const scrollToBottom = () => {
  271. const dom = scrollRef.current;
  272. if (dom) {
  273. setTimeout(() => (dom.scrollTop = dom.scrollHeight), 1);
  274. }
  275. };
  276. // auto scroll
  277. useLayoutEffect(() => {
  278. autoScroll && scrollToBottom();
  279. });
  280. return {
  281. scrollRef,
  282. autoScroll,
  283. setAutoScroll,
  284. scrollToBottom,
  285. };
  286. }
  287. export function ChatActions(props: {
  288. showPromptModal: () => void;
  289. scrollToBottom: () => void;
  290. showPromptHints: () => void;
  291. hitBottom: boolean;
  292. }) {
  293. const config = useAppConfig();
  294. const navigate = useNavigate();
  295. // switch themes
  296. const theme = config.theme;
  297. function nextTheme() {
  298. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  299. const themeIndex = themes.indexOf(theme);
  300. const nextIndex = (themeIndex + 1) % themes.length;
  301. const nextTheme = themes[nextIndex];
  302. config.update((config) => (config.theme = nextTheme));
  303. }
  304. // stop all responses
  305. const couldStop = ChatControllerPool.hasPending();
  306. const stopAll = () => ChatControllerPool.stopAll();
  307. return (
  308. <div className={chatStyle["chat-input-actions"]}>
  309. {couldStop && (
  310. <div
  311. className={`${chatStyle["chat-input-action"]} clickable`}
  312. onClick={stopAll}
  313. >
  314. <StopIcon />
  315. </div>
  316. )}
  317. {!props.hitBottom && (
  318. <div
  319. className={`${chatStyle["chat-input-action"]} clickable`}
  320. onClick={props.scrollToBottom}
  321. >
  322. <BottomIcon />
  323. </div>
  324. )}
  325. {props.hitBottom && (
  326. <div
  327. className={`${chatStyle["chat-input-action"]} clickable`}
  328. onClick={props.showPromptModal}
  329. >
  330. <BrainIcon />
  331. </div>
  332. )}
  333. <div
  334. className={`${chatStyle["chat-input-action"]} clickable`}
  335. onClick={nextTheme}
  336. >
  337. {theme === Theme.Auto ? (
  338. <AutoIcon />
  339. ) : theme === Theme.Light ? (
  340. <LightIcon />
  341. ) : theme === Theme.Dark ? (
  342. <DarkIcon />
  343. ) : null}
  344. </div>
  345. <div
  346. className={`${chatStyle["chat-input-action"]} clickable`}
  347. onClick={props.showPromptHints}
  348. >
  349. <PromptIcon />
  350. </div>
  351. <div
  352. className={`${chatStyle["chat-input-action"]} clickable`}
  353. onClick={() => {
  354. navigate(Path.Masks);
  355. }}
  356. >
  357. <MaskIcon />
  358. </div>
  359. </div>
  360. );
  361. }
  362. export function Chat() {
  363. type RenderMessage = ChatMessage & { preview?: boolean };
  364. const chatStore = useChatStore();
  365. const [session, sessionIndex] = useChatStore((state) => [
  366. state.currentSession(),
  367. state.currentSessionIndex,
  368. ]);
  369. const config = useAppConfig();
  370. const fontSize = config.fontSize;
  371. const inputRef = useRef<HTMLTextAreaElement>(null);
  372. const [userInput, setUserInput] = useState("");
  373. const [isLoading, setIsLoading] = useState(false);
  374. const { submitKey, shouldSubmit } = useSubmitHandler();
  375. const { scrollRef, setAutoScroll, scrollToBottom } = useScrollToBottom();
  376. const [hitBottom, setHitBottom] = useState(true);
  377. const isMobileScreen = useMobileScreen();
  378. const navigate = useNavigate();
  379. const onChatBodyScroll = (e: HTMLElement) => {
  380. const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 100;
  381. setHitBottom(isTouchBottom);
  382. };
  383. // prompt hints
  384. const promptStore = usePromptStore();
  385. const [promptHints, setPromptHints] = useState<Prompt[]>([]);
  386. const onSearch = useDebouncedCallback(
  387. (text: string) => {
  388. setPromptHints(promptStore.search(text));
  389. },
  390. 100,
  391. { leading: true, trailing: true },
  392. );
  393. const onPromptSelect = (prompt: Prompt) => {
  394. setPromptHints([]);
  395. inputRef.current?.focus();
  396. setTimeout(() => setUserInput(prompt.content), 60);
  397. };
  398. // auto grow input
  399. const [inputRows, setInputRows] = useState(2);
  400. const measure = useDebouncedCallback(
  401. () => {
  402. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  403. const inputRows = Math.min(
  404. 20,
  405. Math.max(2 + Number(!isMobileScreen), rows),
  406. );
  407. setInputRows(inputRows);
  408. },
  409. 100,
  410. {
  411. leading: true,
  412. trailing: true,
  413. },
  414. );
  415. // eslint-disable-next-line react-hooks/exhaustive-deps
  416. useEffect(measure, [userInput]);
  417. // only search prompts when user input is short
  418. const SEARCH_TEXT_LIMIT = 30;
  419. const onInput = (text: string) => {
  420. setUserInput(text);
  421. const n = text.trim().length;
  422. // clear search results
  423. if (n === 0) {
  424. setPromptHints([]);
  425. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  426. // check if need to trigger auto completion
  427. if (text.startsWith("/")) {
  428. let searchText = text.slice(1);
  429. onSearch(searchText);
  430. }
  431. }
  432. };
  433. const doSubmit = (userInput: string) => {
  434. if (userInput.trim() === "") return;
  435. setIsLoading(true);
  436. chatStore.onUserInput(userInput).then(() => setIsLoading(false));
  437. localStorage.setItem(LAST_INPUT_KEY, userInput);
  438. setUserInput("");
  439. setPromptHints([]);
  440. if (!isMobileScreen) inputRef.current?.focus();
  441. setAutoScroll(true);
  442. };
  443. // stop response
  444. const onUserStop = (messageId: number) => {
  445. ChatControllerPool.stop(sessionIndex, messageId);
  446. };
  447. useEffect(() => {
  448. chatStore.updateCurrentSession((session) => {
  449. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  450. session.messages.forEach((m) => {
  451. // check if should stop all stale messages
  452. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  453. if (m.streaming) {
  454. m.streaming = false;
  455. }
  456. if (m.content.length === 0) {
  457. m.isError = true;
  458. m.content = prettyObject({
  459. error: true,
  460. message: "empty response",
  461. });
  462. }
  463. }
  464. });
  465. // auto sync mask config from global config
  466. if (session.mask.syncGlobalConfig) {
  467. console.log("[Mask] syncing from global, name = ", session.mask.name);
  468. session.mask.modelConfig = { ...config.modelConfig };
  469. }
  470. });
  471. // eslint-disable-next-line react-hooks/exhaustive-deps
  472. }, []);
  473. // check if should send message
  474. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  475. // if ArrowUp and no userInput, fill with last input
  476. if (
  477. e.key === "ArrowUp" &&
  478. userInput.length <= 0 &&
  479. !(e.metaKey || e.altKey || e.ctrlKey)
  480. ) {
  481. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  482. e.preventDefault();
  483. return;
  484. }
  485. if (shouldSubmit(e) && promptHints.length === 0) {
  486. doSubmit(userInput);
  487. e.preventDefault();
  488. }
  489. };
  490. const onRightClick = (e: any, message: ChatMessage) => {
  491. // copy to clipboard
  492. if (selectOrCopy(e.currentTarget, message.content)) {
  493. e.preventDefault();
  494. }
  495. };
  496. const findLastUserIndex = (messageId: number) => {
  497. // find last user input message and resend
  498. let lastUserMessageIndex: number | null = null;
  499. for (let i = 0; i < session.messages.length; i += 1) {
  500. const message = session.messages[i];
  501. if (message.id === messageId) {
  502. break;
  503. }
  504. if (message.role === "user") {
  505. lastUserMessageIndex = i;
  506. }
  507. }
  508. return lastUserMessageIndex;
  509. };
  510. const deleteMessage = (userIndex: number) => {
  511. chatStore.updateCurrentSession((session) =>
  512. session.messages.splice(userIndex, 2),
  513. );
  514. };
  515. const onDelete = (botMessageId: number) => {
  516. const userIndex = findLastUserIndex(botMessageId);
  517. if (userIndex === null) return;
  518. deleteMessage(userIndex);
  519. };
  520. const onResend = (botMessageId: number) => {
  521. // find last user input message and resend
  522. const userIndex = findLastUserIndex(botMessageId);
  523. if (userIndex === null) return;
  524. setIsLoading(true);
  525. const content = session.messages[userIndex].content;
  526. deleteMessage(userIndex);
  527. chatStore.onUserInput(content).then(() => setIsLoading(false));
  528. inputRef.current?.focus();
  529. };
  530. const context: RenderMessage[] = session.mask.context.slice();
  531. const accessStore = useAccessStore();
  532. if (
  533. context.length === 0 &&
  534. session.messages.at(0)?.content !== BOT_HELLO.content
  535. ) {
  536. const copiedHello = Object.assign({}, BOT_HELLO);
  537. if (!accessStore.isAuthorized()) {
  538. copiedHello.content = Locale.Error.Unauthorized;
  539. }
  540. context.push(copiedHello);
  541. }
  542. // preview messages
  543. const messages = context
  544. .concat(session.messages as RenderMessage[])
  545. .concat(
  546. isLoading
  547. ? [
  548. {
  549. ...createMessage({
  550. role: "assistant",
  551. content: "……",
  552. }),
  553. preview: true,
  554. },
  555. ]
  556. : [],
  557. )
  558. .concat(
  559. userInput.length > 0 && config.sendPreviewBubble
  560. ? [
  561. {
  562. ...createMessage({
  563. role: "user",
  564. content: userInput,
  565. }),
  566. preview: true,
  567. },
  568. ]
  569. : [],
  570. );
  571. const [showPromptModal, setShowPromptModal] = useState(false);
  572. const renameSession = () => {
  573. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  574. if (newTopic && newTopic !== session.topic) {
  575. chatStore.updateCurrentSession((session) => (session.topic = newTopic!));
  576. }
  577. };
  578. const location = useLocation();
  579. const isChat = location.pathname === Path.Chat;
  580. const autoFocus = !isMobileScreen || isChat; // only focus in chat page
  581. useCommand({
  582. fill: setUserInput,
  583. submit: (text) => {
  584. doSubmit(text);
  585. },
  586. });
  587. return (
  588. <div className={styles.chat} key={session.id}>
  589. <div className="window-header">
  590. <div className="window-header-title">
  591. <div
  592. className={`window-header-main-title " ${styles["chat-body-title"]}`}
  593. onClickCapture={renameSession}
  594. >
  595. {!session.topic ? DEFAULT_TOPIC : session.topic}
  596. </div>
  597. <div className="window-header-sub-title">
  598. {Locale.Chat.SubTitle(session.messages.length)}
  599. </div>
  600. </div>
  601. <div className="window-actions">
  602. <div className={"window-action-button" + " " + styles.mobile}>
  603. <IconButton
  604. icon={<ReturnIcon />}
  605. bordered
  606. title={Locale.Chat.Actions.ChatList}
  607. onClick={() => navigate(Path.Home)}
  608. />
  609. </div>
  610. <div className="window-action-button">
  611. <IconButton
  612. icon={<RenameIcon />}
  613. bordered
  614. onClick={renameSession}
  615. />
  616. </div>
  617. <div className="window-action-button">
  618. <IconButton
  619. icon={<ExportIcon />}
  620. bordered
  621. title={Locale.Chat.Actions.Export}
  622. onClick={() => {
  623. exportMessages(
  624. session.messages.filter((msg) => !msg.isError),
  625. session.topic,
  626. );
  627. }}
  628. />
  629. </div>
  630. {!isMobileScreen && (
  631. <div className="window-action-button">
  632. <IconButton
  633. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  634. bordered
  635. onClick={() => {
  636. config.update(
  637. (config) => (config.tightBorder = !config.tightBorder),
  638. );
  639. }}
  640. />
  641. </div>
  642. )}
  643. </div>
  644. <PromptToast
  645. showToast={!hitBottom}
  646. showModal={showPromptModal}
  647. setShowModal={setShowPromptModal}
  648. />
  649. </div>
  650. <div
  651. className={styles["chat-body"]}
  652. ref={scrollRef}
  653. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  654. onMouseDown={() => inputRef.current?.blur()}
  655. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  656. onTouchStart={() => {
  657. inputRef.current?.blur();
  658. setAutoScroll(false);
  659. }}
  660. >
  661. {messages.map((message, i) => {
  662. const isUser = message.role === "user";
  663. const showActions =
  664. !isUser &&
  665. i > 0 &&
  666. !(message.preview || message.content.length === 0);
  667. const showTyping = message.preview || message.streaming;
  668. return (
  669. <div
  670. key={i}
  671. className={
  672. isUser ? styles["chat-message-user"] : styles["chat-message"]
  673. }
  674. >
  675. <div className={styles["chat-message-container"]}>
  676. <div className={styles["chat-message-avatar"]}>
  677. {message.role === "user" ? (
  678. <Avatar avatar={config.avatar} />
  679. ) : (
  680. <MaskAvatar mask={session.mask} />
  681. )}
  682. </div>
  683. {showTyping && (
  684. <div className={styles["chat-message-status"]}>
  685. {Locale.Chat.Typing}
  686. </div>
  687. )}
  688. <div className={styles["chat-message-item"]}>
  689. {showActions && (
  690. <div className={styles["chat-message-top-actions"]}>
  691. {message.streaming ? (
  692. <div
  693. className={styles["chat-message-top-action"]}
  694. onClick={() => onUserStop(message.id ?? i)}
  695. >
  696. {Locale.Chat.Actions.Stop}
  697. </div>
  698. ) : (
  699. <>
  700. <div
  701. className={styles["chat-message-top-action"]}
  702. onClick={() => onDelete(message.id ?? i)}
  703. >
  704. {Locale.Chat.Actions.Delete}
  705. </div>
  706. <div
  707. className={styles["chat-message-top-action"]}
  708. onClick={() => onResend(message.id ?? i)}
  709. >
  710. {Locale.Chat.Actions.Retry}
  711. </div>
  712. </>
  713. )}
  714. <div
  715. className={styles["chat-message-top-action"]}
  716. onClick={() => copyToClipboard(message.content)}
  717. >
  718. {Locale.Chat.Actions.Copy}
  719. </div>
  720. </div>
  721. )}
  722. <Markdown
  723. content={message.content}
  724. loading={
  725. (message.preview || message.content.length === 0) &&
  726. !isUser
  727. }
  728. onContextMenu={(e) => onRightClick(e, message)}
  729. onDoubleClickCapture={() => {
  730. if (!isMobileScreen) return;
  731. setUserInput(message.content);
  732. }}
  733. fontSize={fontSize}
  734. parentRef={scrollRef}
  735. defaultShow={i >= messages.length - 10}
  736. />
  737. </div>
  738. {!isUser && !message.preview && (
  739. <div className={styles["chat-message-actions"]}>
  740. <div className={styles["chat-message-action-date"]}>
  741. {message.date.toLocaleString()}
  742. </div>
  743. </div>
  744. )}
  745. </div>
  746. </div>
  747. );
  748. })}
  749. </div>
  750. <div className={styles["chat-input-panel"]}>
  751. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  752. <ChatActions
  753. showPromptModal={() => setShowPromptModal(true)}
  754. scrollToBottom={scrollToBottom}
  755. hitBottom={hitBottom}
  756. showPromptHints={() => {
  757. // Click again to close
  758. if (promptHints.length > 0) {
  759. setPromptHints([]);
  760. return;
  761. }
  762. inputRef.current?.focus();
  763. setUserInput("/");
  764. onSearch("");
  765. }}
  766. />
  767. <div className={styles["chat-input-panel-inner"]}>
  768. <textarea
  769. ref={inputRef}
  770. className={styles["chat-input"]}
  771. placeholder={Locale.Chat.Input(submitKey)}
  772. onInput={(e) => onInput(e.currentTarget.value)}
  773. value={userInput}
  774. onKeyDown={onInputKeyDown}
  775. onFocus={() => setAutoScroll(true)}
  776. onBlur={() => setAutoScroll(false)}
  777. rows={inputRows}
  778. autoFocus={autoFocus}
  779. />
  780. <IconButton
  781. icon={<SendWhiteIcon />}
  782. text={Locale.Chat.Send}
  783. className={styles["chat-input-send"]}
  784. type="primary"
  785. onClick={() => doSubmit(userInput)}
  786. />
  787. </div>
  788. </div>
  789. </div>
  790. );
  791. }