home.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. "use client";
  2. import { useState, useRef, useEffect } from "react";
  3. import { IconButton } from "./button";
  4. import styles from "./home.module.scss";
  5. import SettingsIcon from "../icons/settings.svg";
  6. import GithubIcon from "../icons/github.svg";
  7. import ChatGptIcon from "../icons/chatgpt.svg";
  8. import SendWhiteIcon from "../icons/send-white.svg";
  9. import BrainIcon from "../icons/brain.svg";
  10. import ExportIcon from "../icons/export.svg";
  11. import BotIcon from "../icons/bot.svg";
  12. import AddIcon from "../icons/add.svg";
  13. import DeleteIcon from "../icons/delete.svg";
  14. import LoadingIcon from "../icons/three-dots.svg";
  15. import MenuIcon from "../icons/menu.svg";
  16. import CloseIcon from "../icons/close.svg";
  17. import CopyIcon from "../icons/copy.svg";
  18. import DownloadIcon from "../icons/download.svg";
  19. import { Message, SubmitKey, useChatStore, ChatSession } from "../store";
  20. import { showModal } from "./ui-lib";
  21. import { copyToClipboard, downloadAs, isIOS, selectOrCopy } from "../utils";
  22. import Locale from "../locales";
  23. import dynamic from "next/dynamic";
  24. export function Loading(props: { noLogo?: boolean }) {
  25. return (
  26. <div className={styles["loading-content"]}>
  27. {!props.noLogo && <BotIcon />}
  28. <LoadingIcon />
  29. </div>
  30. );
  31. }
  32. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  33. loading: () => <LoadingIcon />,
  34. });
  35. const Settings = dynamic(async () => (await import("./settings")).Settings, {
  36. loading: () => <Loading noLogo />,
  37. });
  38. const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, {
  39. loading: () => <LoadingIcon />,
  40. });
  41. export function Avatar(props: { role: Message["role"] }) {
  42. const config = useChatStore((state) => state.config);
  43. if (props.role === "assistant") {
  44. return <BotIcon className={styles["user-avtar"]} />;
  45. }
  46. return (
  47. <div className={styles["user-avtar"]}>
  48. <Emoji unified={config.avatar} size={18} />
  49. </div>
  50. );
  51. }
  52. export function ChatItem(props: {
  53. onClick?: () => void;
  54. onDelete?: () => void;
  55. title: string;
  56. count: number;
  57. time: string;
  58. selected: boolean;
  59. }) {
  60. return (
  61. <div
  62. className={`${styles["chat-item"]} ${
  63. props.selected && styles["chat-item-selected"]
  64. }`}
  65. onClick={props.onClick}
  66. >
  67. <div className={styles["chat-item-title"]}>{props.title}</div>
  68. <div className={styles["chat-item-info"]}>
  69. <div className={styles["chat-item-count"]}>
  70. {Locale.ChatItem.ChatItemCount(props.count)}
  71. </div>
  72. <div className={styles["chat-item-date"]}>{props.time}</div>
  73. </div>
  74. <div className={styles["chat-item-delete"]} onClick={props.onDelete}>
  75. <DeleteIcon />
  76. </div>
  77. </div>
  78. );
  79. }
  80. export function ChatList() {
  81. const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
  82. (state) => [
  83. state.sessions,
  84. state.currentSessionIndex,
  85. state.selectSession,
  86. state.removeSession,
  87. ]
  88. );
  89. return (
  90. <div className={styles["chat-list"]}>
  91. {sessions.map((item, i) => (
  92. <ChatItem
  93. title={item.topic}
  94. time={item.lastUpdate}
  95. count={item.messages.length}
  96. key={i}
  97. selected={i === selectedIndex}
  98. onClick={() => selectSession(i)}
  99. onDelete={() => removeSession(i)}
  100. />
  101. ))}
  102. </div>
  103. );
  104. }
  105. function useSubmitHandler() {
  106. const config = useChatStore((state) => state.config);
  107. const submitKey = config.submitKey;
  108. const shouldSubmit = (e: KeyboardEvent) => {
  109. if (e.key !== "Enter") return false;
  110. return (
  111. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  112. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  113. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  114. config.submitKey === SubmitKey.Enter
  115. );
  116. };
  117. return {
  118. submitKey,
  119. shouldSubmit,
  120. };
  121. }
  122. export function Chat(props: { showSideBar?: () => void }) {
  123. type RenderMessage = Message & { preview?: boolean };
  124. const session = useChatStore((state) => state.currentSession());
  125. const [userInput, setUserInput] = useState("");
  126. const [isLoading, setIsLoading] = useState(false);
  127. const { submitKey, shouldSubmit } = useSubmitHandler();
  128. const onUserInput = useChatStore((state) => state.onUserInput);
  129. const onUserSubmit = () => {
  130. if (userInput.length <= 0) return;
  131. setIsLoading(true);
  132. onUserInput(userInput).then(() => setIsLoading(false));
  133. setUserInput("");
  134. };
  135. const onInputKeyDown = (e: KeyboardEvent) => {
  136. if (shouldSubmit(e)) {
  137. onUserSubmit();
  138. e.preventDefault();
  139. }
  140. };
  141. const latestMessageRef = useRef<HTMLDivElement>(null);
  142. const messages = (session.messages as RenderMessage[])
  143. .concat(
  144. isLoading
  145. ? [
  146. {
  147. role: "assistant",
  148. content: "……",
  149. date: new Date().toLocaleString(),
  150. preview: true,
  151. },
  152. ]
  153. : []
  154. )
  155. .concat(
  156. userInput.length > 0
  157. ? [
  158. {
  159. role: "user",
  160. content: userInput,
  161. date: new Date().toLocaleString(),
  162. preview: true,
  163. },
  164. ]
  165. : []
  166. );
  167. useEffect(() => {
  168. const dom = latestMessageRef.current;
  169. if (dom && !isIOS()) {
  170. dom.scrollIntoView({
  171. behavior: "smooth",
  172. block: "end",
  173. });
  174. }
  175. });
  176. return (
  177. <div className={styles.chat} key={session.id}>
  178. <div className={styles["window-header"]}>
  179. <div
  180. className={styles["window-header-title"]}
  181. onClick={props?.showSideBar}
  182. >
  183. <div className={styles["window-header-main-title"]}>
  184. {session.topic}
  185. </div>
  186. <div className={styles["window-header-sub-title"]}>
  187. {Locale.Chat.SubTitle(session.messages.length)}
  188. </div>
  189. </div>
  190. <div className={styles["window-actions"]}>
  191. <div className={styles["window-action-button"] + " " + styles.mobile}>
  192. <IconButton
  193. icon={<MenuIcon />}
  194. bordered
  195. title={Locale.Chat.Actions.ChatList}
  196. onClick={props?.showSideBar}
  197. />
  198. </div>
  199. <div className={styles["window-action-button"]}>
  200. <IconButton
  201. icon={<BrainIcon />}
  202. bordered
  203. title={Locale.Chat.Actions.CompressedHistory}
  204. onClick={() => {
  205. showMemoryPrompt(session);
  206. }}
  207. />
  208. </div>
  209. <div className={styles["window-action-button"]}>
  210. <IconButton
  211. icon={<ExportIcon />}
  212. bordered
  213. title={Locale.Chat.Actions.Export}
  214. onClick={() => {
  215. exportMessages(session.messages, session.topic);
  216. }}
  217. />
  218. </div>
  219. </div>
  220. </div>
  221. <div className={styles["chat-body"]}>
  222. {messages.map((message, i) => {
  223. const isUser = message.role === "user";
  224. return (
  225. <div
  226. key={i}
  227. className={
  228. isUser ? styles["chat-message-user"] : styles["chat-message"]
  229. }
  230. >
  231. <div className={styles["chat-message-container"]}>
  232. <div className={styles["chat-message-avatar"]}>
  233. <Avatar role={message.role} />
  234. </div>
  235. {(message.preview || message.streaming) && (
  236. <div className={styles["chat-message-status"]}>
  237. {Locale.Chat.Typing}
  238. </div>
  239. )}
  240. <div className={styles["chat-message-item"]}>
  241. {(message.preview || message.content.length === 0) &&
  242. !isUser ? (
  243. <LoadingIcon />
  244. ) : (
  245. <div
  246. className="markdown-body"
  247. onContextMenu={(e) => {
  248. if (selectOrCopy(e.currentTarget, message.content)) {
  249. e.preventDefault();
  250. }
  251. }}
  252. >
  253. <Markdown content={message.content} />
  254. </div>
  255. )}
  256. </div>
  257. {!isUser && !message.preview && (
  258. <div className={styles["chat-message-actions"]}>
  259. <div className={styles["chat-message-action-date"]}>
  260. {message.date.toLocaleString()}
  261. </div>
  262. </div>
  263. )}
  264. </div>
  265. </div>
  266. );
  267. })}
  268. <span ref={latestMessageRef} style={{ opacity: 0 }}>
  269. -
  270. </span>
  271. </div>
  272. <div className={styles["chat-input-panel"]}>
  273. <div className={styles["chat-input-panel-inner"]}>
  274. <textarea
  275. className={styles["chat-input"]}
  276. placeholder={Locale.Chat.Input(submitKey)}
  277. rows={3}
  278. onInput={(e) => setUserInput(e.currentTarget.value)}
  279. value={userInput}
  280. onKeyDown={(e) => onInputKeyDown(e as any)}
  281. />
  282. <IconButton
  283. icon={<SendWhiteIcon />}
  284. text={Locale.Chat.Send}
  285. className={styles["chat-input-send"] + " no-dark"}
  286. onClick={onUserSubmit}
  287. />
  288. </div>
  289. </div>
  290. </div>
  291. );
  292. }
  293. function useSwitchTheme() {
  294. const config = useChatStore((state) => state.config);
  295. useEffect(() => {
  296. document.body.classList.remove("light");
  297. document.body.classList.remove("dark");
  298. if (config.theme === "dark") {
  299. document.body.classList.add("dark");
  300. } else if (config.theme === "light") {
  301. document.body.classList.add("light");
  302. }
  303. }, [config.theme]);
  304. }
  305. function exportMessages(messages: Message[], topic: string) {
  306. const mdText =
  307. `# ${topic}\n\n` +
  308. messages
  309. .map((m) => {
  310. return m.role === "user" ? `## ${m.content}` : m.content.trim();
  311. })
  312. .join("\n\n");
  313. const filename = `${topic}.md`;
  314. showModal({
  315. title: Locale.Export.Title,
  316. children: (
  317. <div className="markdown-body">
  318. <pre className={styles["export-content"]}>{mdText}</pre>
  319. </div>
  320. ),
  321. actions: [
  322. <IconButton
  323. key="copy"
  324. icon={<CopyIcon />}
  325. bordered
  326. text={Locale.Export.Copy}
  327. onClick={() => copyToClipboard(mdText)}
  328. />,
  329. <IconButton
  330. key="download"
  331. icon={<DownloadIcon />}
  332. bordered
  333. text={Locale.Export.Download}
  334. onClick={() => downloadAs(mdText, filename)}
  335. />,
  336. ],
  337. });
  338. }
  339. function showMemoryPrompt(session: ChatSession) {
  340. showModal({
  341. title: `${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`,
  342. children: (
  343. <div className="markdown-body">
  344. <pre className={styles["export-content"]}>
  345. {session.memoryPrompt || Locale.Memory.EmptyContent}
  346. </pre>
  347. </div>
  348. ),
  349. actions: [
  350. <IconButton
  351. key="copy"
  352. icon={<CopyIcon />}
  353. bordered
  354. text={Locale.Memory.Copy}
  355. onClick={() => copyToClipboard(session.memoryPrompt)}
  356. />,
  357. ],
  358. });
  359. }
  360. export function Home() {
  361. const [createNewSession, currentIndex, removeSession] = useChatStore(
  362. (state) => [
  363. state.newSession,
  364. state.currentSessionIndex,
  365. state.removeSession,
  366. ]
  367. );
  368. const loading = !useChatStore?.persist?.hasHydrated();
  369. const [showSideBar, setShowSideBar] = useState(true);
  370. // setting
  371. const [openSettings, setOpenSettings] = useState(false);
  372. const config = useChatStore((state) => state.config);
  373. useSwitchTheme();
  374. if (loading) {
  375. return <Loading />;
  376. }
  377. return (
  378. <div
  379. className={`${
  380. config.tightBorder ? styles["tight-container"] : styles.container
  381. }`}
  382. >
  383. <div
  384. className={styles.sidebar + ` ${showSideBar && styles["sidebar-show"]}`}
  385. >
  386. <div className={styles["sidebar-header"]}>
  387. <div className={styles["sidebar-title"]}>ChatGPT Next</div>
  388. <div className={styles["sidebar-sub-title"]}>
  389. Build your own AI assistant.
  390. </div>
  391. <div className={styles["sidebar-logo"]}>
  392. <ChatGptIcon />
  393. </div>
  394. </div>
  395. <div
  396. className={styles["sidebar-body"]}
  397. onClick={() => {
  398. setOpenSettings(false);
  399. setShowSideBar(false);
  400. }}
  401. >
  402. <ChatList />
  403. </div>
  404. <div className={styles["sidebar-tail"]}>
  405. <div className={styles["sidebar-actions"]}>
  406. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  407. <IconButton
  408. icon={<CloseIcon />}
  409. onClick={() => {
  410. if (confirm(Locale.Home.DeleteChat)) {
  411. removeSession(currentIndex);
  412. }
  413. }}
  414. />
  415. </div>
  416. <div className={styles["sidebar-action"]}>
  417. <IconButton
  418. icon={<SettingsIcon />}
  419. onClick={() => {
  420. setOpenSettings(true);
  421. setShowSideBar(false);
  422. }}
  423. />
  424. </div>
  425. <div className={styles["sidebar-action"]}>
  426. <a
  427. href="https://github.com/Yidadaa/ChatGPT-Next-Web"
  428. target="_blank"
  429. >
  430. <IconButton icon={<GithubIcon />} />
  431. </a>
  432. </div>
  433. </div>
  434. <div>
  435. <IconButton
  436. icon={<AddIcon />}
  437. text={Locale.Home.NewChat}
  438. onClick={createNewSession}
  439. />
  440. </div>
  441. </div>
  442. </div>
  443. <div className={styles["window-content"]}>
  444. {openSettings ? (
  445. <Settings
  446. closeSettings={() => {
  447. setOpenSettings(false);
  448. setShowSideBar(true);
  449. }}
  450. />
  451. ) : (
  452. <Chat key="chat" showSideBar={() => setShowSideBar(true)} />
  453. )}
  454. </div>
  455. </div>
  456. );
  457. }