chat.tsx 25 KB

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