chat.tsx 25 KB

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