settings.tsx 21 KB

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