chat.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. import { useDebounce, useDebouncedCallback } from "use-debounce";
  2. import { memo, useState, useRef, useEffect, useLayoutEffect } from "react";
  3. import SendWhiteIcon from "../icons/send-white.svg";
  4. import BrainIcon from "../icons/brain.svg";
  5. import ExportIcon from "../icons/share.svg";
  6. import ReturnIcon from "../icons/return.svg";
  7. import CopyIcon from "../icons/copy.svg";
  8. import DownloadIcon from "../icons/download.svg";
  9. import LoadingIcon from "../icons/three-dots.svg";
  10. import BotIcon from "../icons/bot.svg";
  11. import AddIcon from "../icons/add.svg";
  12. import DeleteIcon from "../icons/delete.svg";
  13. import MaxIcon from "../icons/max.svg";
  14. import MinIcon from "../icons/min.svg";
  15. import {
  16. Message,
  17. SubmitKey,
  18. useChatStore,
  19. BOT_HELLO,
  20. ROLES,
  21. createMessage,
  22. useAccessStore,
  23. } from "../store";
  24. import {
  25. copyToClipboard,
  26. downloadAs,
  27. getEmojiUrl,
  28. isMobileScreen,
  29. selectOrCopy,
  30. autoGrowTextArea,
  31. } from "../utils";
  32. import dynamic from "next/dynamic";
  33. import { ControllerPool } from "../requests";
  34. import { Prompt, usePromptStore } from "../store/prompt";
  35. import Locale from "../locales";
  36. import { IconButton } from "./button";
  37. import styles from "./home.module.scss";
  38. import chatStyle from "./chat.module.scss";
  39. import { Input, Modal, showModal } from "./ui-lib";
  40. const Markdown = dynamic(
  41. async () => memo((await import("./markdown")).Markdown),
  42. {
  43. loading: () => <LoadingIcon />,
  44. },
  45. );
  46. const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, {
  47. loading: () => <LoadingIcon />,
  48. });
  49. export function Avatar(props: { role: Message["role"] }) {
  50. const config = useChatStore((state) => state.config);
  51. if (props.role !== "user") {
  52. return <BotIcon className={styles["user-avtar"]} />;
  53. }
  54. return (
  55. <div className={styles["user-avtar"]}>
  56. <Emoji unified={config.avatar} size={18} getEmojiUrl={getEmojiUrl} />
  57. </div>
  58. );
  59. }
  60. function exportMessages(messages: Message[], topic: string) {
  61. const mdText =
  62. `# ${topic}\n\n` +
  63. messages
  64. .map((m) => {
  65. return m.role === "user"
  66. ? `## ${Locale.Export.MessageFromYou}:\n${m.content}`
  67. : `## ${Locale.Export.MessageFromChatGPT}:\n${m.content.trim()}`;
  68. })
  69. .join("\n\n");
  70. const filename = `${topic}.md`;
  71. showModal({
  72. title: Locale.Export.Title,
  73. children: (
  74. <div className="markdown-body">
  75. <pre className={styles["export-content"]}>{mdText}</pre>
  76. </div>
  77. ),
  78. actions: [
  79. <IconButton
  80. key="copy"
  81. icon={<CopyIcon />}
  82. bordered
  83. text={Locale.Export.Copy}
  84. onClick={() => copyToClipboard(mdText)}
  85. />,
  86. <IconButton
  87. key="download"
  88. icon={<DownloadIcon />}
  89. bordered
  90. text={Locale.Export.Download}
  91. onClick={() => downloadAs(mdText, filename)}
  92. />,
  93. ],
  94. });
  95. }
  96. function PromptToast(props: {
  97. showToast?: boolean;
  98. showModal?: boolean;
  99. setShowModal: (_: boolean) => void;
  100. }) {
  101. const chatStore = useChatStore();
  102. const session = chatStore.currentSession();
  103. const context = session.context;
  104. const addContextPrompt = (prompt: Message) => {
  105. chatStore.updateCurrentSession((session) => {
  106. session.context.push(prompt);
  107. });
  108. };
  109. const removeContextPrompt = (i: number) => {
  110. chatStore.updateCurrentSession((session) => {
  111. session.context.splice(i, 1);
  112. });
  113. };
  114. const updateContextPrompt = (i: number, prompt: Message) => {
  115. chatStore.updateCurrentSession((session) => {
  116. session.context[i] = prompt;
  117. });
  118. };
  119. return (
  120. <div className={chatStyle["prompt-toast"]} key="prompt-toast">
  121. {props.showToast && (
  122. <div
  123. className={chatStyle["prompt-toast-inner"] + " clickable"}
  124. role="button"
  125. onClick={() => props.setShowModal(true)}
  126. >
  127. <BrainIcon />
  128. <span className={chatStyle["prompt-toast-content"]}>
  129. {Locale.Context.Toast(context.length)}
  130. </span>
  131. </div>
  132. )}
  133. {props.showModal && (
  134. <div className="modal-mask">
  135. <Modal
  136. title={Locale.Context.Edit}
  137. onClose={() => props.setShowModal(false)}
  138. actions={[
  139. <IconButton
  140. key="reset"
  141. icon={<CopyIcon />}
  142. bordered
  143. text={Locale.Memory.Reset}
  144. onClick={() =>
  145. confirm(Locale.Memory.ResetConfirm) &&
  146. chatStore.resetSession()
  147. }
  148. />,
  149. <IconButton
  150. key="copy"
  151. icon={<CopyIcon />}
  152. bordered
  153. text={Locale.Memory.Copy}
  154. onClick={() => copyToClipboard(session.memoryPrompt)}
  155. />,
  156. ]}
  157. >
  158. <>
  159. <div className={chatStyle["context-prompt"]}>
  160. {context.map((c, i) => (
  161. <div className={chatStyle["context-prompt-row"]} key={i}>
  162. <select
  163. value={c.role}
  164. className={chatStyle["context-role"]}
  165. onChange={(e) =>
  166. updateContextPrompt(i, {
  167. ...c,
  168. role: e.target.value as any,
  169. })
  170. }
  171. >
  172. {ROLES.map((r) => (
  173. <option key={r} value={r}>
  174. {r}
  175. </option>
  176. ))}
  177. </select>
  178. <Input
  179. value={c.content}
  180. type="text"
  181. className={chatStyle["context-content"]}
  182. rows={1}
  183. onInput={(e) =>
  184. updateContextPrompt(i, {
  185. ...c,
  186. content: e.currentTarget.value as any,
  187. })
  188. }
  189. />
  190. <IconButton
  191. icon={<DeleteIcon />}
  192. className={chatStyle["context-delete-button"]}
  193. onClick={() => removeContextPrompt(i)}
  194. bordered
  195. />
  196. </div>
  197. ))}
  198. <div className={chatStyle["context-prompt-row"]}>
  199. <IconButton
  200. icon={<AddIcon />}
  201. text={Locale.Context.Add}
  202. bordered
  203. className={chatStyle["context-prompt-button"]}
  204. onClick={() =>
  205. addContextPrompt({
  206. role: "system",
  207. content: "",
  208. date: "",
  209. })
  210. }
  211. />
  212. </div>
  213. </div>
  214. <div className={chatStyle["memory-prompt"]}>
  215. <div className={chatStyle["memory-prompt-title"]}>
  216. <span>
  217. {Locale.Memory.Title} ({session.lastSummarizeIndex} of{" "}
  218. {session.messages.length})
  219. </span>
  220. <label className={chatStyle["memory-prompt-action"]}>
  221. {Locale.Memory.Send}
  222. <input
  223. type="checkbox"
  224. checked={session.sendMemory}
  225. onChange={() =>
  226. chatStore.updateCurrentSession(
  227. (session) =>
  228. (session.sendMemory = !session.sendMemory),
  229. )
  230. }
  231. ></input>
  232. </label>
  233. </div>
  234. <div className={chatStyle["memory-prompt-content"]}>
  235. {session.memoryPrompt || Locale.Memory.EmptyContent}
  236. </div>
  237. </div>
  238. </>
  239. </Modal>
  240. </div>
  241. )}
  242. </div>
  243. );
  244. }
  245. function useSubmitHandler() {
  246. const config = useChatStore((state) => state.config);
  247. const submitKey = config.submitKey;
  248. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  249. if (e.key !== "Enter") return false;
  250. if (e.key === "Enter" && e.nativeEvent.isComposing) return false;
  251. return (
  252. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  253. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  254. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  255. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  256. (config.submitKey === SubmitKey.Enter &&
  257. !e.altKey &&
  258. !e.ctrlKey &&
  259. !e.shiftKey &&
  260. !e.metaKey)
  261. );
  262. };
  263. return {
  264. submitKey,
  265. shouldSubmit,
  266. };
  267. }
  268. export function PromptHints(props: {
  269. prompts: Prompt[];
  270. onPromptSelect: (prompt: Prompt) => void;
  271. }) {
  272. if (props.prompts.length === 0) return null;
  273. return (
  274. <div className={styles["prompt-hints"]}>
  275. {props.prompts.map((prompt, i) => (
  276. <div
  277. className={styles["prompt-hint"]}
  278. key={prompt.title + i.toString()}
  279. onClick={() => props.onPromptSelect(prompt)}
  280. >
  281. <div className={styles["hint-title"]}>{prompt.title}</div>
  282. <div className={styles["hint-content"]}>{prompt.content}</div>
  283. </div>
  284. ))}
  285. </div>
  286. );
  287. }
  288. function useScrollToBottom() {
  289. // for auto-scroll
  290. const scrollRef = useRef<HTMLDivElement>(null);
  291. const [autoScroll, setAutoScroll] = useState(true);
  292. // auto scroll
  293. useLayoutEffect(() => {
  294. const dom = scrollRef.current;
  295. if (dom && autoScroll) {
  296. setTimeout(() => (dom.scrollTop = dom.scrollHeight), 1);
  297. }
  298. });
  299. return {
  300. scrollRef,
  301. autoScroll,
  302. setAutoScroll,
  303. };
  304. }
  305. export function Chat(props: {
  306. showSideBar?: () => void;
  307. sideBarShowing?: boolean;
  308. }) {
  309. type RenderMessage = Message & { preview?: boolean };
  310. const chatStore = useChatStore();
  311. const [session, sessionIndex] = useChatStore((state) => [
  312. state.currentSession(),
  313. state.currentSessionIndex,
  314. ]);
  315. const fontSize = useChatStore((state) => state.config.fontSize);
  316. const inputRef = useRef<HTMLTextAreaElement>(null);
  317. const [userInput, setUserInput] = useState("");
  318. const [beforeInput, setBeforeInput] = useState("");
  319. const [isLoading, setIsLoading] = useState(false);
  320. const { submitKey, shouldSubmit } = useSubmitHandler();
  321. const { scrollRef, setAutoScroll } = useScrollToBottom();
  322. const [hitBottom, setHitBottom] = useState(false);
  323. const onChatBodyScroll = (e: HTMLElement) => {
  324. const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 20;
  325. setHitBottom(isTouchBottom);
  326. };
  327. // prompt hints
  328. const promptStore = usePromptStore();
  329. const [promptHints, setPromptHints] = useState<Prompt[]>([]);
  330. const onSearch = useDebouncedCallback(
  331. (text: string) => {
  332. setPromptHints(promptStore.search(text));
  333. },
  334. 100,
  335. { leading: true, trailing: true },
  336. );
  337. const onPromptSelect = (prompt: Prompt) => {
  338. setUserInput(prompt.content);
  339. setPromptHints([]);
  340. inputRef.current?.focus();
  341. };
  342. const scrollInput = () => {
  343. const dom = inputRef.current;
  344. if (!dom) return;
  345. const paddingBottomNum: number = parseInt(
  346. window.getComputedStyle(dom).paddingBottom,
  347. 10,
  348. );
  349. dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
  350. };
  351. // auto grow input
  352. const [inputRows, setInputRows] = useState(2);
  353. const measure = useDebouncedCallback(
  354. () => {
  355. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  356. const inputRows = Math.min(
  357. 5,
  358. Math.max(2 + Number(!isMobileScreen()), rows),
  359. );
  360. setInputRows(inputRows);
  361. },
  362. 100,
  363. {
  364. leading: true,
  365. trailing: true,
  366. },
  367. );
  368. // eslint-disable-next-line react-hooks/exhaustive-deps
  369. useEffect(measure, [userInput]);
  370. // only search prompts when user input is short
  371. const SEARCH_TEXT_LIMIT = 30;
  372. const onInput = (text: string) => {
  373. scrollInput();
  374. setUserInput(text);
  375. const n = text.trim().length;
  376. // clear search results
  377. if (n === 0) {
  378. setPromptHints([]);
  379. } else if (!chatStore.config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  380. // check if need to trigger auto completion
  381. if (text.startsWith("/")) {
  382. let searchText = text.slice(1);
  383. onSearch(searchText);
  384. }
  385. }
  386. };
  387. // submit user input
  388. const onUserSubmit = () => {
  389. if (userInput.length <= 0) return;
  390. setIsLoading(true);
  391. chatStore.onUserInput(userInput).then(() => setIsLoading(false));
  392. setBeforeInput(userInput);
  393. setUserInput("");
  394. setPromptHints([]);
  395. if (!isMobileScreen()) inputRef.current?.focus();
  396. setAutoScroll(true);
  397. };
  398. // stop response
  399. const onUserStop = (messageId: number) => {
  400. ControllerPool.stop(sessionIndex, messageId);
  401. };
  402. // check if should send message
  403. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  404. // if ArrowUp and no userInput
  405. if (e.key === "ArrowUp" && userInput.length <= 0) {
  406. setUserInput(beforeInput);
  407. e.preventDefault();
  408. return;
  409. }
  410. if (shouldSubmit(e)) {
  411. onUserSubmit();
  412. e.preventDefault();
  413. }
  414. };
  415. const onRightClick = (e: any, message: Message) => {
  416. // auto fill user input
  417. if (message.role === "user") {
  418. setUserInput(message.content);
  419. }
  420. // copy to clipboard
  421. if (selectOrCopy(e.currentTarget, message.content)) {
  422. e.preventDefault();
  423. }
  424. };
  425. const onResend = (botIndex: number) => {
  426. // find last user input message and resend
  427. for (let i = botIndex; i >= 0; i -= 1) {
  428. if (messages[i].role === "user") {
  429. setIsLoading(true);
  430. chatStore
  431. .onUserInput(messages[i].content)
  432. .then(() => setIsLoading(false));
  433. chatStore.updateCurrentSession((session) =>
  434. session.messages.splice(i, 2),
  435. );
  436. inputRef.current?.focus();
  437. return;
  438. }
  439. }
  440. };
  441. const config = useChatStore((state) => state.config);
  442. const context: RenderMessage[] = session.context.slice();
  443. const accessStore = useAccessStore();
  444. if (
  445. context.length === 0 &&
  446. session.messages.at(0)?.content !== BOT_HELLO.content
  447. ) {
  448. const copiedHello = Object.assign({}, BOT_HELLO);
  449. if (!accessStore.isAuthorized()) {
  450. copiedHello.content = Locale.Error.Unauthorized;
  451. }
  452. context.push(copiedHello);
  453. }
  454. // preview messages
  455. const messages = context
  456. .concat(session.messages as RenderMessage[])
  457. .concat(
  458. isLoading
  459. ? [
  460. {
  461. ...createMessage({
  462. role: "assistant",
  463. content: "……",
  464. }),
  465. preview: true,
  466. },
  467. ]
  468. : [],
  469. )
  470. .concat(
  471. userInput.length > 0 && config.sendPreviewBubble
  472. ? [
  473. {
  474. ...createMessage({
  475. role: "user",
  476. content: userInput,
  477. }),
  478. preview: true,
  479. },
  480. ]
  481. : [],
  482. );
  483. const [showPromptModal, setShowPromptModal] = useState(false);
  484. // Auto focus
  485. useEffect(() => {
  486. if (props.sideBarShowing && isMobileScreen()) return;
  487. inputRef.current?.focus();
  488. // eslint-disable-next-line react-hooks/exhaustive-deps
  489. }, []);
  490. return (
  491. <div className={styles.chat} key={session.id}>
  492. <div className={styles["window-header"]}>
  493. <div className={styles["window-header-title"]}>
  494. <div
  495. className={`${styles["window-header-main-title"]} ${styles["chat-body-title"]}`}
  496. onClickCapture={() => {
  497. const newTopic = prompt(Locale.Chat.Rename, session.topic);
  498. if (newTopic && newTopic !== session.topic) {
  499. chatStore.updateCurrentSession(
  500. (session) => (session.topic = newTopic!),
  501. );
  502. }
  503. }}
  504. >
  505. {session.topic}
  506. </div>
  507. <div className={styles["window-header-sub-title"]}>
  508. {Locale.Chat.SubTitle(session.messages.length)}
  509. </div>
  510. </div>
  511. <div className={styles["window-actions"]}>
  512. <div className={styles["window-action-button"] + " " + styles.mobile}>
  513. <IconButton
  514. icon={<ReturnIcon />}
  515. bordered
  516. title={Locale.Chat.Actions.ChatList}
  517. onClick={props?.showSideBar}
  518. />
  519. </div>
  520. <div className={styles["window-action-button"]}>
  521. <IconButton
  522. icon={<BrainIcon />}
  523. bordered
  524. title={Locale.Chat.Actions.CompressedHistory}
  525. onClick={() => {
  526. setShowPromptModal(true);
  527. }}
  528. />
  529. </div>
  530. <div className={styles["window-action-button"]}>
  531. <IconButton
  532. icon={<ExportIcon />}
  533. bordered
  534. title={Locale.Chat.Actions.Export}
  535. onClick={() => {
  536. exportMessages(
  537. session.messages.filter((msg) => !msg.isError),
  538. session.topic,
  539. );
  540. }}
  541. />
  542. </div>
  543. {!isMobileScreen() && (
  544. <div className={styles["window-action-button"]}>
  545. <IconButton
  546. icon={chatStore.config.tightBorder ? <MinIcon /> : <MaxIcon />}
  547. bordered
  548. onClick={() => {
  549. chatStore.updateConfig(
  550. (config) => (config.tightBorder = !config.tightBorder),
  551. );
  552. }}
  553. />
  554. </div>
  555. )}
  556. </div>
  557. <PromptToast
  558. showToast={!hitBottom}
  559. showModal={showPromptModal}
  560. setShowModal={setShowPromptModal}
  561. />
  562. </div>
  563. <div
  564. className={styles["chat-body"]}
  565. ref={scrollRef}
  566. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  567. onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
  568. onTouchStart={() => {
  569. inputRef.current?.blur();
  570. setAutoScroll(false);
  571. }}
  572. >
  573. {messages.map((message, i) => {
  574. const isUser = message.role === "user";
  575. return (
  576. <div
  577. key={i}
  578. className={
  579. isUser ? styles["chat-message-user"] : styles["chat-message"]
  580. }
  581. >
  582. <div className={styles["chat-message-container"]}>
  583. <div className={styles["chat-message-avatar"]}>
  584. <Avatar role={message.role} />
  585. </div>
  586. {(message.preview || message.streaming) && (
  587. <div className={styles["chat-message-status"]}>
  588. {Locale.Chat.Typing}
  589. </div>
  590. )}
  591. <div className={styles["chat-message-item"]}>
  592. {!isUser &&
  593. !(message.preview || message.content.length === 0) && (
  594. <div className={styles["chat-message-top-actions"]}>
  595. {message.streaming ? (
  596. <div
  597. className={styles["chat-message-top-action"]}
  598. onClick={() => onUserStop(message.id ?? i)}
  599. >
  600. {Locale.Chat.Actions.Stop}
  601. </div>
  602. ) : (
  603. <div
  604. className={styles["chat-message-top-action"]}
  605. onClick={() => onResend(i)}
  606. >
  607. {Locale.Chat.Actions.Retry}
  608. </div>
  609. )}
  610. <div
  611. className={styles["chat-message-top-action"]}
  612. onClick={() => copyToClipboard(message.content)}
  613. >
  614. {Locale.Chat.Actions.Copy}
  615. </div>
  616. </div>
  617. )}
  618. {(message.preview || message.content.length === 0) &&
  619. !isUser ? (
  620. <LoadingIcon />
  621. ) : (
  622. <div
  623. className="markdown-body"
  624. style={{ fontSize: `${fontSize}px` }}
  625. onContextMenu={(e) => onRightClick(e, message)}
  626. onDoubleClickCapture={() => {
  627. if (!isMobileScreen()) return;
  628. setUserInput(message.content);
  629. }}
  630. >
  631. <Markdown content={message.content} />
  632. </div>
  633. )}
  634. </div>
  635. {!isUser && !message.preview && (
  636. <div className={styles["chat-message-actions"]}>
  637. <div className={styles["chat-message-action-date"]}>
  638. {message.date.toLocaleString()}
  639. </div>
  640. </div>
  641. )}
  642. </div>
  643. </div>
  644. );
  645. })}
  646. </div>
  647. <div className={styles["chat-input-panel"]}>
  648. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  649. <div className={styles["chat-input-panel-inner"]}>
  650. <textarea
  651. ref={inputRef}
  652. className={styles["chat-input"]}
  653. placeholder={Locale.Chat.Input(submitKey)}
  654. onInput={(e) => onInput(e.currentTarget.value)}
  655. value={userInput}
  656. onKeyDown={onInputKeyDown}
  657. onFocus={() => setAutoScroll(true)}
  658. onBlur={() => {
  659. setAutoScroll(false);
  660. setTimeout(() => setPromptHints([]), 500);
  661. }}
  662. autoFocus={!props?.sideBarShowing}
  663. rows={inputRows}
  664. />
  665. <IconButton
  666. icon={<SendWhiteIcon />}
  667. text={Locale.Chat.Send}
  668. className={styles["chat-input-send"]}
  669. noDark
  670. onClick={onUserSubmit}
  671. />
  672. </div>
  673. </div>
  674. </div>
  675. );
  676. }