chat.tsx 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  1. import { useDebouncedCallback } from "use-debounce";
  2. import React, {
  3. useState,
  4. useRef,
  5. useEffect,
  6. useMemo,
  7. useCallback,
  8. Fragment,
  9. RefObject,
  10. } from "react";
  11. import SendWhiteIcon from "../icons/send-white.svg";
  12. import BrainIcon from "../icons/brain.svg";
  13. import RenameIcon from "../icons/rename.svg";
  14. import ExportIcon from "../icons/share.svg";
  15. import ReturnIcon from "../icons/return.svg";
  16. import CopyIcon from "../icons/copy.svg";
  17. import LoadingIcon from "../icons/three-dots.svg";
  18. import LoadingButtonIcon from "../icons/loading.svg";
  19. import PromptIcon from "../icons/prompt.svg";
  20. import MaskIcon from "../icons/mask.svg";
  21. import MaxIcon from "../icons/max.svg";
  22. import MinIcon from "../icons/min.svg";
  23. import ResetIcon from "../icons/reload.svg";
  24. import BreakIcon from "../icons/break.svg";
  25. import SettingsIcon from "../icons/chat-settings.svg";
  26. import DeleteIcon from "../icons/clear.svg";
  27. import PinIcon from "../icons/pin.svg";
  28. import EditIcon from "../icons/rename.svg";
  29. import ConfirmIcon from "../icons/confirm.svg";
  30. import CancelIcon from "../icons/cancel.svg";
  31. import ImageIcon from "../icons/image.svg";
  32. import LightIcon from "../icons/light.svg";
  33. import DarkIcon from "../icons/dark.svg";
  34. import AutoIcon from "../icons/auto.svg";
  35. import BottomIcon from "../icons/bottom.svg";
  36. import StopIcon from "../icons/pause.svg";
  37. import RobotIcon from "../icons/robot.svg";
  38. import {
  39. ChatMessage,
  40. SubmitKey,
  41. useChatStore,
  42. BOT_HELLO,
  43. createMessage,
  44. useAccessStore,
  45. Theme,
  46. useAppConfig,
  47. DEFAULT_TOPIC,
  48. ModelType,
  49. } from "../store";
  50. import {
  51. copyToClipboard,
  52. selectOrCopy,
  53. autoGrowTextArea,
  54. useMobileScreen,
  55. getMessageTextContent,
  56. getMessageImages,
  57. isVisionModel,
  58. compressImage,
  59. } from "../utils";
  60. import dynamic from "next/dynamic";
  61. import { ChatControllerPool } from "../client/controller";
  62. import { Prompt, usePromptStore } from "../store/prompt";
  63. import Locale from "../locales";
  64. import { IconButton } from "./button";
  65. import styles from "./chat.module.scss";
  66. import {
  67. List,
  68. ListItem,
  69. Modal,
  70. Selector,
  71. showConfirm,
  72. showPrompt,
  73. showToast,
  74. } from "./ui-lib";
  75. import { useNavigate } from "react-router-dom";
  76. import {
  77. CHAT_PAGE_SIZE,
  78. LAST_INPUT_KEY,
  79. Path,
  80. REQUEST_TIMEOUT_MS,
  81. UNFINISHED_INPUT,
  82. } from "../constant";
  83. import { Avatar } from "./emoji";
  84. import { ContextPrompts, MaskAvatar, MaskConfig } from "./mask";
  85. import { useMaskStore } from "../store/mask";
  86. import { ChatCommandPrefix, useChatCommand, useCommand } from "../command";
  87. import { prettyObject } from "../utils/format";
  88. import { ExportMessageModal } from "./exporter";
  89. import { getClientConfig } from "../config/client";
  90. import { useAllModels } from "../utils/hooks";
  91. import { MultimodalContent } from "../client/api";
  92. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  93. loading: () => <LoadingIcon />,
  94. });
  95. export function SessionConfigModel(props: { onClose: () => void }) {
  96. const chatStore = useChatStore();
  97. const session = chatStore.currentSession();
  98. const maskStore = useMaskStore();
  99. const navigate = useNavigate();
  100. return (
  101. <div className="modal-mask">
  102. <Modal
  103. title={Locale.Context.Edit}
  104. onClose={() => props.onClose()}
  105. actions={[
  106. <IconButton
  107. key="reset"
  108. icon={<ResetIcon />}
  109. bordered
  110. text={Locale.Chat.Config.Reset}
  111. onClick={async () => {
  112. if (await showConfirm(Locale.Memory.ResetConfirm)) {
  113. chatStore.updateCurrentSession(
  114. (session) => (session.memoryPrompt = ""),
  115. );
  116. }
  117. }}
  118. />,
  119. <IconButton
  120. key="copy"
  121. icon={<CopyIcon />}
  122. bordered
  123. text={Locale.Chat.Config.SaveAs}
  124. onClick={() => {
  125. navigate(Path.Masks);
  126. setTimeout(() => {
  127. maskStore.create(session.mask);
  128. }, 500);
  129. }}
  130. />,
  131. ]}
  132. >
  133. <MaskConfig
  134. mask={session.mask}
  135. updateMask={(updater) => {
  136. const mask = { ...session.mask };
  137. updater(mask);
  138. chatStore.updateCurrentSession((session) => (session.mask = mask));
  139. }}
  140. shouldSyncFromGlobal
  141. extraListItems={
  142. session.mask.modelConfig.sendMemory ? (
  143. <ListItem
  144. className="copyable"
  145. title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`}
  146. subTitle={session.memoryPrompt || Locale.Memory.EmptyContent}
  147. ></ListItem>
  148. ) : (
  149. <></>
  150. )
  151. }
  152. ></MaskConfig>
  153. </Modal>
  154. </div>
  155. );
  156. }
  157. function PromptToast(props: {
  158. showToast?: boolean;
  159. showModal?: boolean;
  160. setShowModal: (_: boolean) => void;
  161. }) {
  162. const chatStore = useChatStore();
  163. const session = chatStore.currentSession();
  164. const context = session.mask.context;
  165. return (
  166. <div className={styles["prompt-toast"]} key="prompt-toast">
  167. {props.showToast && (
  168. <div
  169. className={styles["prompt-toast-inner"] + " clickable"}
  170. role="button"
  171. onClick={() => props.setShowModal(true)}
  172. >
  173. <BrainIcon />
  174. <span className={styles["prompt-toast-content"]}>
  175. {Locale.Context.Toast(context.length)}
  176. </span>
  177. </div>
  178. )}
  179. {props.showModal && (
  180. <SessionConfigModel onClose={() => props.setShowModal(false)} />
  181. )}
  182. </div>
  183. );
  184. }
  185. function useSubmitHandler() {
  186. const config = useAppConfig();
  187. const submitKey = config.submitKey;
  188. const isComposing = useRef(false);
  189. useEffect(() => {
  190. const onCompositionStart = () => {
  191. isComposing.current = true;
  192. };
  193. const onCompositionEnd = () => {
  194. isComposing.current = false;
  195. };
  196. window.addEventListener("compositionstart", onCompositionStart);
  197. window.addEventListener("compositionend", onCompositionEnd);
  198. return () => {
  199. window.removeEventListener("compositionstart", onCompositionStart);
  200. window.removeEventListener("compositionend", onCompositionEnd);
  201. };
  202. }, []);
  203. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  204. // Fix Chinese input method "Enter" on Safari
  205. if (e.keyCode == 229) return false;
  206. if (e.key !== "Enter") return false;
  207. if (e.key === "Enter" && (e.nativeEvent.isComposing || isComposing.current))
  208. return false;
  209. return (
  210. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  211. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  212. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  213. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  214. (config.submitKey === SubmitKey.Enter &&
  215. !e.altKey &&
  216. !e.ctrlKey &&
  217. !e.shiftKey &&
  218. !e.metaKey)
  219. );
  220. };
  221. return {
  222. submitKey,
  223. shouldSubmit,
  224. };
  225. }
  226. export type RenderPompt = Pick<Prompt, "title" | "content">;
  227. export function PromptHints(props: {
  228. prompts: RenderPompt[];
  229. onPromptSelect: (prompt: RenderPompt) => void;
  230. }) {
  231. const noPrompts = props.prompts.length === 0;
  232. const [selectIndex, setSelectIndex] = useState(0);
  233. const selectedRef = useRef<HTMLDivElement>(null);
  234. useEffect(() => {
  235. setSelectIndex(0);
  236. }, [props.prompts.length]);
  237. useEffect(() => {
  238. const onKeyDown = (e: KeyboardEvent) => {
  239. if (noPrompts || e.metaKey || e.altKey || e.ctrlKey) {
  240. return;
  241. }
  242. // arrow up / down to select prompt
  243. const changeIndex = (delta: number) => {
  244. e.stopPropagation();
  245. e.preventDefault();
  246. const nextIndex = Math.max(
  247. 0,
  248. Math.min(props.prompts.length - 1, selectIndex + delta),
  249. );
  250. setSelectIndex(nextIndex);
  251. selectedRef.current?.scrollIntoView({
  252. block: "center",
  253. });
  254. };
  255. if (e.key === "ArrowUp") {
  256. changeIndex(1);
  257. } else if (e.key === "ArrowDown") {
  258. changeIndex(-1);
  259. } else if (e.key === "Enter") {
  260. const selectedPrompt = props.prompts.at(selectIndex);
  261. if (selectedPrompt) {
  262. props.onPromptSelect(selectedPrompt);
  263. }
  264. }
  265. };
  266. window.addEventListener("keydown", onKeyDown);
  267. return () => window.removeEventListener("keydown", onKeyDown);
  268. // eslint-disable-next-line react-hooks/exhaustive-deps
  269. }, [props.prompts.length, selectIndex]);
  270. if (noPrompts) return null;
  271. return (
  272. <div className={styles["prompt-hints"]}>
  273. {props.prompts.map((prompt, i) => (
  274. <div
  275. ref={i === selectIndex ? selectedRef : null}
  276. className={
  277. styles["prompt-hint"] +
  278. ` ${i === selectIndex ? styles["prompt-hint-selected"] : ""}`
  279. }
  280. key={prompt.title + i.toString()}
  281. onClick={() => props.onPromptSelect(prompt)}
  282. onMouseEnter={() => setSelectIndex(i)}
  283. >
  284. <div className={styles["hint-title"]}>{prompt.title}</div>
  285. <div className={styles["hint-content"]}>{prompt.content}</div>
  286. </div>
  287. ))}
  288. </div>
  289. );
  290. }
  291. function ClearContextDivider() {
  292. const chatStore = useChatStore();
  293. return (
  294. <div
  295. className={styles["clear-context"]}
  296. onClick={() =>
  297. chatStore.updateCurrentSession(
  298. (session) => (session.clearContextIndex = undefined),
  299. )
  300. }
  301. >
  302. <div className={styles["clear-context-tips"]}>{Locale.Context.Clear}</div>
  303. <div className={styles["clear-context-revert-btn"]}>
  304. {Locale.Context.Revert}
  305. </div>
  306. </div>
  307. );
  308. }
  309. function ChatAction(props: {
  310. text: string;
  311. icon: JSX.Element;
  312. onClick: () => void;
  313. }) {
  314. const iconRef = useRef<HTMLDivElement>(null);
  315. const textRef = useRef<HTMLDivElement>(null);
  316. const [width, setWidth] = useState({
  317. full: 16,
  318. icon: 16,
  319. });
  320. function updateWidth() {
  321. if (!iconRef.current || !textRef.current) return;
  322. const getWidth = (dom: HTMLDivElement) => dom.getBoundingClientRect().width;
  323. const textWidth = getWidth(textRef.current);
  324. const iconWidth = getWidth(iconRef.current);
  325. setWidth({
  326. full: textWidth + iconWidth,
  327. icon: iconWidth,
  328. });
  329. }
  330. return (
  331. <div
  332. className={`${styles["chat-input-action"]} clickable`}
  333. onClick={() => {
  334. props.onClick();
  335. setTimeout(updateWidth, 1);
  336. }}
  337. onMouseEnter={updateWidth}
  338. onTouchStart={updateWidth}
  339. style={
  340. {
  341. "--icon-width": `${width.icon}px`,
  342. "--full-width": `${width.full}px`,
  343. } as React.CSSProperties
  344. }
  345. >
  346. <div ref={iconRef} className={styles["icon"]}>
  347. {props.icon}
  348. </div>
  349. <div className={styles["text"]} ref={textRef}>
  350. {props.text}
  351. </div>
  352. </div>
  353. );
  354. }
  355. function useScrollToBottom(
  356. scrollRef: RefObject<HTMLDivElement>,
  357. detach: boolean = false,
  358. ) {
  359. // for auto-scroll
  360. const [autoScroll, setAutoScroll] = useState(true);
  361. function scrollDomToBottom() {
  362. const dom = scrollRef.current;
  363. if (dom) {
  364. requestAnimationFrame(() => {
  365. setAutoScroll(true);
  366. dom.scrollTo(0, dom.scrollHeight);
  367. });
  368. }
  369. }
  370. // auto scroll
  371. useEffect(() => {
  372. if (autoScroll && !detach) {
  373. scrollDomToBottom();
  374. }
  375. });
  376. return {
  377. scrollRef,
  378. autoScroll,
  379. setAutoScroll,
  380. scrollDomToBottom,
  381. };
  382. }
  383. export function ChatActions(props: {
  384. uploadImage: () => void;
  385. setAttachImages: (images: string[]) => void;
  386. setUploading: (uploading: boolean) => void;
  387. showPromptModal: () => void;
  388. scrollToBottom: () => void;
  389. showPromptHints: () => void;
  390. hitBottom: boolean;
  391. uploading: boolean;
  392. }) {
  393. const config = useAppConfig();
  394. const navigate = useNavigate();
  395. const chatStore = useChatStore();
  396. // switch themes
  397. const theme = config.theme;
  398. function nextTheme() {
  399. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  400. const themeIndex = themes.indexOf(theme);
  401. const nextIndex = (themeIndex + 1) % themes.length;
  402. const nextTheme = themes[nextIndex];
  403. config.update((config) => (config.theme = nextTheme));
  404. }
  405. // stop all responses
  406. const couldStop = ChatControllerPool.hasPending();
  407. const stopAll = () => ChatControllerPool.stopAll();
  408. // switch model
  409. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  410. const allModels = useAllModels();
  411. const models = useMemo(
  412. () => allModels.filter((m) => m.available),
  413. [allModels],
  414. );
  415. const [showModelSelector, setShowModelSelector] = useState(false);
  416. const [showUploadImage, setShowUploadImage] = useState(false);
  417. useEffect(() => {
  418. const show = isVisionModel(currentModel);
  419. setShowUploadImage(show);
  420. if (!show) {
  421. props.setAttachImages([]);
  422. props.setUploading(false);
  423. }
  424. // if current model is not available
  425. // switch to first available model
  426. const isUnavaliableModel = !models.some((m) => m.name === currentModel);
  427. if (isUnavaliableModel && models.length > 0) {
  428. const nextModel = models[0].name as ModelType;
  429. chatStore.updateCurrentSession(
  430. (session) => (session.mask.modelConfig.model = nextModel),
  431. );
  432. showToast(nextModel);
  433. }
  434. }, [chatStore, currentModel, models]);
  435. return (
  436. <div className={styles["chat-input-actions"]}>
  437. {couldStop && (
  438. <ChatAction
  439. onClick={stopAll}
  440. text={Locale.Chat.InputActions.Stop}
  441. icon={<StopIcon />}
  442. />
  443. )}
  444. {!props.hitBottom && (
  445. <ChatAction
  446. onClick={props.scrollToBottom}
  447. text={Locale.Chat.InputActions.ToBottom}
  448. icon={<BottomIcon />}
  449. />
  450. )}
  451. {props.hitBottom && (
  452. <ChatAction
  453. onClick={props.showPromptModal}
  454. text={Locale.Chat.InputActions.Settings}
  455. icon={<SettingsIcon />}
  456. />
  457. )}
  458. {showUploadImage && (
  459. <ChatAction
  460. onClick={props.uploadImage}
  461. text={Locale.Chat.InputActions.UploadImage}
  462. icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />}
  463. />
  464. )}
  465. <ChatAction
  466. onClick={nextTheme}
  467. text={Locale.Chat.InputActions.Theme[theme]}
  468. icon={
  469. <>
  470. {theme === Theme.Auto ? (
  471. <AutoIcon />
  472. ) : theme === Theme.Light ? (
  473. <LightIcon />
  474. ) : theme === Theme.Dark ? (
  475. <DarkIcon />
  476. ) : null}
  477. </>
  478. }
  479. />
  480. <ChatAction
  481. onClick={props.showPromptHints}
  482. text={Locale.Chat.InputActions.Prompt}
  483. icon={<PromptIcon />}
  484. />
  485. <ChatAction
  486. onClick={() => {
  487. navigate(Path.Masks);
  488. }}
  489. text={Locale.Chat.InputActions.Masks}
  490. icon={<MaskIcon />}
  491. />
  492. <ChatAction
  493. text={Locale.Chat.InputActions.Clear}
  494. icon={<BreakIcon />}
  495. onClick={() => {
  496. chatStore.updateCurrentSession((session) => {
  497. if (session.clearContextIndex === session.messages.length) {
  498. session.clearContextIndex = undefined;
  499. } else {
  500. session.clearContextIndex = session.messages.length;
  501. session.memoryPrompt = ""; // will clear memory
  502. }
  503. });
  504. }}
  505. />
  506. <ChatAction
  507. onClick={() => setShowModelSelector(true)}
  508. text={currentModel}
  509. icon={<RobotIcon />}
  510. />
  511. {showModelSelector && (
  512. <Selector
  513. defaultSelectedValue={currentModel}
  514. items={models.map((m) => ({
  515. title: m.displayName,
  516. value: m.name,
  517. }))}
  518. onClose={() => setShowModelSelector(false)}
  519. onSelection={(s) => {
  520. if (s.length === 0) return;
  521. chatStore.updateCurrentSession((session) => {
  522. session.mask.modelConfig.model = s[0] as ModelType;
  523. session.mask.syncGlobalConfig = false;
  524. });
  525. showToast(s[0]);
  526. }}
  527. />
  528. )}
  529. </div>
  530. );
  531. }
  532. export function EditMessageModal(props: { onClose: () => void }) {
  533. const chatStore = useChatStore();
  534. const session = chatStore.currentSession();
  535. const [messages, setMessages] = useState(session.messages.slice());
  536. return (
  537. <div className="modal-mask">
  538. <Modal
  539. title={Locale.Chat.EditMessage.Title}
  540. onClose={props.onClose}
  541. actions={[
  542. <IconButton
  543. text={Locale.UI.Cancel}
  544. icon={<CancelIcon />}
  545. key="cancel"
  546. onClick={() => {
  547. props.onClose();
  548. }}
  549. />,
  550. <IconButton
  551. type="primary"
  552. text={Locale.UI.Confirm}
  553. icon={<ConfirmIcon />}
  554. key="ok"
  555. onClick={() => {
  556. chatStore.updateCurrentSession(
  557. (session) => (session.messages = messages),
  558. );
  559. props.onClose();
  560. }}
  561. />,
  562. ]}
  563. >
  564. <List>
  565. <ListItem
  566. title={Locale.Chat.EditMessage.Topic.Title}
  567. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  568. >
  569. <input
  570. type="text"
  571. value={session.topic}
  572. onInput={(e) =>
  573. chatStore.updateCurrentSession(
  574. (session) => (session.topic = e.currentTarget.value),
  575. )
  576. }
  577. ></input>
  578. </ListItem>
  579. </List>
  580. <ContextPrompts
  581. context={messages}
  582. updateContext={(updater) => {
  583. const newMessages = messages.slice();
  584. updater(newMessages);
  585. setMessages(newMessages);
  586. }}
  587. />
  588. </Modal>
  589. </div>
  590. );
  591. }
  592. export function DeleteImageButton(props: { deleteImage: () => void }) {
  593. return (
  594. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  595. <DeleteIcon />
  596. </div>
  597. );
  598. }
  599. function _Chat() {
  600. type RenderMessage = ChatMessage & { preview?: boolean };
  601. const chatStore = useChatStore();
  602. const session = chatStore.currentSession();
  603. const config = useAppConfig();
  604. const fontSize = config.fontSize;
  605. const [showExport, setShowExport] = useState(false);
  606. const inputRef = useRef<HTMLTextAreaElement>(null);
  607. const [userInput, setUserInput] = useState("");
  608. const [isLoading, setIsLoading] = useState(false);
  609. const { submitKey, shouldSubmit } = useSubmitHandler();
  610. const scrollRef = useRef<HTMLDivElement>(null);
  611. const isScrolledToBottom = scrollRef?.current
  612. ? Math.abs(
  613. scrollRef.current.scrollHeight -
  614. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  615. ) <= 1
  616. : false;
  617. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  618. scrollRef,
  619. isScrolledToBottom,
  620. );
  621. const [hitBottom, setHitBottom] = useState(true);
  622. const isMobileScreen = useMobileScreen();
  623. const navigate = useNavigate();
  624. const [attachImages, setAttachImages] = useState<string[]>([]);
  625. const [uploading, setUploading] = useState(false);
  626. // prompt hints
  627. const promptStore = usePromptStore();
  628. const [promptHints, setPromptHints] = useState<RenderPompt[]>([]);
  629. const onSearch = useDebouncedCallback(
  630. (text: string) => {
  631. const matchedPrompts = promptStore.search(text);
  632. setPromptHints(matchedPrompts);
  633. },
  634. 100,
  635. { leading: true, trailing: true },
  636. );
  637. // auto grow input
  638. const [inputRows, setInputRows] = useState(2);
  639. const measure = useDebouncedCallback(
  640. () => {
  641. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  642. const inputRows = Math.min(
  643. 20,
  644. Math.max(2 + Number(!isMobileScreen), rows),
  645. );
  646. setInputRows(inputRows);
  647. },
  648. 100,
  649. {
  650. leading: true,
  651. trailing: true,
  652. },
  653. );
  654. // eslint-disable-next-line react-hooks/exhaustive-deps
  655. useEffect(measure, [userInput]);
  656. // chat commands shortcuts
  657. const chatCommands = useChatCommand({
  658. new: () => chatStore.newSession(),
  659. newm: () => navigate(Path.NewChat),
  660. prev: () => chatStore.nextSession(-1),
  661. next: () => chatStore.nextSession(1),
  662. clear: () =>
  663. chatStore.updateCurrentSession(
  664. (session) => (session.clearContextIndex = session.messages.length),
  665. ),
  666. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  667. });
  668. // only search prompts when user input is short
  669. const SEARCH_TEXT_LIMIT = 30;
  670. const onInput = (text: string) => {
  671. setUserInput(text);
  672. const n = text.trim().length;
  673. // clear search results
  674. if (n === 0) {
  675. setPromptHints([]);
  676. } else if (text.startsWith(ChatCommandPrefix)) {
  677. setPromptHints(chatCommands.search(text));
  678. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  679. // check if need to trigger auto completion
  680. if (text.startsWith("/")) {
  681. let searchText = text.slice(1);
  682. onSearch(searchText);
  683. }
  684. }
  685. };
  686. const doSubmit = (userInput: string) => {
  687. if (userInput.trim() === "") return;
  688. const matchCommand = chatCommands.match(userInput);
  689. if (matchCommand.matched) {
  690. setUserInput("");
  691. setPromptHints([]);
  692. matchCommand.invoke();
  693. return;
  694. }
  695. setIsLoading(true);
  696. chatStore
  697. .onUserInput(userInput, attachImages)
  698. .then(() => setIsLoading(false));
  699. setAttachImages([]);
  700. localStorage.setItem(LAST_INPUT_KEY, userInput);
  701. setUserInput("");
  702. setPromptHints([]);
  703. if (!isMobileScreen) inputRef.current?.focus();
  704. setAutoScroll(true);
  705. };
  706. const onPromptSelect = (prompt: RenderPompt) => {
  707. setTimeout(() => {
  708. setPromptHints([]);
  709. const matchedChatCommand = chatCommands.match(prompt.content);
  710. if (matchedChatCommand.matched) {
  711. // if user is selecting a chat command, just trigger it
  712. matchedChatCommand.invoke();
  713. setUserInput("");
  714. } else {
  715. // or fill the prompt
  716. setUserInput(prompt.content);
  717. }
  718. inputRef.current?.focus();
  719. }, 30);
  720. };
  721. // stop response
  722. const onUserStop = (messageId: string) => {
  723. ChatControllerPool.stop(session.id, messageId);
  724. };
  725. useEffect(() => {
  726. chatStore.updateCurrentSession((session) => {
  727. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  728. session.messages.forEach((m) => {
  729. // check if should stop all stale messages
  730. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  731. if (m.streaming) {
  732. m.streaming = false;
  733. }
  734. if (m.content.length === 0) {
  735. m.isError = true;
  736. m.content = prettyObject({
  737. error: true,
  738. message: "empty response",
  739. });
  740. }
  741. }
  742. });
  743. // auto sync mask config from global config
  744. if (session.mask.syncGlobalConfig) {
  745. console.log("[Mask] syncing from global, name = ", session.mask.name);
  746. session.mask.modelConfig = { ...config.modelConfig };
  747. }
  748. });
  749. // eslint-disable-next-line react-hooks/exhaustive-deps
  750. }, []);
  751. // check if should send message
  752. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  753. // if ArrowUp and no userInput, fill with last input
  754. if (
  755. e.key === "ArrowUp" &&
  756. userInput.length <= 0 &&
  757. !(e.metaKey || e.altKey || e.ctrlKey)
  758. ) {
  759. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  760. e.preventDefault();
  761. return;
  762. }
  763. if (shouldSubmit(e) && promptHints.length === 0) {
  764. doSubmit(userInput);
  765. e.preventDefault();
  766. }
  767. };
  768. const onRightClick = (e: any, message: ChatMessage) => {
  769. // copy to clipboard
  770. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  771. if (userInput.length === 0) {
  772. setUserInput(getMessageTextContent(message));
  773. }
  774. e.preventDefault();
  775. }
  776. };
  777. const deleteMessage = (msgId?: string) => {
  778. chatStore.updateCurrentSession(
  779. (session) =>
  780. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  781. );
  782. };
  783. const onDelete = (msgId: string) => {
  784. deleteMessage(msgId);
  785. };
  786. const onResend = (message: ChatMessage) => {
  787. // when it is resending a message
  788. // 1. for a user's message, find the next bot response
  789. // 2. for a bot's message, find the last user's input
  790. // 3. delete original user input and bot's message
  791. // 4. resend the user's input
  792. const resendingIndex = session.messages.findIndex(
  793. (m) => m.id === message.id,
  794. );
  795. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  796. console.error("[Chat] failed to find resending message", message);
  797. return;
  798. }
  799. let userMessage: ChatMessage | undefined;
  800. let botMessage: ChatMessage | undefined;
  801. if (message.role === "assistant") {
  802. // if it is resending a bot's message, find the user input for it
  803. botMessage = message;
  804. for (let i = resendingIndex; i >= 0; i -= 1) {
  805. if (session.messages[i].role === "user") {
  806. userMessage = session.messages[i];
  807. break;
  808. }
  809. }
  810. } else if (message.role === "user") {
  811. // if it is resending a user's input, find the bot's response
  812. userMessage = message;
  813. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  814. if (session.messages[i].role === "assistant") {
  815. botMessage = session.messages[i];
  816. break;
  817. }
  818. }
  819. }
  820. if (userMessage === undefined) {
  821. console.error("[Chat] failed to resend", message);
  822. return;
  823. }
  824. // delete the original messages
  825. deleteMessage(userMessage.id);
  826. deleteMessage(botMessage?.id);
  827. // resend the message
  828. setIsLoading(true);
  829. const textContent = getMessageTextContent(userMessage);
  830. const images = getMessageImages(userMessage);
  831. chatStore.onUserInput(textContent, images).then(() => setIsLoading(false));
  832. inputRef.current?.focus();
  833. };
  834. const onPinMessage = (message: ChatMessage) => {
  835. chatStore.updateCurrentSession((session) =>
  836. session.mask.context.push(message),
  837. );
  838. showToast(Locale.Chat.Actions.PinToastContent, {
  839. text: Locale.Chat.Actions.PinToastAction,
  840. onClick: () => {
  841. setShowPromptModal(true);
  842. },
  843. });
  844. };
  845. const context: RenderMessage[] = useMemo(() => {
  846. return session.mask.hideContext ? [] : session.mask.context.slice();
  847. }, [session.mask.context, session.mask.hideContext]);
  848. const accessStore = useAccessStore();
  849. if (
  850. context.length === 0 &&
  851. session.messages.at(0)?.content !== BOT_HELLO.content
  852. ) {
  853. const copiedHello = Object.assign({}, BOT_HELLO);
  854. if (!accessStore.isAuthorized()) {
  855. copiedHello.content = Locale.Error.Unauthorized;
  856. }
  857. context.push(copiedHello);
  858. }
  859. // preview messages
  860. const renderMessages = useMemo(() => {
  861. return context
  862. .concat(session.messages as RenderMessage[])
  863. .concat(
  864. isLoading
  865. ? [
  866. {
  867. ...createMessage({
  868. role: "assistant",
  869. content: "……",
  870. }),
  871. preview: true,
  872. },
  873. ]
  874. : [],
  875. )
  876. .concat(
  877. userInput.length > 0 && config.sendPreviewBubble
  878. ? [
  879. {
  880. ...createMessage({
  881. role: "user",
  882. content: userInput,
  883. }),
  884. preview: true,
  885. },
  886. ]
  887. : [],
  888. );
  889. }, [
  890. config.sendPreviewBubble,
  891. context,
  892. isLoading,
  893. session.messages,
  894. userInput,
  895. ]);
  896. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  897. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  898. );
  899. function setMsgRenderIndex(newIndex: number) {
  900. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  901. newIndex = Math.max(0, newIndex);
  902. _setMsgRenderIndex(newIndex);
  903. }
  904. const messages = useMemo(() => {
  905. const endRenderIndex = Math.min(
  906. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  907. renderMessages.length,
  908. );
  909. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  910. }, [msgRenderIndex, renderMessages]);
  911. const onChatBodyScroll = (e: HTMLElement) => {
  912. const bottomHeight = e.scrollTop + e.clientHeight;
  913. const edgeThreshold = e.clientHeight;
  914. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  915. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  916. const isHitBottom =
  917. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  918. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  919. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  920. if (isTouchTopEdge && !isTouchBottomEdge) {
  921. setMsgRenderIndex(prevPageMsgIndex);
  922. } else if (isTouchBottomEdge) {
  923. setMsgRenderIndex(nextPageMsgIndex);
  924. }
  925. setHitBottom(isHitBottom);
  926. setAutoScroll(isHitBottom);
  927. };
  928. function scrollToBottom() {
  929. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  930. scrollDomToBottom();
  931. }
  932. // clear context index = context length + index in messages
  933. const clearContextIndex =
  934. (session.clearContextIndex ?? -1) >= 0
  935. ? session.clearContextIndex! + context.length - msgRenderIndex
  936. : -1;
  937. const [showPromptModal, setShowPromptModal] = useState(false);
  938. const clientConfig = useMemo(() => getClientConfig(), []);
  939. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  940. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  941. useCommand({
  942. fill: setUserInput,
  943. submit: (text) => {
  944. doSubmit(text);
  945. },
  946. code: (text) => {
  947. if (accessStore.disableFastLink) return;
  948. console.log("[Command] got code from url: ", text);
  949. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  950. if (res) {
  951. accessStore.update((access) => (access.accessCode = text));
  952. }
  953. });
  954. },
  955. settings: (text) => {
  956. if (accessStore.disableFastLink) return;
  957. try {
  958. const payload = JSON.parse(text) as {
  959. key?: string;
  960. url?: string;
  961. };
  962. console.log("[Command] got settings from url: ", payload);
  963. if (payload.key || payload.url) {
  964. showConfirm(
  965. Locale.URLCommand.Settings +
  966. `\n${JSON.stringify(payload, null, 4)}`,
  967. ).then((res) => {
  968. if (!res) return;
  969. if (payload.key) {
  970. accessStore.update(
  971. (access) => (access.openaiApiKey = payload.key!),
  972. );
  973. }
  974. if (payload.url) {
  975. accessStore.update((access) => (access.openaiUrl = payload.url!));
  976. }
  977. });
  978. }
  979. } catch {
  980. console.error("[Command] failed to get settings from url: ", text);
  981. }
  982. },
  983. });
  984. // edit / insert message modal
  985. const [isEditingMessage, setIsEditingMessage] = useState(false);
  986. // remember unfinished input
  987. useEffect(() => {
  988. // try to load from local storage
  989. const key = UNFINISHED_INPUT(session.id);
  990. const mayBeUnfinishedInput = localStorage.getItem(key);
  991. if (mayBeUnfinishedInput && userInput.length === 0) {
  992. setUserInput(mayBeUnfinishedInput);
  993. localStorage.removeItem(key);
  994. }
  995. const dom = inputRef.current;
  996. return () => {
  997. localStorage.setItem(key, dom?.value ?? "");
  998. };
  999. // eslint-disable-next-line react-hooks/exhaustive-deps
  1000. }, []);
  1001. const handlePaste = useCallback(
  1002. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1003. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1004. if(!isVisionModel(currentModel)){return;}
  1005. const items = (event.clipboardData || window.clipboardData).items;
  1006. for (const item of items) {
  1007. if (item.kind === "file" && item.type.startsWith("image/")) {
  1008. event.preventDefault();
  1009. const file = item.getAsFile();
  1010. if (file) {
  1011. const images: string[] = [];
  1012. images.push(...attachImages);
  1013. images.push(
  1014. ...(await new Promise<string[]>((res, rej) => {
  1015. setUploading(true);
  1016. const imagesData: string[] = [];
  1017. compressImage(file, 256 * 1024)
  1018. .then((dataUrl) => {
  1019. imagesData.push(dataUrl);
  1020. setUploading(false);
  1021. res(imagesData);
  1022. })
  1023. .catch((e) => {
  1024. setUploading(false);
  1025. rej(e);
  1026. });
  1027. })),
  1028. );
  1029. const imagesLength = images.length;
  1030. if (imagesLength > 3) {
  1031. images.splice(3, imagesLength - 3);
  1032. }
  1033. setAttachImages(images);
  1034. }
  1035. }
  1036. }
  1037. },
  1038. [attachImages, chatStore],
  1039. );
  1040. async function uploadImage() {
  1041. const images: string[] = [];
  1042. images.push(...attachImages);
  1043. images.push(
  1044. ...(await new Promise<string[]>((res, rej) => {
  1045. const fileInput = document.createElement("input");
  1046. fileInput.type = "file";
  1047. fileInput.accept =
  1048. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1049. fileInput.multiple = true;
  1050. fileInput.onchange = (event: any) => {
  1051. setUploading(true);
  1052. const files = event.target.files;
  1053. const imagesData: string[] = [];
  1054. for (let i = 0; i < files.length; i++) {
  1055. const file = event.target.files[i];
  1056. compressImage(file, 256 * 1024)
  1057. .then((dataUrl) => {
  1058. imagesData.push(dataUrl);
  1059. if (
  1060. imagesData.length === 3 ||
  1061. imagesData.length === files.length
  1062. ) {
  1063. setUploading(false);
  1064. res(imagesData);
  1065. }
  1066. })
  1067. .catch((e) => {
  1068. setUploading(false);
  1069. rej(e);
  1070. });
  1071. }
  1072. };
  1073. fileInput.click();
  1074. })),
  1075. );
  1076. const imagesLength = images.length;
  1077. if (imagesLength > 3) {
  1078. images.splice(3, imagesLength - 3);
  1079. }
  1080. setAttachImages(images);
  1081. }
  1082. return (
  1083. <div className={styles.chat} key={session.id}>
  1084. <div className="window-header" data-tauri-drag-region>
  1085. {isMobileScreen && (
  1086. <div className="window-actions">
  1087. <div className={"window-action-button"}>
  1088. <IconButton
  1089. icon={<ReturnIcon />}
  1090. bordered
  1091. title={Locale.Chat.Actions.ChatList}
  1092. onClick={() => navigate(Path.Home)}
  1093. />
  1094. </div>
  1095. </div>
  1096. )}
  1097. <div className={`window-header-title ${styles["chat-body-title"]}`}>
  1098. <div
  1099. className={`window-header-main-title ${styles["chat-body-main-title"]}`}
  1100. onClickCapture={() => setIsEditingMessage(true)}
  1101. >
  1102. {!session.topic ? DEFAULT_TOPIC : session.topic}
  1103. </div>
  1104. <div className="window-header-sub-title">
  1105. {Locale.Chat.SubTitle(session.messages.length)}
  1106. </div>
  1107. </div>
  1108. <div className="window-actions">
  1109. {!isMobileScreen && (
  1110. <div className="window-action-button">
  1111. <IconButton
  1112. icon={<RenameIcon />}
  1113. bordered
  1114. onClick={() => setIsEditingMessage(true)}
  1115. />
  1116. </div>
  1117. )}
  1118. <div className="window-action-button">
  1119. <IconButton
  1120. icon={<ExportIcon />}
  1121. bordered
  1122. title={Locale.Chat.Actions.Export}
  1123. onClick={() => {
  1124. setShowExport(true);
  1125. }}
  1126. />
  1127. </div>
  1128. {showMaxIcon && (
  1129. <div className="window-action-button">
  1130. <IconButton
  1131. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1132. bordered
  1133. onClick={() => {
  1134. config.update(
  1135. (config) => (config.tightBorder = !config.tightBorder),
  1136. );
  1137. }}
  1138. />
  1139. </div>
  1140. )}
  1141. </div>
  1142. <PromptToast
  1143. showToast={!hitBottom}
  1144. showModal={showPromptModal}
  1145. setShowModal={setShowPromptModal}
  1146. />
  1147. </div>
  1148. <div
  1149. className={styles["chat-body"]}
  1150. ref={scrollRef}
  1151. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1152. onMouseDown={() => inputRef.current?.blur()}
  1153. onTouchStart={() => {
  1154. inputRef.current?.blur();
  1155. setAutoScroll(false);
  1156. }}
  1157. >
  1158. {messages.map((message, i) => {
  1159. const isUser = message.role === "user";
  1160. const isContext = i < context.length;
  1161. const showActions =
  1162. i > 0 &&
  1163. !(message.preview || message.content.length === 0) &&
  1164. !isContext;
  1165. const showTyping = message.preview || message.streaming;
  1166. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1167. return (
  1168. <Fragment key={message.id}>
  1169. <div
  1170. className={
  1171. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1172. }
  1173. >
  1174. <div className={styles["chat-message-container"]}>
  1175. <div className={styles["chat-message-header"]}>
  1176. <div className={styles["chat-message-avatar"]}>
  1177. <div className={styles["chat-message-edit"]}>
  1178. <IconButton
  1179. icon={<EditIcon />}
  1180. onClick={async () => {
  1181. const newMessage = await showPrompt(
  1182. Locale.Chat.Actions.Edit,
  1183. getMessageTextContent(message),
  1184. 10,
  1185. );
  1186. let newContent: string | MultimodalContent[] =
  1187. newMessage;
  1188. const images = getMessageImages(message);
  1189. if (images.length > 0) {
  1190. newContent = [{ type: "text", text: newMessage }];
  1191. for (let i = 0; i < images.length; i++) {
  1192. newContent.push({
  1193. type: "image_url",
  1194. image_url: {
  1195. url: images[i],
  1196. },
  1197. });
  1198. }
  1199. }
  1200. chatStore.updateCurrentSession((session) => {
  1201. const m = session.mask.context
  1202. .concat(session.messages)
  1203. .find((m) => m.id === message.id);
  1204. if (m) {
  1205. m.content = newContent;
  1206. }
  1207. });
  1208. }}
  1209. ></IconButton>
  1210. </div>
  1211. {isUser ? (
  1212. <Avatar avatar={config.avatar} />
  1213. ) : (
  1214. <>
  1215. {["system"].includes(message.role) ? (
  1216. <Avatar avatar="2699-fe0f" />
  1217. ) : (
  1218. <MaskAvatar
  1219. avatar={session.mask.avatar}
  1220. model={
  1221. message.model || session.mask.modelConfig.model
  1222. }
  1223. />
  1224. )}
  1225. </>
  1226. )}
  1227. </div>
  1228. {showActions && (
  1229. <div className={styles["chat-message-actions"]}>
  1230. <div className={styles["chat-input-actions"]}>
  1231. {message.streaming ? (
  1232. <ChatAction
  1233. text={Locale.Chat.Actions.Stop}
  1234. icon={<StopIcon />}
  1235. onClick={() => onUserStop(message.id ?? i)}
  1236. />
  1237. ) : (
  1238. <>
  1239. <ChatAction
  1240. text={Locale.Chat.Actions.Retry}
  1241. icon={<ResetIcon />}
  1242. onClick={() => onResend(message)}
  1243. />
  1244. <ChatAction
  1245. text={Locale.Chat.Actions.Delete}
  1246. icon={<DeleteIcon />}
  1247. onClick={() => onDelete(message.id ?? i)}
  1248. />
  1249. <ChatAction
  1250. text={Locale.Chat.Actions.Pin}
  1251. icon={<PinIcon />}
  1252. onClick={() => onPinMessage(message)}
  1253. />
  1254. <ChatAction
  1255. text={Locale.Chat.Actions.Copy}
  1256. icon={<CopyIcon />}
  1257. onClick={() =>
  1258. copyToClipboard(
  1259. getMessageTextContent(message),
  1260. )
  1261. }
  1262. />
  1263. </>
  1264. )}
  1265. </div>
  1266. </div>
  1267. )}
  1268. </div>
  1269. {showTyping && (
  1270. <div className={styles["chat-message-status"]}>
  1271. {Locale.Chat.Typing}
  1272. </div>
  1273. )}
  1274. <div className={styles["chat-message-item"]}>
  1275. <Markdown
  1276. content={getMessageTextContent(message)}
  1277. loading={
  1278. (message.preview || message.streaming) &&
  1279. message.content.length === 0 &&
  1280. !isUser
  1281. }
  1282. onContextMenu={(e) => onRightClick(e, message)}
  1283. onDoubleClickCapture={() => {
  1284. if (!isMobileScreen) return;
  1285. setUserInput(getMessageTextContent(message));
  1286. }}
  1287. fontSize={fontSize}
  1288. parentRef={scrollRef}
  1289. defaultShow={i >= messages.length - 6}
  1290. />
  1291. {getMessageImages(message).length == 1 && (
  1292. <img
  1293. className={styles["chat-message-item-image"]}
  1294. src={getMessageImages(message)[0]}
  1295. alt=""
  1296. />
  1297. )}
  1298. {getMessageImages(message).length > 1 && (
  1299. <div
  1300. className={styles["chat-message-item-images"]}
  1301. style={
  1302. {
  1303. "--image-count": getMessageImages(message).length,
  1304. } as React.CSSProperties
  1305. }
  1306. >
  1307. {getMessageImages(message).map((image, index) => {
  1308. return (
  1309. <img
  1310. className={
  1311. styles["chat-message-item-image-multi"]
  1312. }
  1313. key={index}
  1314. src={image}
  1315. alt=""
  1316. />
  1317. );
  1318. })}
  1319. </div>
  1320. )}
  1321. </div>
  1322. <div className={styles["chat-message-action-date"]}>
  1323. {isContext
  1324. ? Locale.Chat.IsContext
  1325. : message.date.toLocaleString()}
  1326. </div>
  1327. </div>
  1328. </div>
  1329. {shouldShowClearContextDivider && <ClearContextDivider />}
  1330. </Fragment>
  1331. );
  1332. })}
  1333. </div>
  1334. <div className={styles["chat-input-panel"]}>
  1335. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  1336. <ChatActions
  1337. uploadImage={uploadImage}
  1338. setAttachImages={setAttachImages}
  1339. setUploading={setUploading}
  1340. showPromptModal={() => setShowPromptModal(true)}
  1341. scrollToBottom={scrollToBottom}
  1342. hitBottom={hitBottom}
  1343. uploading={uploading}
  1344. showPromptHints={() => {
  1345. // Click again to close
  1346. if (promptHints.length > 0) {
  1347. setPromptHints([]);
  1348. return;
  1349. }
  1350. inputRef.current?.focus();
  1351. setUserInput("/");
  1352. onSearch("");
  1353. }}
  1354. />
  1355. <label
  1356. className={`${styles["chat-input-panel-inner"]} ${
  1357. attachImages.length != 0
  1358. ? styles["chat-input-panel-inner-attach"]
  1359. : ""
  1360. }`}
  1361. htmlFor="chat-input"
  1362. >
  1363. <textarea
  1364. id="chat-input"
  1365. ref={inputRef}
  1366. className={styles["chat-input"]}
  1367. placeholder={Locale.Chat.Input(submitKey)}
  1368. onInput={(e) => onInput(e.currentTarget.value)}
  1369. value={userInput}
  1370. onKeyDown={onInputKeyDown}
  1371. onFocus={scrollToBottom}
  1372. onClick={scrollToBottom}
  1373. onPaste={handlePaste}
  1374. rows={inputRows}
  1375. autoFocus={autoFocus}
  1376. style={{
  1377. fontSize: config.fontSize,
  1378. }}
  1379. />
  1380. {attachImages.length != 0 && (
  1381. <div className={styles["attach-images"]}>
  1382. {attachImages.map((image, index) => {
  1383. return (
  1384. <div
  1385. key={index}
  1386. className={styles["attach-image"]}
  1387. style={{ backgroundImage: `url("${image}")` }}
  1388. >
  1389. <div className={styles["attach-image-mask"]}>
  1390. <DeleteImageButton
  1391. deleteImage={() => {
  1392. setAttachImages(
  1393. attachImages.filter((_, i) => i !== index),
  1394. );
  1395. }}
  1396. />
  1397. </div>
  1398. </div>
  1399. );
  1400. })}
  1401. </div>
  1402. )}
  1403. <IconButton
  1404. icon={<SendWhiteIcon />}
  1405. text={Locale.Chat.Send}
  1406. className={styles["chat-input-send"]}
  1407. type="primary"
  1408. onClick={() => doSubmit(userInput)}
  1409. />
  1410. </label>
  1411. </div>
  1412. {showExport && (
  1413. <ExportMessageModal onClose={() => setShowExport(false)} />
  1414. )}
  1415. {isEditingMessage && (
  1416. <EditMessageModal
  1417. onClose={() => {
  1418. setIsEditingMessage(false);
  1419. }}
  1420. />
  1421. )}
  1422. </div>
  1423. );
  1424. }
  1425. export function Chat() {
  1426. const chatStore = useChatStore();
  1427. const sessionIndex = chatStore.currentSessionIndex;
  1428. return <_Chat key={sessionIndex}></_Chat>;
  1429. }