chat.tsx 24 KB

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