DeepSeekHomeChat.tsx 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505
  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. SubmitKey,
  23. useChatStore,
  24. useAccessStore,
  25. Theme,
  26. useAppConfig,
  27. DEFAULT_TOPIC,
  28. ModelType,
  29. } from "../store";
  30. import {
  31. copyToClipboard,
  32. selectOrCopy,
  33. autoGrowTextArea,
  34. useMobileScreen,
  35. getMessageTextContent,
  36. getMessageImages,
  37. isVisionModel,
  38. isDalle3,
  39. } from "../utils";
  40. import { uploadImage as uploadImageRemote } from "@/app/utils/chat";
  41. import dynamic from "next/dynamic";
  42. import { ChatControllerPool } from "../client/controller";
  43. import { DalleSize } from "../typing";
  44. import type { RequestMessage } from "../client/api";
  45. import { Prompt, usePromptStore } from "../store/prompt";
  46. import { useGlobalStore } from "../store";
  47. import Locale from "../locales";
  48. import { IconButton } from "./button";
  49. import styles from "./chat.module.scss";
  50. import {
  51. List,
  52. ListItem,
  53. Modal,
  54. Selector,
  55. showConfirm,
  56. showToast,
  57. } from "./ui-lib";
  58. import { useNavigate, useLocation } from "react-router-dom";
  59. import {
  60. CHAT_PAGE_SIZE,
  61. LAST_INPUT_KEY,
  62. Path,
  63. REQUEST_TIMEOUT_MS,
  64. UNFINISHED_INPUT,
  65. ServiceProvider,
  66. Plugin,
  67. } from "../constant";
  68. import { ContextPrompts, MaskConfig } from "./mask";
  69. import { useMaskStore } from "../store/mask";
  70. import { ChatCommandPrefix, useChatCommand, useCommand } from "../command";
  71. import { prettyObject } from "../utils/format";
  72. import { ExportMessageModal } from "./exporter";
  73. import { getClientConfig } from "../config/client";
  74. import { useAllModels } from "../utils/hooks";
  75. import { nanoid } from "nanoid";
  76. export function createMessage(override: Partial<ChatMessage>): ChatMessage {
  77. return {
  78. id: nanoid(),
  79. date: new Date().toLocaleString(),
  80. role: "user",
  81. content: "",
  82. ...override,
  83. };
  84. }
  85. export type ChatMessage = RequestMessage & {
  86. date: string;
  87. streaming?: boolean;
  88. isError?: boolean;
  89. id: string;
  90. model?: ModelType;
  91. };
  92. export const BOT_HELLO: ChatMessage = createMessage({
  93. role: "assistant",
  94. content: '您好,我是小智',
  95. });
  96. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  97. loading: () => <LoadingIcon />,
  98. });
  99. export function SessionConfigModel(props: { onClose: () => void }) {
  100. const chatStore = useChatStore();
  101. const session = chatStore.currentSession();
  102. const maskStore = useMaskStore();
  103. const navigate = useNavigate();
  104. return (
  105. <div className="modal-mask">
  106. <Modal
  107. title={Locale.Context.Edit}
  108. onClose={() => props.onClose()}
  109. actions={[
  110. <IconButton
  111. key="reset"
  112. icon={<ResetIcon />}
  113. bordered
  114. text={Locale.Chat.Config.Reset}
  115. onClick={async () => {
  116. if (await showConfirm(Locale.Memory.ResetConfirm)) {
  117. chatStore.updateCurrentSession(
  118. (session) => (session.memoryPrompt = ""),
  119. );
  120. }
  121. }}
  122. />,
  123. <IconButton
  124. key="copy"
  125. icon={<CopyIcon />}
  126. bordered
  127. text={Locale.Chat.Config.SaveAs}
  128. onClick={() => {
  129. navigate(Path.Masks);
  130. setTimeout(() => {
  131. maskStore.create(session.mask);
  132. }, 500);
  133. }}
  134. />,
  135. ]}
  136. >
  137. <MaskConfig
  138. mask={session.mask}
  139. updateMask={(updater) => {
  140. const mask = { ...session.mask };
  141. updater(mask);
  142. chatStore.updateCurrentSession((session) => (session.mask = mask));
  143. }}
  144. shouldSyncFromGlobal
  145. extraListItems={
  146. session.mask.modelConfig.sendMemory ? (
  147. <ListItem
  148. className="copyable"
  149. title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`}
  150. subTitle={session.memoryPrompt || Locale.Memory.EmptyContent}
  151. ></ListItem>
  152. ) : (
  153. <></>
  154. )
  155. }
  156. ></MaskConfig>
  157. </Modal>
  158. </div>
  159. );
  160. }
  161. // 提示词
  162. const CallWord = (props: {
  163. setUserInput: (value: string) => void,
  164. doSubmit: (userInput: string) => void,
  165. }) => {
  166. const { setUserInput, doSubmit } = props
  167. const list = [
  168. {
  169. title: '信息公布',
  170. // text: '在哪里查看招聘信息?',
  171. text: '今年上海建科工程咨询的校园招聘什么时候开始?如何查阅相关招聘信息?',
  172. },
  173. {
  174. title: '招聘岗位',
  175. // text: '今年招聘的岗位有哪些?',
  176. text: '今年招聘的岗位有哪些?',
  177. },
  178. {
  179. title: '专业要求',
  180. // text: '招聘的岗位有什么专业要求?',
  181. text: '招聘的岗位有什么专业要求?',
  182. },
  183. {
  184. title: '工作地点',
  185. // text: '全国都有工作地点吗?',
  186. text: '工作地点是如何确定的?',
  187. },
  188. {
  189. title: '薪资待遇',
  190. // text: '企业可提供的薪资与福利待遇如何?',
  191. text: '企业可提供的薪资与福利待遇如何?',
  192. },
  193. {
  194. title: '职业发展',
  195. // text: '我应聘贵单位,你们能提供怎样的职业发展规划?',
  196. text: '公司有哪些职业发展通道?',
  197. },
  198. {
  199. title: '落户政策',
  200. // text: '公司是否能协助我落户?',
  201. text: '关于落户支持?',
  202. }
  203. ]
  204. return (
  205. <>
  206. {
  207. list.map((item, index) => {
  208. return <span
  209. key={index}
  210. style={{
  211. padding: '5px 10px',
  212. background: '#f6f7f8',
  213. color: '#5e5e66',
  214. borderRadius: 4,
  215. margin: '0 5px 10px 0',
  216. cursor: 'pointer',
  217. fontSize: 12
  218. }}
  219. onClick={() => {
  220. const plan: string = '2';
  221. if (plan === '1') {
  222. // 方案1.点击后出现在输入框内,用户自己点击发送
  223. setUserInput(item.text);
  224. } else {
  225. // 方案2.点击后直接发送
  226. doSubmit(item.text)
  227. }
  228. }}
  229. >
  230. {item.title}
  231. </span>
  232. })
  233. }
  234. </>
  235. )
  236. }
  237. function PromptToast(props: {
  238. showToast?: boolean;
  239. showModal?: boolean;
  240. setShowModal: (_: boolean) => void;
  241. }) {
  242. const chatStore = useChatStore();
  243. const session = chatStore.currentSession();
  244. const context = session.mask.context;
  245. return (
  246. <div className={styles["prompt-toast"]} key="prompt-toast">
  247. {props.showToast && (
  248. <div
  249. className={styles["prompt-toast-inner"] + " clickable"}
  250. role="button"
  251. onClick={() => props.setShowModal(true)}
  252. >
  253. <BrainIcon />
  254. <span className={styles["prompt-toast-content"]}>
  255. {Locale.Context.Toast(context.length)}
  256. </span>
  257. </div>
  258. )}
  259. {props.showModal && (
  260. <SessionConfigModel onClose={() => props.setShowModal(false)} />
  261. )}
  262. </div>
  263. );
  264. }
  265. function useSubmitHandler() {
  266. const config = useAppConfig();
  267. const submitKey = config.submitKey;
  268. const isComposing = useRef(false);
  269. useEffect(() => {
  270. const onCompositionStart = () => {
  271. isComposing.current = true;
  272. };
  273. const onCompositionEnd = () => {
  274. isComposing.current = false;
  275. };
  276. window.addEventListener("compositionstart", onCompositionStart);
  277. window.addEventListener("compositionend", onCompositionEnd);
  278. return () => {
  279. window.removeEventListener("compositionstart", onCompositionStart);
  280. window.removeEventListener("compositionend", onCompositionEnd);
  281. };
  282. }, []);
  283. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  284. // Fix Chinese input method "Enter" on Safari
  285. if (e.keyCode == 229) return false;
  286. if (e.key !== "Enter") return false;
  287. if (e.key === "Enter" && (e.nativeEvent.isComposing || isComposing.current))
  288. return false;
  289. return (
  290. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  291. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  292. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  293. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  294. (config.submitKey === SubmitKey.Enter &&
  295. !e.altKey &&
  296. !e.ctrlKey &&
  297. !e.shiftKey &&
  298. !e.metaKey)
  299. );
  300. };
  301. return {
  302. submitKey,
  303. shouldSubmit,
  304. };
  305. }
  306. export type RenderPrompt = Pick<Prompt, "title" | "content">;
  307. export function PromptHints(props: {
  308. prompts: RenderPrompt[];
  309. onPromptSelect: (prompt: RenderPrompt) => void;
  310. }) {
  311. const noPrompts = props.prompts.length === 0;
  312. const [selectIndex, setSelectIndex] = useState(0);
  313. const selectedRef = useRef<HTMLDivElement>(null);
  314. useEffect(() => {
  315. setSelectIndex(0);
  316. }, [props.prompts.length]);
  317. useEffect(() => {
  318. const onKeyDown = (e: KeyboardEvent) => {
  319. if (noPrompts || e.metaKey || e.altKey || e.ctrlKey) {
  320. return;
  321. }
  322. // arrow up / down to select prompt
  323. const changeIndex = (delta: number) => {
  324. e.stopPropagation();
  325. e.preventDefault();
  326. const nextIndex = Math.max(
  327. 0,
  328. Math.min(props.prompts.length - 1, selectIndex + delta),
  329. );
  330. setSelectIndex(nextIndex);
  331. selectedRef.current?.scrollIntoView({
  332. block: "center",
  333. });
  334. };
  335. if (e.key === "ArrowUp") {
  336. changeIndex(1);
  337. } else if (e.key === "ArrowDown") {
  338. changeIndex(-1);
  339. } else if (e.key === "Enter") {
  340. const selectedPrompt = props.prompts.at(selectIndex);
  341. if (selectedPrompt) {
  342. props.onPromptSelect(selectedPrompt);
  343. }
  344. }
  345. };
  346. window.addEventListener("keydown", onKeyDown);
  347. return () => window.removeEventListener("keydown", onKeyDown);
  348. // eslint-disable-next-line react-hooks/exhaustive-deps
  349. }, [props.prompts.length, selectIndex]);
  350. if (noPrompts) return null;
  351. return (
  352. <div className={styles["prompt-hints"]}>
  353. {props.prompts.map((prompt, i) => (
  354. <div
  355. ref={i === selectIndex ? selectedRef : null}
  356. className={
  357. styles["prompt-hint"] +
  358. ` ${i === selectIndex ? styles["prompt-hint-selected"] : ""}`
  359. }
  360. key={prompt.title + i.toString()}
  361. onClick={() => props.onPromptSelect(prompt)}
  362. onMouseEnter={() => setSelectIndex(i)}
  363. >
  364. <div className={styles["hint-title"]}>{prompt.title}</div>
  365. <div className={styles["hint-content"]}>{prompt.content}</div>
  366. </div>
  367. ))}
  368. </div>
  369. );
  370. }
  371. function ClearContextDivider() {
  372. const chatStore = useChatStore();
  373. return (
  374. <div
  375. className={styles["clear-context"]}
  376. onClick={() =>
  377. chatStore.updateCurrentSession(
  378. (session) => (session.clearContextIndex = undefined),
  379. )
  380. }
  381. >
  382. <div className={styles["clear-context-tips"]}>{Locale.Context.Clear}</div>
  383. <div className={styles["clear-context-revert-btn"]}>
  384. {Locale.Context.Revert}
  385. </div>
  386. </div>
  387. );
  388. }
  389. export function ChatAction(props: {
  390. text: string;
  391. icon: JSX.Element;
  392. onClick: () => void;
  393. }) {
  394. const iconRef = useRef<HTMLDivElement>(null);
  395. const textRef = useRef<HTMLDivElement>(null);
  396. const [width, setWidth] = useState({
  397. full: 16,
  398. icon: 16,
  399. });
  400. function updateWidth() {
  401. if (!iconRef.current || !textRef.current) return;
  402. const getWidth = (dom: HTMLDivElement) => dom.getBoundingClientRect().width;
  403. const textWidth = getWidth(textRef.current);
  404. const iconWidth = getWidth(iconRef.current);
  405. setWidth({
  406. full: textWidth + iconWidth,
  407. icon: iconWidth,
  408. });
  409. }
  410. return (
  411. <div
  412. className={`${styles["chat-input-action"]} clickable`}
  413. onClick={() => {
  414. props.onClick();
  415. setTimeout(updateWidth, 1);
  416. }}
  417. onMouseEnter={updateWidth}
  418. onTouchStart={updateWidth}
  419. style={
  420. {
  421. "--icon-width": `${width.icon}px`,
  422. "--full-width": `${width.full}px`,
  423. } as React.CSSProperties
  424. }
  425. >
  426. <div ref={iconRef} className={styles["icon"]}>
  427. {props.icon}
  428. </div>
  429. <div className={styles["text"]} ref={textRef}>
  430. {props.text}
  431. </div>
  432. </div>
  433. );
  434. }
  435. function useScrollToBottom(
  436. scrollRef: RefObject<HTMLDivElement>,
  437. detach: boolean = false,
  438. ) {
  439. // for auto-scroll
  440. const [autoScroll, setAutoScroll] = useState(true);
  441. function scrollDomToBottom() {
  442. const dom = scrollRef.current;
  443. if (dom) {
  444. requestAnimationFrame(() => {
  445. setAutoScroll(true);
  446. dom.scrollTo(0, dom.scrollHeight);
  447. });
  448. }
  449. }
  450. // auto scroll
  451. useEffect(() => {
  452. if (autoScroll && !detach) {
  453. scrollDomToBottom();
  454. }
  455. });
  456. return {
  457. scrollRef,
  458. autoScroll,
  459. setAutoScroll,
  460. scrollDomToBottom,
  461. };
  462. }
  463. export function ChatActions(props: {
  464. setUserInput: (value: string) => void;
  465. doSubmit: (userInput: string) => void;
  466. uploadImage: () => void;
  467. setAttachImages: (images: string[]) => void;
  468. setUploading: (uploading: boolean) => void;
  469. showPromptModal: () => void;
  470. scrollToBottom: () => void;
  471. showPromptHints: () => void;
  472. hitBottom: boolean;
  473. uploading: boolean;
  474. }) {
  475. const config = useAppConfig();
  476. const navigate = useNavigate();
  477. const chatStore = useChatStore();
  478. // switch themes
  479. const theme = config.theme;
  480. function nextTheme() {
  481. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  482. const themeIndex = themes.indexOf(theme);
  483. const nextIndex = (themeIndex + 1) % themes.length;
  484. const nextTheme = themes[nextIndex];
  485. config.update((config) => (config.theme = nextTheme));
  486. }
  487. // stop all responses
  488. const couldStop = ChatControllerPool.hasPending();
  489. const stopAll = () => ChatControllerPool.stopAll();
  490. // switch model
  491. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  492. const currentProviderName =
  493. chatStore.currentSession().mask.modelConfig?.providerName ||
  494. ServiceProvider.OpenAI;
  495. const allModels = useAllModels();
  496. const models = useMemo(() => {
  497. const filteredModels = allModels.filter((m) => m.available);
  498. const defaultModel = filteredModels.find((m) => m.isDefault);
  499. if (defaultModel) {
  500. const arr = [
  501. defaultModel,
  502. ...filteredModels.filter((m) => m !== defaultModel),
  503. ];
  504. return arr;
  505. } else {
  506. return filteredModels;
  507. }
  508. }, [allModels]);
  509. const currentModelName = useMemo(() => {
  510. const model = models.find(
  511. (m) =>
  512. m.name == currentModel &&
  513. m?.provider?.providerName == currentProviderName,
  514. );
  515. return model?.displayName ?? "";
  516. }, [models, currentModel, currentProviderName]);
  517. const [showModelSelector, setShowModelSelector] = useState(false);
  518. const [showPluginSelector, setShowPluginSelector] = useState(false);
  519. const [showUploadImage, setShowUploadImage] = useState(false);
  520. type GuessList = string[]
  521. const [guessList, setGuessList] = useState<GuessList>([]);
  522. const [showSizeSelector, setShowSizeSelector] = useState(false);
  523. const dalle3Sizes: DalleSize[] = ["1024x1024", "1792x1024", "1024x1792"];
  524. const currentSize =
  525. chatStore.currentSession().mask.modelConfig?.size ?? "1024x1024";
  526. const session = chatStore.currentSession();
  527. useEffect(() => {
  528. const show = isVisionModel(currentModel);
  529. setShowUploadImage(show);
  530. if (!show) {
  531. props.setAttachImages([]);
  532. props.setUploading(false);
  533. }
  534. // if current model is not available
  535. // switch to first available model
  536. const isUnavaliableModel = !models.some((m) => m.name === currentModel);
  537. if (isUnavaliableModel && models.length > 0) {
  538. // show next model to default model if exist
  539. let nextModel = models.find((model) => model.isDefault) || models[0];
  540. chatStore.updateCurrentSession((session) => {
  541. session.mask.modelConfig.model = nextModel.name;
  542. session.mask.modelConfig.providerName = nextModel?.provider?.providerName as ServiceProvider;
  543. });
  544. showToast(
  545. nextModel?.provider?.providerName == "ByteDance"
  546. ? nextModel.displayName
  547. : nextModel.name,
  548. );
  549. }
  550. }, [chatStore, currentModel, models]);
  551. return (
  552. <div className={styles["chat-input-actions"]}>
  553. {showModelSelector && (
  554. <Selector
  555. defaultSelectedValue={`${currentModel}@${currentProviderName}`}
  556. items={models.map((m) => ({
  557. title: `${m.displayName}${m?.provider?.providerName
  558. ? "(" + m?.provider?.providerName + ")"
  559. : ""
  560. }`,
  561. value: `${m.name}@${m?.provider?.providerName}`,
  562. }))}
  563. onClose={() => setShowModelSelector(false)}
  564. onSelection={(s) => {
  565. if (s.length === 0) return;
  566. const [model, providerName] = s[0].split("@");
  567. chatStore.updateCurrentSession((session) => {
  568. session.mask.modelConfig.model = model as ModelType;
  569. session.mask.modelConfig.providerName =
  570. providerName as ServiceProvider;
  571. session.mask.syncGlobalConfig = false;
  572. });
  573. if (providerName == "ByteDance") {
  574. const selectedModel = models.find(
  575. (m) =>
  576. m.name == model && m?.provider?.providerName == providerName,
  577. );
  578. showToast(selectedModel?.displayName ?? "");
  579. } else {
  580. showToast(model);
  581. }
  582. }}
  583. />
  584. )}
  585. {isDalle3(currentModel) && (
  586. <ChatAction
  587. onClick={() => setShowSizeSelector(true)}
  588. text={currentSize}
  589. icon={<SizeIcon />}
  590. />
  591. )}
  592. {showSizeSelector && (
  593. <Selector
  594. defaultSelectedValue={currentSize}
  595. items={dalle3Sizes.map((m) => ({
  596. title: m,
  597. value: m,
  598. }))}
  599. onClose={() => setShowSizeSelector(false)}
  600. onSelection={(s) => {
  601. if (s.length === 0) return;
  602. const size = s[0];
  603. chatStore.updateCurrentSession((session) => {
  604. session.mask.modelConfig.size = size;
  605. });
  606. showToast(size);
  607. }}
  608. />
  609. )}
  610. {showPluginSelector && (
  611. <Selector
  612. multiple
  613. defaultSelectedValue={chatStore.currentSession().mask?.plugin}
  614. items={[
  615. {
  616. title: Locale.Plugin.Artifacts,
  617. value: Plugin.Artifacts,
  618. },
  619. ]}
  620. onClose={() => setShowPluginSelector(false)}
  621. onSelection={(s) => {
  622. const plugin = s[0];
  623. chatStore.updateCurrentSession((session) => {
  624. session.mask.plugin = s;
  625. });
  626. if (plugin) {
  627. showToast(plugin);
  628. }
  629. }}
  630. />
  631. )}
  632. </div>
  633. );
  634. }
  635. export function EditMessageModal(props: { onClose: () => void }) {
  636. const chatStore = useChatStore();
  637. const session = chatStore.currentSession();
  638. const [messages, setMessages] = useState(session.messages.slice());
  639. return (
  640. <div className="modal-mask">
  641. <Modal
  642. title={Locale.Chat.EditMessage.Title}
  643. onClose={props.onClose}
  644. actions={[
  645. <IconButton
  646. text={Locale.UI.Cancel}
  647. icon={<CancelIcon />}
  648. key="cancel"
  649. onClick={() => {
  650. props.onClose();
  651. }}
  652. />,
  653. <IconButton
  654. type="primary"
  655. text={Locale.UI.Confirm}
  656. icon={<ConfirmIcon />}
  657. key="ok"
  658. onClick={() => {
  659. chatStore.updateCurrentSession(
  660. (session) => (session.messages = messages),
  661. );
  662. props.onClose();
  663. }}
  664. />,
  665. ]}
  666. >
  667. <List>
  668. <ListItem
  669. title={Locale.Chat.EditMessage.Topic.Title}
  670. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  671. >
  672. <input
  673. type="text"
  674. value={session.topic}
  675. onInput={(e) =>
  676. chatStore.updateCurrentSession(
  677. (session) => (session.topic = e.currentTarget.value),
  678. )
  679. }
  680. ></input>
  681. </ListItem>
  682. </List>
  683. <ContextPrompts
  684. context={messages}
  685. updateContext={(updater) => {
  686. const newMessages = messages.slice();
  687. updater(newMessages);
  688. setMessages(newMessages);
  689. }}
  690. />
  691. </Modal>
  692. </div>
  693. );
  694. }
  695. export function DeleteImageButton(props: { deleteImage: () => void }) {
  696. return (
  697. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  698. <DeleteIcon />
  699. </div>
  700. );
  701. }
  702. function _Chat() {
  703. type RenderMessage = ChatMessage & { preview?: boolean };
  704. const chatStore = useChatStore();
  705. const session = chatStore.currentSession();
  706. const config = useAppConfig();
  707. const fontSize = config.fontSize;
  708. const fontFamily = config.fontFamily;
  709. const [showExport, setShowExport] = useState(false);
  710. const inputRef = useRef<HTMLTextAreaElement>(null);
  711. const [userInput, setUserInput] = useState("");
  712. const [isLoading, setIsLoading] = useState(false);
  713. const { submitKey, shouldSubmit } = useSubmitHandler();
  714. const scrollRef = useRef<HTMLDivElement>(null);
  715. const isScrolledToBottom = scrollRef?.current
  716. ? Math.abs(
  717. scrollRef.current.scrollHeight -
  718. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  719. ) <= 1
  720. : false;
  721. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  722. scrollRef,
  723. isScrolledToBottom,
  724. );
  725. const [hitBottom, setHitBottom] = useState(true);
  726. const isMobileScreen = useMobileScreen();
  727. const navigate = useNavigate();
  728. const [attachImages, setAttachImages] = useState<string[]>([]);
  729. const [uploading, setUploading] = useState(false);
  730. // prompt hints
  731. const promptStore = usePromptStore();
  732. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  733. const onSearch = useDebouncedCallback(
  734. (text: string) => {
  735. const matchedPrompts = promptStore.search(text);
  736. setPromptHints(matchedPrompts);
  737. },
  738. 100,
  739. { leading: true, trailing: true },
  740. );
  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. useEffect(() => {
  1373. chatStore.setModel('DeepSeek');
  1374. }, []);
  1375. return <_Chat key={sessionIndex}></_Chat>;
  1376. }