chat.tsx 24 KB

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