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