settings.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. import { useState, useEffect, useMemo } from "react";
  2. import styles from "./settings.module.scss";
  3. import ResetIcon from "../icons/reload.svg";
  4. import AddIcon from "../icons/add.svg";
  5. import CloseIcon from "../icons/close.svg";
  6. import CopyIcon from "../icons/copy.svg";
  7. import ClearIcon from "../icons/clear.svg";
  8. import LoadingIcon from "../icons/three-dots.svg";
  9. import EditIcon from "../icons/edit.svg";
  10. import EyeIcon from "../icons/eye.svg";
  11. import {
  12. Input,
  13. List,
  14. ListItem,
  15. Modal,
  16. PasswordInput,
  17. Popover,
  18. Select,
  19. } from "./ui-lib";
  20. import { ModelConfigList } from "./model-config";
  21. import { IconButton } from "./button";
  22. import {
  23. SubmitKey,
  24. useChatStore,
  25. Theme,
  26. useUpdateStore,
  27. useAccessStore,
  28. useAppConfig,
  29. } from "../store";
  30. import Locale, {
  31. AllLangs,
  32. ALL_LANG_OPTIONS,
  33. changeLang,
  34. getLang,
  35. } from "../locales";
  36. import { copyToClipboard } from "../utils";
  37. import Link from "next/link";
  38. import { Path, UPDATE_URL } from "../constant";
  39. import { Prompt, SearchService, usePromptStore } from "../store/prompt";
  40. import { ErrorBoundary } from "./error";
  41. import { InputRange } from "./input-range";
  42. import { useNavigate } from "react-router-dom";
  43. import { Avatar, AvatarPicker } from "./emoji";
  44. import { getClientConfig } from "../config/client";
  45. import { useSyncStore } from "../store/sync";
  46. function EditPromptModal(props: { id: number; onClose: () => void }) {
  47. const promptStore = usePromptStore();
  48. const prompt = promptStore.get(props.id);
  49. return prompt ? (
  50. <div className="modal-mask">
  51. <Modal
  52. title={Locale.Settings.Prompt.EditModal.Title}
  53. onClose={props.onClose}
  54. actions={[
  55. <IconButton
  56. key=""
  57. onClick={props.onClose}
  58. text={Locale.UI.Confirm}
  59. bordered
  60. />,
  61. ]}
  62. >
  63. <div className={styles["edit-prompt-modal"]}>
  64. <input
  65. type="text"
  66. value={prompt.title}
  67. readOnly={!prompt.isUser}
  68. className={styles["edit-prompt-title"]}
  69. onInput={(e) =>
  70. promptStore.update(
  71. props.id,
  72. (prompt) => (prompt.title = e.currentTarget.value),
  73. )
  74. }
  75. ></input>
  76. <Input
  77. value={prompt.content}
  78. readOnly={!prompt.isUser}
  79. className={styles["edit-prompt-content"]}
  80. rows={10}
  81. onInput={(e) =>
  82. promptStore.update(
  83. props.id,
  84. (prompt) => (prompt.content = e.currentTarget.value),
  85. )
  86. }
  87. ></Input>
  88. </div>
  89. </Modal>
  90. </div>
  91. ) : null;
  92. }
  93. function UserPromptModal(props: { onClose?: () => void }) {
  94. const promptStore = usePromptStore();
  95. const userPrompts = promptStore.getUserPrompts();
  96. const builtinPrompts = SearchService.builtinPrompts;
  97. const allPrompts = userPrompts.concat(builtinPrompts);
  98. const [searchInput, setSearchInput] = useState("");
  99. const [searchPrompts, setSearchPrompts] = useState<Prompt[]>([]);
  100. const prompts = searchInput.length > 0 ? searchPrompts : allPrompts;
  101. const [editingPromptId, setEditingPromptId] = useState<number>();
  102. useEffect(() => {
  103. if (searchInput.length > 0) {
  104. const searchResult = SearchService.search(searchInput);
  105. setSearchPrompts(searchResult);
  106. } else {
  107. setSearchPrompts([]);
  108. }
  109. }, [searchInput]);
  110. return (
  111. <div className="modal-mask">
  112. <Modal
  113. title={Locale.Settings.Prompt.Modal.Title}
  114. onClose={() => props.onClose?.()}
  115. actions={[
  116. <IconButton
  117. key="add"
  118. onClick={() =>
  119. promptStore.add({
  120. title: "Empty Prompt",
  121. content: "Empty Prompt Content",
  122. })
  123. }
  124. icon={<AddIcon />}
  125. bordered
  126. text={Locale.Settings.Prompt.Modal.Add}
  127. />,
  128. ]}
  129. >
  130. <div className={styles["user-prompt-modal"]}>
  131. <input
  132. type="text"
  133. className={styles["user-prompt-search"]}
  134. placeholder={Locale.Settings.Prompt.Modal.Search}
  135. value={searchInput}
  136. onInput={(e) => setSearchInput(e.currentTarget.value)}
  137. ></input>
  138. <div className={styles["user-prompt-list"]}>
  139. {prompts.map((v, _) => (
  140. <div className={styles["user-prompt-item"]} key={v.id ?? v.title}>
  141. <div className={styles["user-prompt-header"]}>
  142. <div className={styles["user-prompt-title"]}>{v.title}</div>
  143. <div className={styles["user-prompt-content"] + " one-line"}>
  144. {v.content}
  145. </div>
  146. </div>
  147. <div className={styles["user-prompt-buttons"]}>
  148. {v.isUser && (
  149. <IconButton
  150. icon={<ClearIcon />}
  151. className={styles["user-prompt-button"]}
  152. onClick={() => promptStore.remove(v.id!)}
  153. />
  154. )}
  155. {v.isUser ? (
  156. <IconButton
  157. icon={<EditIcon />}
  158. className={styles["user-prompt-button"]}
  159. onClick={() => setEditingPromptId(v.id)}
  160. />
  161. ) : (
  162. <IconButton
  163. icon={<EyeIcon />}
  164. className={styles["user-prompt-button"]}
  165. onClick={() => setEditingPromptId(v.id)}
  166. />
  167. )}
  168. <IconButton
  169. icon={<CopyIcon />}
  170. className={styles["user-prompt-button"]}
  171. onClick={() => copyToClipboard(v.content)}
  172. />
  173. </div>
  174. </div>
  175. ))}
  176. </div>
  177. </div>
  178. </Modal>
  179. {editingPromptId !== undefined && (
  180. <EditPromptModal
  181. id={editingPromptId!}
  182. onClose={() => setEditingPromptId(undefined)}
  183. />
  184. )}
  185. </div>
  186. );
  187. }
  188. function SyncItems() {
  189. const syncStore = useSyncStore();
  190. const webdav = syncStore.webDavConfig;
  191. // not ready: https://github.com/Yidadaa/ChatGPT-Next-Web/issues/920#issuecomment-1609866332
  192. return null;
  193. return (
  194. <List>
  195. <ListItem
  196. title={"上次同步:" + new Date().toLocaleString()}
  197. subTitle={"20 次对话,100 条消息,200 提示词,20 面具"}
  198. >
  199. <IconButton
  200. icon={<ResetIcon />}
  201. text="同步"
  202. onClick={() => {
  203. syncStore.check().then(console.log);
  204. }}
  205. />
  206. </ListItem>
  207. <ListItem
  208. title={"本地备份"}
  209. subTitle={"20 次对话,100 条消息,200 提示词,20 面具"}
  210. ></ListItem>
  211. <ListItem
  212. title={"Web Dav Server"}
  213. subTitle={Locale.Settings.AccessCode.SubTitle}
  214. >
  215. <input
  216. value={webdav.server}
  217. type="text"
  218. placeholder={"https://example.com"}
  219. onChange={(e) => {
  220. syncStore.update(
  221. (config) => (config.server = e.currentTarget.value),
  222. );
  223. }}
  224. />
  225. </ListItem>
  226. <ListItem title="Web Dav User Name" subTitle="user name here">
  227. <input
  228. value={webdav.username}
  229. type="text"
  230. placeholder={"username"}
  231. onChange={(e) => {
  232. syncStore.update(
  233. (config) => (config.username = e.currentTarget.value),
  234. );
  235. }}
  236. />
  237. </ListItem>
  238. <ListItem title="Web Dav Password" subTitle="password here">
  239. <input
  240. value={webdav.password}
  241. type="text"
  242. placeholder={"password"}
  243. onChange={(e) => {
  244. syncStore.update(
  245. (config) => (config.password = e.currentTarget.value),
  246. );
  247. }}
  248. />
  249. </ListItem>
  250. </List>
  251. );
  252. }
  253. function formatVersionDate(t: string) {
  254. const d = new Date(+t);
  255. const year = d.getUTCFullYear();
  256. const month = d.getUTCMonth() + 1;
  257. const day = d.getUTCDate();
  258. return [
  259. year.toString(),
  260. month.toString().padStart(2, "0"),
  261. day.toString().padStart(2, "0"),
  262. ].join("");
  263. }
  264. export function Settings() {
  265. const navigate = useNavigate();
  266. const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  267. const config = useAppConfig();
  268. const updateConfig = config.update;
  269. const resetConfig = config.reset;
  270. const chatStore = useChatStore();
  271. const updateStore = useUpdateStore();
  272. const [checkingUpdate, setCheckingUpdate] = useState(false);
  273. const currentVersion = formatVersionDate(updateStore.version);
  274. const remoteId = formatVersionDate(updateStore.remoteVersion);
  275. const hasNewVersion = currentVersion !== remoteId;
  276. function checkUpdate(force = false) {
  277. setCheckingUpdate(true);
  278. updateStore.getLatestVersion(force).then(() => {
  279. setCheckingUpdate(false);
  280. });
  281. console.log(
  282. "[Update] local version ",
  283. new Date(+updateStore.version).toLocaleString(),
  284. );
  285. console.log(
  286. "[Update] remote version ",
  287. new Date(+updateStore.remoteVersion).toLocaleString(),
  288. );
  289. }
  290. const usage = {
  291. used: updateStore.used,
  292. subscription: updateStore.subscription,
  293. };
  294. const [loadingUsage, setLoadingUsage] = useState(false);
  295. function checkUsage(force = false) {
  296. setLoadingUsage(true);
  297. updateStore.updateUsage(force).finally(() => {
  298. setLoadingUsage(false);
  299. });
  300. }
  301. const accessStore = useAccessStore();
  302. const enabledAccessControl = useMemo(
  303. () => accessStore.enabledAccessControl(),
  304. // eslint-disable-next-line react-hooks/exhaustive-deps
  305. [],
  306. );
  307. const promptStore = usePromptStore();
  308. const builtinCount = SearchService.count.builtin;
  309. const customCount = promptStore.getUserPrompts().length ?? 0;
  310. const [shouldShowPromptModal, setShowPromptModal] = useState(false);
  311. const showUsage = accessStore.isAuthorized();
  312. useEffect(() => {
  313. // checks per minutes
  314. checkUpdate();
  315. showUsage && checkUsage();
  316. // eslint-disable-next-line react-hooks/exhaustive-deps
  317. }, []);
  318. useEffect(() => {
  319. const keydownEvent = (e: KeyboardEvent) => {
  320. if (e.key === "Escape") {
  321. navigate(Path.Home);
  322. }
  323. };
  324. document.addEventListener("keydown", keydownEvent);
  325. return () => {
  326. document.removeEventListener("keydown", keydownEvent);
  327. };
  328. // eslint-disable-next-line react-hooks/exhaustive-deps
  329. }, []);
  330. const clientConfig = useMemo(() => getClientConfig(), []);
  331. const showAccessCode = enabledAccessControl && !clientConfig?.isApp;
  332. return (
  333. <ErrorBoundary>
  334. <div className="window-header" data-tauri-drag-region>
  335. <div className="window-header-title">
  336. <div className="window-header-main-title">
  337. {Locale.Settings.Title}
  338. </div>
  339. <div className="window-header-sub-title">
  340. {Locale.Settings.SubTitle}
  341. </div>
  342. </div>
  343. <div className="window-actions">
  344. <div className="window-action-button">
  345. <IconButton
  346. icon={<ClearIcon />}
  347. onClick={() => {
  348. if (confirm(Locale.Settings.Actions.ConfirmClearAll)) {
  349. chatStore.clearAllData();
  350. }
  351. }}
  352. bordered
  353. title={Locale.Settings.Actions.ClearAll}
  354. />
  355. </div>
  356. <div className="window-action-button">
  357. <IconButton
  358. icon={<ResetIcon />}
  359. onClick={() => {
  360. if (confirm(Locale.Settings.Actions.ConfirmResetAll)) {
  361. resetConfig();
  362. }
  363. }}
  364. bordered
  365. title={Locale.Settings.Actions.ResetAll}
  366. />
  367. </div>
  368. <div className="window-action-button">
  369. <IconButton
  370. icon={<CloseIcon />}
  371. onClick={() => navigate(Path.Home)}
  372. bordered
  373. title={Locale.Settings.Actions.Close}
  374. />
  375. </div>
  376. </div>
  377. </div>
  378. <div className={styles["settings"]}>
  379. <List>
  380. <ListItem title={Locale.Settings.Avatar}>
  381. <Popover
  382. onClose={() => setShowEmojiPicker(false)}
  383. content={
  384. <AvatarPicker
  385. onEmojiClick={(avatar: string) => {
  386. updateConfig((config) => (config.avatar = avatar));
  387. setShowEmojiPicker(false);
  388. }}
  389. />
  390. }
  391. open={showEmojiPicker}
  392. >
  393. <div
  394. className={styles.avatar}
  395. onClick={() => setShowEmojiPicker(true)}
  396. >
  397. <Avatar avatar={config.avatar} />
  398. </div>
  399. </Popover>
  400. </ListItem>
  401. <ListItem
  402. title={Locale.Settings.Update.Version(currentVersion ?? "unknown")}
  403. subTitle={
  404. checkingUpdate
  405. ? Locale.Settings.Update.IsChecking
  406. : hasNewVersion
  407. ? Locale.Settings.Update.FoundUpdate(remoteId ?? "ERROR")
  408. : Locale.Settings.Update.IsLatest
  409. }
  410. >
  411. {checkingUpdate ? (
  412. <LoadingIcon />
  413. ) : hasNewVersion ? (
  414. <Link href={UPDATE_URL} target="_blank" className="link">
  415. {Locale.Settings.Update.GoToUpdate}
  416. </Link>
  417. ) : (
  418. <IconButton
  419. icon={<ResetIcon></ResetIcon>}
  420. text={Locale.Settings.Update.CheckUpdate}
  421. onClick={() => checkUpdate(true)}
  422. />
  423. )}
  424. </ListItem>
  425. <ListItem title={Locale.Settings.SendKey}>
  426. <Select
  427. value={config.submitKey}
  428. onChange={(e) => {
  429. updateConfig(
  430. (config) =>
  431. (config.submitKey = e.target.value as any as SubmitKey),
  432. );
  433. }}
  434. >
  435. {Object.values(SubmitKey).map((v) => (
  436. <option value={v} key={v}>
  437. {v}
  438. </option>
  439. ))}
  440. </Select>
  441. </ListItem>
  442. <ListItem title={Locale.Settings.Theme}>
  443. <Select
  444. value={config.theme}
  445. onChange={(e) => {
  446. updateConfig(
  447. (config) => (config.theme = e.target.value as any as Theme),
  448. );
  449. }}
  450. >
  451. {Object.values(Theme).map((v) => (
  452. <option value={v} key={v}>
  453. {v}
  454. </option>
  455. ))}
  456. </Select>
  457. </ListItem>
  458. <ListItem title={Locale.Settings.Lang.Name}>
  459. <Select
  460. value={getLang()}
  461. onChange={(e) => {
  462. changeLang(e.target.value as any);
  463. }}
  464. >
  465. {AllLangs.map((lang) => (
  466. <option value={lang} key={lang}>
  467. {ALL_LANG_OPTIONS[lang]}
  468. </option>
  469. ))}
  470. </Select>
  471. </ListItem>
  472. <ListItem
  473. title={Locale.Settings.FontSize.Title}
  474. subTitle={Locale.Settings.FontSize.SubTitle}
  475. >
  476. <InputRange
  477. title={`${config.fontSize ?? 14}px`}
  478. value={config.fontSize}
  479. min="12"
  480. max="18"
  481. step="1"
  482. onChange={(e) =>
  483. updateConfig(
  484. (config) =>
  485. (config.fontSize = Number.parseInt(e.currentTarget.value)),
  486. )
  487. }
  488. ></InputRange>
  489. </ListItem>
  490. <ListItem
  491. title={Locale.Settings.SendPreviewBubble.Title}
  492. subTitle={Locale.Settings.SendPreviewBubble.SubTitle}
  493. >
  494. <input
  495. type="checkbox"
  496. checked={config.sendPreviewBubble}
  497. onChange={(e) =>
  498. updateConfig(
  499. (config) =>
  500. (config.sendPreviewBubble = e.currentTarget.checked),
  501. )
  502. }
  503. ></input>
  504. </ListItem>
  505. <ListItem
  506. title={Locale.Settings.Mask.Title}
  507. subTitle={Locale.Settings.Mask.SubTitle}
  508. >
  509. <input
  510. type="checkbox"
  511. checked={!config.dontShowMaskSplashScreen}
  512. onChange={(e) =>
  513. updateConfig(
  514. (config) =>
  515. (config.dontShowMaskSplashScreen =
  516. !e.currentTarget.checked),
  517. )
  518. }
  519. ></input>
  520. </ListItem>
  521. </List>
  522. <List>
  523. {showAccessCode ? (
  524. <ListItem
  525. title={Locale.Settings.AccessCode.Title}
  526. subTitle={Locale.Settings.AccessCode.SubTitle}
  527. >
  528. <PasswordInput
  529. value={accessStore.accessCode}
  530. type="text"
  531. placeholder={Locale.Settings.AccessCode.Placeholder}
  532. onChange={(e) => {
  533. accessStore.updateCode(e.currentTarget.value);
  534. }}
  535. />
  536. </ListItem>
  537. ) : (
  538. <></>
  539. )}
  540. {!accessStore.hideUserApiKey ? (
  541. <ListItem
  542. title={Locale.Settings.Token.Title}
  543. subTitle={Locale.Settings.Token.SubTitle}
  544. >
  545. <PasswordInput
  546. value={accessStore.token}
  547. type="text"
  548. placeholder={Locale.Settings.Token.Placeholder}
  549. onChange={(e) => {
  550. accessStore.updateToken(e.currentTarget.value);
  551. }}
  552. />
  553. </ListItem>
  554. ) : null}
  555. {!accessStore.hideBalanceQuery ? (
  556. <ListItem
  557. title={Locale.Settings.Usage.Title}
  558. subTitle={
  559. showUsage
  560. ? loadingUsage
  561. ? Locale.Settings.Usage.IsChecking
  562. : Locale.Settings.Usage.SubTitle(
  563. usage?.used ?? "[?]",
  564. usage?.subscription ?? "[?]",
  565. )
  566. : Locale.Settings.Usage.NoAccess
  567. }
  568. >
  569. {!showUsage || loadingUsage ? (
  570. <div />
  571. ) : (
  572. <IconButton
  573. icon={<ResetIcon></ResetIcon>}
  574. text={Locale.Settings.Usage.Check}
  575. onClick={() => checkUsage(true)}
  576. />
  577. )}
  578. </ListItem>
  579. ) : null}
  580. {!accessStore.hideUserApiKey ? (
  581. <ListItem
  582. title={Locale.Settings.Endpoint.Title}
  583. subTitle={Locale.Settings.Endpoint.SubTitle}
  584. >
  585. <input
  586. type="text"
  587. value={accessStore.openaiUrl}
  588. placeholder="https://api.openai.com/"
  589. onChange={(e) =>
  590. accessStore.updateOpenAiUrl(e.currentTarget.value)
  591. }
  592. ></input>
  593. </ListItem>
  594. ) : null}
  595. </List>
  596. <List>
  597. <ListItem
  598. title={Locale.Settings.Prompt.Disable.Title}
  599. subTitle={Locale.Settings.Prompt.Disable.SubTitle}
  600. >
  601. <input
  602. type="checkbox"
  603. checked={config.disablePromptHint}
  604. onChange={(e) =>
  605. updateConfig(
  606. (config) =>
  607. (config.disablePromptHint = e.currentTarget.checked),
  608. )
  609. }
  610. ></input>
  611. </ListItem>
  612. <ListItem
  613. title={Locale.Settings.Prompt.List}
  614. subTitle={Locale.Settings.Prompt.ListCount(
  615. builtinCount,
  616. customCount,
  617. )}
  618. >
  619. <IconButton
  620. icon={<EditIcon />}
  621. text={Locale.Settings.Prompt.Edit}
  622. onClick={() => setShowPromptModal(true)}
  623. />
  624. </ListItem>
  625. </List>
  626. <SyncItems />
  627. <List>
  628. <ModelConfigList
  629. modelConfig={config.modelConfig}
  630. updateConfig={(updater) => {
  631. const modelConfig = { ...config.modelConfig };
  632. updater(modelConfig);
  633. config.update((config) => (config.modelConfig = modelConfig));
  634. }}
  635. />
  636. </List>
  637. {shouldShowPromptModal && (
  638. <UserPromptModal onClose={() => setShowPromptModal(false)} />
  639. )}
  640. </div>
  641. </ErrorBoundary>
  642. );
  643. }