chat.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. ROLES,
  27. createMessage,
  28. useAccessStore,
  29. Theme,
  30. useAppConfig,
  31. ModelConfig,
  32. DEFAULT_TOPIC,
  33. } from "../store";
  34. import {
  35. copyToClipboard,
  36. downloadAs,
  37. selectOrCopy,
  38. autoGrowTextArea,
  39. useMobileScreen,
  40. } from "../utils";
  41. import dynamic from "next/dynamic";
  42. import { ControllerPool } from "../requests";
  43. import { Prompt, usePromptStore } from "../store/prompt";
  44. import Locale from "../locales";
  45. import { IconButton } from "./button";
  46. import styles from "./home.module.scss";
  47. import chatStyle from "./chat.module.scss";
  48. import { ListItem, Modal, showModal } from "./ui-lib";
  49. import { useLocation, useNavigate } from "react-router-dom";
  50. import { Path } from "../constant";
  51. import { Avatar } from "./emoji";
  52. import { MaskAvatar, MaskConfig } from "./mask";
  53. import {
  54. DEFAULT_MASK_AVATAR,
  55. DEFAULT_MASK_ID,
  56. useMaskStore,
  57. } from "../store/mask";
  58. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  59. loading: () => <LoadingIcon />,
  60. });
  61. function exportMessages(messages: Message[], topic: string) {
  62. const mdText =
  63. `# ${topic}\n\n` +
  64. messages
  65. .map((m) => {
  66. return m.role === "user"
  67. ? `## ${Locale.Export.MessageFromYou}:\n${m.content}`
  68. : `## ${Locale.Export.MessageFromChatGPT}:\n${m.content.trim()}`;
  69. })
  70. .join("\n\n");
  71. const filename = `${topic}.md`;
  72. showModal({
  73. title: Locale.Export.Title,
  74. children: (
  75. <div className="markdown-body">
  76. <pre className={styles["export-content"]}>{mdText}</pre>
  77. </div>
  78. ),
  79. actions: [
  80. <IconButton
  81. key="copy"
  82. icon={<CopyIcon />}
  83. bordered
  84. text={Locale.Export.Copy}
  85. onClick={() => copyToClipboard(mdText)}
  86. />,
  87. <IconButton
  88. key="download"
  89. icon={<DownloadIcon />}
  90. bordered
  91. text={Locale.Export.Download}
  92. onClick={() => downloadAs(mdText, filename)}
  93. />,
  94. ],
  95. });
  96. }
  97. export function SessionConfigModel(props: { onClose: () => void }) {
  98. const chatStore = useChatStore();
  99. const session = chatStore.currentSession();
  100. const maskStore = useMaskStore();
  101. const navigate = useNavigate();
  102. return (
  103. <div className="modal-mask">
  104. <Modal
  105. title={Locale.Context.Edit}
  106. onClose={() => props.onClose()}
  107. actions={[
  108. <IconButton
  109. key="reset"
  110. icon={<ResetIcon />}
  111. bordered
  112. text={Locale.Chat.Config.Reset}
  113. onClick={() =>
  114. confirm(Locale.Memory.ResetConfirm) && chatStore.resetSession()
  115. }
  116. />,
  117. <IconButton
  118. key="copy"
  119. icon={<CopyIcon />}
  120. bordered
  121. text={Locale.Chat.Config.SaveAs}
  122. onClick={() => {
  123. navigate(Path.Masks);
  124. setTimeout(() => {
  125. maskStore.create(session.mask);
  126. }, 500);
  127. }}
  128. />,
  129. ]}
  130. >
  131. <MaskConfig
  132. mask={session.mask}
  133. updateMask={(updater) => {
  134. const mask = { ...session.mask };
  135. updater(mask);
  136. chatStore.updateCurrentSession((session) => (session.mask = mask));
  137. }}
  138. extraListItems={
  139. session.mask.modelConfig.sendMemory ? (
  140. <ListItem
  141. title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`}
  142. subTitle={session.memoryPrompt || Locale.Memory.EmptyContent}
  143. ></ListItem>
  144. ) : (
  145. <></>
  146. )
  147. }
  148. ></MaskConfig>
  149. </Modal>
  150. </div>
  151. );
  152. }
  153. function PromptToast(props: {
  154. showToast?: boolean;
  155. showModal?: boolean;
  156. setShowModal: (_: boolean) => void;
  157. }) {
  158. const chatStore = useChatStore();
  159. const session = chatStore.currentSession();
  160. const context = session.mask.context;
  161. return (
  162. <div className={chatStyle["prompt-toast"]} key="prompt-toast">
  163. {props.showToast && (
  164. <div
  165. className={chatStyle["prompt-toast-inner"] + " clickable"}
  166. role="button"
  167. onClick={() => props.setShowModal(true)}
  168. >
  169. <BrainIcon />
  170. <span className={chatStyle["prompt-toast-content"]}>
  171. {Locale.Context.Toast(context.length)}
  172. </span>
  173. </div>
  174. )}
  175. {props.showModal && (
  176. <SessionConfigModel onClose={() => props.setShowModal(false)} />
  177. )}
  178. </div>
  179. );
  180. }
  181. function useSubmitHandler() {
  182. const config = useAppConfig();
  183. const submitKey = config.submitKey;
  184. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  185. if (e.key !== "Enter") return false;
  186. if (e.key === "Enter" && e.nativeEvent.isComposing) return false;
  187. return (
  188. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  189. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  190. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  191. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  192. (config.submitKey === SubmitKey.Enter &&
  193. !e.altKey &&
  194. !e.ctrlKey &&
  195. !e.shiftKey &&
  196. !e.metaKey)
  197. );
  198. };
  199. return {
  200. submitKey,
  201. shouldSubmit,
  202. };
  203. }
  204. export function PromptHints(props: {
  205. prompts: Prompt[];
  206. onPromptSelect: (prompt: Prompt) => void;
  207. }) {
  208. const noPrompts = props.prompts.length === 0;
  209. const [selectIndex, setSelectIndex] = useState(0);
  210. const selectedRef = useRef<HTMLDivElement>(null);
  211. useEffect(() => {
  212. setSelectIndex(0);
  213. }, [props.prompts.length]);
  214. useEffect(() => {
  215. const onKeyDown = (e: KeyboardEvent) => {
  216. if (noPrompts) return;
  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 = ControllerPool.hasPending();
  306. const stopAll = () => ControllerPool.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 = Message & { 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 [beforeInput, setBeforeInput] = useState("");
  374. const [isLoading, setIsLoading] = useState(false);
  375. const { submitKey, shouldSubmit } = useSubmitHandler();
  376. const { scrollRef, setAutoScroll, scrollToBottom } = useScrollToBottom();
  377. const [hitBottom, setHitBottom] = useState(true);
  378. const isMobileScreen = useMobileScreen();
  379. const navigate = useNavigate();
  380. const onChatBodyScroll = (e: HTMLElement) => {
  381. const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 100;
  382. setHitBottom(isTouchBottom);
  383. };
  384. // prompt hints
  385. const promptStore = usePromptStore();
  386. const [promptHints, setPromptHints] = useState<Prompt[]>([]);
  387. const onSearch = useDebouncedCallback(
  388. (text: string) => {
  389. setPromptHints(promptStore.search(text));
  390. },
  391. 100,
  392. { leading: true, trailing: true },
  393. );
  394. const onPromptSelect = (prompt: Prompt) => {
  395. setPromptHints([]);
  396. inputRef.current?.focus();
  397. setTimeout(() => setUserInput(prompt.content), 60);
  398. };
  399. // auto grow input
  400. const [inputRows, setInputRows] = useState(2);
  401. const measure = useDebouncedCallback(
  402. () => {
  403. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  404. const inputRows = Math.min(
  405. 20,
  406. Math.max(2 + Number(!isMobileScreen), rows),
  407. );
  408. setInputRows(inputRows);
  409. },
  410. 100,
  411. {
  412. leading: true,
  413. trailing: true,
  414. },
  415. );
  416. // eslint-disable-next-line react-hooks/exhaustive-deps
  417. useEffect(measure, [userInput]);
  418. // only search prompts when user input is short
  419. const SEARCH_TEXT_LIMIT = 30;
  420. const onInput = (text: string) => {
  421. setUserInput(text);
  422. const n = text.trim().length;
  423. // clear search results
  424. if (n === 0) {
  425. setPromptHints([]);
  426. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  427. // check if need to trigger auto completion
  428. if (text.startsWith("/")) {
  429. let searchText = text.slice(1);
  430. onSearch(searchText);
  431. }
  432. }
  433. };
  434. // submit user input
  435. const onUserSubmit = () => {
  436. if (userInput.trim() === "") return;
  437. setIsLoading(true);
  438. chatStore.onUserInput(userInput).then(() => setIsLoading(false));
  439. setBeforeInput(userInput);
  440. setUserInput("");
  441. setPromptHints([]);
  442. if (!isMobileScreen) inputRef.current?.focus();
  443. setAutoScroll(true);
  444. };
  445. // stop response
  446. const onUserStop = (messageId: number) => {
  447. ControllerPool.stop(sessionIndex, messageId);
  448. };
  449. // check if should send message
  450. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  451. // if ArrowUp and no userInput
  452. if (e.key === "ArrowUp" && userInput.length <= 0) {
  453. setUserInput(beforeInput);
  454. e.preventDefault();
  455. return;
  456. }
  457. if (shouldSubmit(e)) {
  458. onUserSubmit();
  459. e.preventDefault();
  460. }
  461. };
  462. const onRightClick = (e: any, message: Message) => {
  463. // auto fill user input
  464. if (message.role === "user") {
  465. setUserInput(message.content);
  466. }
  467. // copy to clipboard
  468. if (selectOrCopy(e.currentTarget, message.content)) {
  469. e.preventDefault();
  470. }
  471. };
  472. const findLastUserIndex = (messageId: number) => {
  473. // find last user input message and resend
  474. let lastUserMessageIndex: number | null = null;
  475. for (let i = 0; i < session.messages.length; i += 1) {
  476. const message = session.messages[i];
  477. if (message.id === messageId) {
  478. break;
  479. }
  480. if (message.role === "user") {
  481. lastUserMessageIndex = i;
  482. }
  483. }
  484. return lastUserMessageIndex;
  485. };
  486. const deleteMessage = (userIndex: number) => {
  487. chatStore.updateCurrentSession((session) =>
  488. session.messages.splice(userIndex, 2),
  489. );
  490. };
  491. const onDelete = (botMessageId: number) => {
  492. const userIndex = findLastUserIndex(botMessageId);
  493. if (userIndex === null) return;
  494. deleteMessage(userIndex);
  495. };
  496. const onResend = (botMessageId: number) => {
  497. // find last user input message and resend
  498. const userIndex = findLastUserIndex(botMessageId);
  499. if (userIndex === null) return;
  500. setIsLoading(true);
  501. const content = session.messages[userIndex].content;
  502. deleteMessage(userIndex);
  503. chatStore.onUserInput(content).then(() => setIsLoading(false));
  504. inputRef.current?.focus();
  505. };
  506. const context: RenderMessage[] = session.mask.context.slice();
  507. const accessStore = useAccessStore();
  508. if (
  509. context.length === 0 &&
  510. session.messages.at(0)?.content !== BOT_HELLO.content
  511. ) {
  512. const copiedHello = Object.assign({}, BOT_HELLO);
  513. if (!accessStore.isAuthorized()) {
  514. copiedHello.content = Locale.Error.Unauthorized;
  515. }
  516. context.push(copiedHello);
  517. }
  518. // preview messages
  519. const messages = context
  520. .concat(session.messages as RenderMessage[])
  521. .concat(
  522. isLoading
  523. ? [
  524. {
  525. ...createMessage({
  526. role: "assistant",
  527. content: "……",
  528. }),
  529. preview: true,
  530. },
  531. ]
  532. : [],
  533. )
  534. .concat(
  535. userInput.length > 0 && config.sendPreviewBubble
  536. ? [
  537. {
  538. ...createMessage({
  539. role: "user",
  540. content: userInput,
  541. }),
  542. preview: true,
  543. },
  544. ]
  545. : [],
  546. );
  547. const [showPromptModal, setShowPromptModal] = useState(false);
  548. const renameSession = () => {
  549. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  550. if (newTopic && newTopic !== session.topic) {
  551. chatStore.updateCurrentSession((session) => (session.topic = newTopic!));
  552. }
  553. };
  554. const location = useLocation();
  555. const isChat = location.pathname === Path.Chat;
  556. const autoFocus = !isMobileScreen || isChat; // only focus in chat page
  557. return (
  558. <div className={styles.chat} key={session.id}>
  559. <div className="window-header">
  560. <div className="window-header-title">
  561. <div
  562. className={`window-header-main-title " ${styles["chat-body-title"]}`}
  563. onClickCapture={renameSession}
  564. >
  565. {!session.topic ? DEFAULT_TOPIC : session.topic}
  566. </div>
  567. <div className="window-header-sub-title">
  568. {Locale.Chat.SubTitle(session.messages.length)}
  569. </div>
  570. </div>
  571. <div className="window-actions">
  572. <div className={"window-action-button" + " " + styles.mobile}>
  573. <IconButton
  574. icon={<ReturnIcon />}
  575. bordered
  576. title={Locale.Chat.Actions.ChatList}
  577. onClick={() => navigate(Path.Home)}
  578. />
  579. </div>
  580. <div className="window-action-button">
  581. <IconButton
  582. icon={<RenameIcon />}
  583. bordered
  584. onClick={renameSession}
  585. />
  586. </div>
  587. <div className="window-action-button">
  588. <IconButton
  589. icon={<ExportIcon />}
  590. bordered
  591. title={Locale.Chat.Actions.Export}
  592. onClick={() => {
  593. exportMessages(
  594. session.messages.filter((msg) => !msg.isError),
  595. session.topic,
  596. );
  597. }}
  598. />
  599. </div>
  600. {!isMobileScreen && (
  601. <div className="window-action-button">
  602. <IconButton
  603. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  604. bordered
  605. onClick={() => {
  606. config.update(
  607. (config) => (config.tightBorder = !config.tightBorder),
  608. );
  609. }}
  610. />
  611. </div>
  612. )}
  613. </div>
  614. <PromptToast
  615. showToast={!hitBottom}
  616. showModal={showPromptModal}
  617. setShowModal={setShowPromptModal}
  618. />
  619. </div>
  620. <div
  621. className={styles["chat-body"]}
  622. ref={scrollRef}
  623. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  624. onMouseDown={() => inputRef.current?.blur()}
  625. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  626. onTouchStart={() => {
  627. inputRef.current?.blur();
  628. setAutoScroll(false);
  629. }}
  630. >
  631. {messages.map((message, i) => {
  632. const isUser = message.role === "user";
  633. const showActions =
  634. !isUser &&
  635. i > 0 &&
  636. !(message.preview || message.content.length === 0);
  637. const showTyping = message.preview || message.streaming;
  638. return (
  639. <div
  640. key={i}
  641. className={
  642. isUser ? styles["chat-message-user"] : styles["chat-message"]
  643. }
  644. >
  645. <div className={styles["chat-message-container"]}>
  646. <div className={styles["chat-message-avatar"]}>
  647. {message.role === "user" ? (
  648. <Avatar avatar={config.avatar} />
  649. ) : (
  650. <MaskAvatar mask={session.mask} />
  651. )}
  652. </div>
  653. {showTyping && (
  654. <div className={styles["chat-message-status"]}>
  655. {Locale.Chat.Typing}
  656. </div>
  657. )}
  658. <div className={styles["chat-message-item"]}>
  659. {showActions && (
  660. <div className={styles["chat-message-top-actions"]}>
  661. {message.streaming ? (
  662. <div
  663. className={styles["chat-message-top-action"]}
  664. onClick={() => onUserStop(message.id ?? i)}
  665. >
  666. {Locale.Chat.Actions.Stop}
  667. </div>
  668. ) : (
  669. <>
  670. <div
  671. className={styles["chat-message-top-action"]}
  672. onClick={() => onDelete(message.id ?? i)}
  673. >
  674. {Locale.Chat.Actions.Delete}
  675. </div>
  676. <div
  677. className={styles["chat-message-top-action"]}
  678. onClick={() => onResend(message.id ?? i)}
  679. >
  680. {Locale.Chat.Actions.Retry}
  681. </div>
  682. </>
  683. )}
  684. <div
  685. className={styles["chat-message-top-action"]}
  686. onClick={() => copyToClipboard(message.content)}
  687. >
  688. {Locale.Chat.Actions.Copy}
  689. </div>
  690. </div>
  691. )}
  692. <Markdown
  693. content={message.content}
  694. loading={
  695. (message.preview || message.content.length === 0) &&
  696. !isUser
  697. }
  698. onContextMenu={(e) => onRightClick(e, message)}
  699. onDoubleClickCapture={() => {
  700. if (!isMobileScreen) return;
  701. setUserInput(message.content);
  702. }}
  703. fontSize={fontSize}
  704. parentRef={scrollRef}
  705. defaultShow={i >= messages.length - 10}
  706. />
  707. </div>
  708. {!isUser && !message.preview && (
  709. <div className={styles["chat-message-actions"]}>
  710. <div className={styles["chat-message-action-date"]}>
  711. {message.date.toLocaleString()}
  712. </div>
  713. </div>
  714. )}
  715. </div>
  716. </div>
  717. );
  718. })}
  719. </div>
  720. <div className={styles["chat-input-panel"]}>
  721. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  722. <ChatActions
  723. showPromptModal={() => setShowPromptModal(true)}
  724. scrollToBottom={scrollToBottom}
  725. hitBottom={hitBottom}
  726. showPromptHints={() => {
  727. inputRef.current?.focus();
  728. onSearch("");
  729. }}
  730. />
  731. <div className={styles["chat-input-panel-inner"]}>
  732. <textarea
  733. ref={inputRef}
  734. className={styles["chat-input"]}
  735. placeholder={Locale.Chat.Input(submitKey)}
  736. onInput={(e) => onInput(e.currentTarget.value)}
  737. value={userInput}
  738. onKeyDown={onInputKeyDown}
  739. onFocus={() => setAutoScroll(true)}
  740. onBlur={() => setAutoScroll(false)}
  741. rows={inputRows}
  742. autoFocus={autoFocus}
  743. />
  744. <IconButton
  745. icon={<SendWhiteIcon />}
  746. text={Locale.Chat.Send}
  747. className={styles["chat-input-send"]}
  748. type="primary"
  749. onClick={onUserSubmit}
  750. />
  751. </div>
  752. </div>
  753. </div>
  754. );
  755. }