home.tsx 14 KB

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