chat.tsx 25 KB

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