chat.tsx 25 KB

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