chat.tsx 25 KB

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