chat.tsx 25 KB

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