chat.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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. 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 = ChatControllerPool.hasPending();
  304. const stopAll = () => ChatControllerPool.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 = ChatMessage & { 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. chatStore.updateCurrentSession((session) => {
  444. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  445. session.messages.forEach((m) => {
  446. // check if should stop all stale messages
  447. if (m.streaming && new Date(m.date).getTime() < stopTiming) {
  448. m.isError = false;
  449. m.streaming = false;
  450. }
  451. });
  452. });
  453. ChatControllerPool.stop(sessionIndex, messageId);
  454. };
  455. // check if should send message
  456. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  457. // if ArrowUp and no userInput, fill with last input
  458. if (
  459. e.key === "ArrowUp" &&
  460. userInput.length <= 0 &&
  461. !(e.metaKey || e.altKey || e.ctrlKey)
  462. ) {
  463. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  464. e.preventDefault();
  465. return;
  466. }
  467. if (shouldSubmit(e) && promptHints.length === 0) {
  468. doSubmit(userInput);
  469. e.preventDefault();
  470. }
  471. };
  472. const onRightClick = (e: any, message: ChatMessage) => {
  473. // copy to clipboard
  474. if (selectOrCopy(e.currentTarget, message.content)) {
  475. e.preventDefault();
  476. }
  477. };
  478. const findLastUserIndex = (messageId: number) => {
  479. // find last user input message and resend
  480. let lastUserMessageIndex: number | null = null;
  481. for (let i = 0; i < session.messages.length; i += 1) {
  482. const message = session.messages[i];
  483. if (message.id === messageId) {
  484. break;
  485. }
  486. if (message.role === "user") {
  487. lastUserMessageIndex = i;
  488. }
  489. }
  490. return lastUserMessageIndex;
  491. };
  492. const deleteMessage = (userIndex: number) => {
  493. chatStore.updateCurrentSession((session) =>
  494. session.messages.splice(userIndex, 2),
  495. );
  496. };
  497. const onDelete = (botMessageId: number) => {
  498. const userIndex = findLastUserIndex(botMessageId);
  499. if (userIndex === null) return;
  500. deleteMessage(userIndex);
  501. };
  502. const onResend = (botMessageId: number) => {
  503. // find last user input message and resend
  504. const userIndex = findLastUserIndex(botMessageId);
  505. if (userIndex === null) return;
  506. setIsLoading(true);
  507. const content = session.messages[userIndex].content;
  508. deleteMessage(userIndex);
  509. chatStore.onUserInput(content).then(() => setIsLoading(false));
  510. inputRef.current?.focus();
  511. };
  512. const context: RenderMessage[] = session.mask.context.slice();
  513. const accessStore = useAccessStore();
  514. if (
  515. context.length === 0 &&
  516. session.messages.at(0)?.content !== BOT_HELLO.content
  517. ) {
  518. const copiedHello = Object.assign({}, BOT_HELLO);
  519. if (!accessStore.isAuthorized()) {
  520. copiedHello.content = Locale.Error.Unauthorized;
  521. }
  522. context.push(copiedHello);
  523. }
  524. // preview messages
  525. const messages = context
  526. .concat(session.messages as RenderMessage[])
  527. .concat(
  528. isLoading
  529. ? [
  530. {
  531. ...createMessage({
  532. role: "assistant",
  533. content: "……",
  534. }),
  535. preview: true,
  536. },
  537. ]
  538. : [],
  539. )
  540. .concat(
  541. userInput.length > 0 && config.sendPreviewBubble
  542. ? [
  543. {
  544. ...createMessage({
  545. role: "user",
  546. content: userInput,
  547. }),
  548. preview: true,
  549. },
  550. ]
  551. : [],
  552. );
  553. const [showPromptModal, setShowPromptModal] = useState(false);
  554. const renameSession = () => {
  555. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  556. if (newTopic && newTopic !== session.topic) {
  557. chatStore.updateCurrentSession((session) => (session.topic = newTopic!));
  558. }
  559. };
  560. const location = useLocation();
  561. const isChat = location.pathname === Path.Chat;
  562. const autoFocus = !isMobileScreen || isChat; // only focus in chat page
  563. useCommand({
  564. fill: setUserInput,
  565. submit: (text) => {
  566. doSubmit(text);
  567. },
  568. });
  569. return (
  570. <div className={styles.chat} key={session.id}>
  571. <div className="window-header">
  572. <div className="window-header-title">
  573. <div
  574. className={`window-header-main-title " ${styles["chat-body-title"]}`}
  575. onClickCapture={renameSession}
  576. >
  577. {!session.topic ? DEFAULT_TOPIC : session.topic}
  578. </div>
  579. <div className="window-header-sub-title">
  580. {Locale.Chat.SubTitle(session.messages.length)}
  581. </div>
  582. </div>
  583. <div className="window-actions">
  584. <div className={"window-action-button" + " " + styles.mobile}>
  585. <IconButton
  586. icon={<ReturnIcon />}
  587. bordered
  588. title={Locale.Chat.Actions.ChatList}
  589. onClick={() => navigate(Path.Home)}
  590. />
  591. </div>
  592. <div className="window-action-button">
  593. <IconButton
  594. icon={<RenameIcon />}
  595. bordered
  596. onClick={renameSession}
  597. />
  598. </div>
  599. <div className="window-action-button">
  600. <IconButton
  601. icon={<ExportIcon />}
  602. bordered
  603. title={Locale.Chat.Actions.Export}
  604. onClick={() => {
  605. exportMessages(
  606. session.messages.filter((msg) => !msg.isError),
  607. session.topic,
  608. );
  609. }}
  610. />
  611. </div>
  612. {!isMobileScreen && (
  613. <div className="window-action-button">
  614. <IconButton
  615. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  616. bordered
  617. onClick={() => {
  618. config.update(
  619. (config) => (config.tightBorder = !config.tightBorder),
  620. );
  621. }}
  622. />
  623. </div>
  624. )}
  625. </div>
  626. <PromptToast
  627. showToast={!hitBottom}
  628. showModal={showPromptModal}
  629. setShowModal={setShowPromptModal}
  630. />
  631. </div>
  632. <div
  633. className={styles["chat-body"]}
  634. ref={scrollRef}
  635. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  636. onMouseDown={() => inputRef.current?.blur()}
  637. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  638. onTouchStart={() => {
  639. inputRef.current?.blur();
  640. setAutoScroll(false);
  641. }}
  642. >
  643. {messages.map((message, i) => {
  644. const isUser = message.role === "user";
  645. const showActions =
  646. !isUser &&
  647. i > 0 &&
  648. !(message.preview || message.content.length === 0);
  649. const showTyping = message.preview || message.streaming;
  650. return (
  651. <div
  652. key={i}
  653. className={
  654. isUser ? styles["chat-message-user"] : styles["chat-message"]
  655. }
  656. >
  657. <div className={styles["chat-message-container"]}>
  658. <div className={styles["chat-message-avatar"]}>
  659. {message.role === "user" ? (
  660. <Avatar avatar={config.avatar} />
  661. ) : (
  662. <MaskAvatar mask={session.mask} />
  663. )}
  664. </div>
  665. {showTyping && (
  666. <div className={styles["chat-message-status"]}>
  667. {Locale.Chat.Typing}
  668. </div>
  669. )}
  670. <div className={styles["chat-message-item"]}>
  671. {showActions && (
  672. <div className={styles["chat-message-top-actions"]}>
  673. {message.streaming ? (
  674. <div
  675. className={styles["chat-message-top-action"]}
  676. onClick={() => onUserStop(message.id ?? i)}
  677. >
  678. {Locale.Chat.Actions.Stop}
  679. </div>
  680. ) : (
  681. <>
  682. <div
  683. className={styles["chat-message-top-action"]}
  684. onClick={() => onDelete(message.id ?? i)}
  685. >
  686. {Locale.Chat.Actions.Delete}
  687. </div>
  688. <div
  689. className={styles["chat-message-top-action"]}
  690. onClick={() => onResend(message.id ?? i)}
  691. >
  692. {Locale.Chat.Actions.Retry}
  693. </div>
  694. </>
  695. )}
  696. <div
  697. className={styles["chat-message-top-action"]}
  698. onClick={() => copyToClipboard(message.content)}
  699. >
  700. {Locale.Chat.Actions.Copy}
  701. </div>
  702. </div>
  703. )}
  704. <Markdown
  705. content={message.content}
  706. loading={
  707. (message.preview || message.content.length === 0) &&
  708. !isUser
  709. }
  710. onContextMenu={(e) => onRightClick(e, message)}
  711. onDoubleClickCapture={() => {
  712. if (!isMobileScreen) return;
  713. setUserInput(message.content);
  714. }}
  715. fontSize={fontSize}
  716. parentRef={scrollRef}
  717. defaultShow={i >= messages.length - 10}
  718. />
  719. </div>
  720. {!isUser && !message.preview && (
  721. <div className={styles["chat-message-actions"]}>
  722. <div className={styles["chat-message-action-date"]}>
  723. {message.date.toLocaleString()}
  724. </div>
  725. </div>
  726. )}
  727. </div>
  728. </div>
  729. );
  730. })}
  731. </div>
  732. <div className={styles["chat-input-panel"]}>
  733. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  734. <ChatActions
  735. showPromptModal={() => setShowPromptModal(true)}
  736. scrollToBottom={scrollToBottom}
  737. hitBottom={hitBottom}
  738. showPromptHints={() => {
  739. // Click again to close
  740. if (promptHints.length > 0) {
  741. setPromptHints([]);
  742. return;
  743. }
  744. inputRef.current?.focus();
  745. setUserInput("/");
  746. onSearch("");
  747. }}
  748. />
  749. <div className={styles["chat-input-panel-inner"]}>
  750. <textarea
  751. ref={inputRef}
  752. className={styles["chat-input"]}
  753. placeholder={Locale.Chat.Input(submitKey)}
  754. onInput={(e) => onInput(e.currentTarget.value)}
  755. value={userInput}
  756. onKeyDown={onInputKeyDown}
  757. onFocus={() => setAutoScroll(true)}
  758. onBlur={() => setAutoScroll(false)}
  759. rows={inputRows}
  760. autoFocus={autoFocus}
  761. />
  762. <IconButton
  763. icon={<SendWhiteIcon />}
  764. text={Locale.Chat.Send}
  765. className={styles["chat-input-send"]}
  766. type="primary"
  767. onClick={() => doSubmit(userInput)}
  768. />
  769. </div>
  770. </div>
  771. </div>
  772. );
  773. }