home.tsx 14 KB

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