DeepSeekChat.tsx 44 KB

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