settings.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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 SyncItems() {
  190. const syncStore = useSyncStore();
  191. const webdav = syncStore.webDavConfig;
  192. // not ready: https://github.com/Yidadaa/ChatGPT-Next-Web/issues/920#issuecomment-1609866332
  193. return null;
  194. return (
  195. <List>
  196. <ListItem
  197. title={"上次同步:" + new Date().toLocaleString()}
  198. subTitle={"20 次对话,100 条消息,200 提示词,20 面具"}
  199. >
  200. <IconButton
  201. icon={<ResetIcon />}
  202. text="同步"
  203. onClick={() => {
  204. syncStore.check().then(console.log);
  205. }}
  206. />
  207. </ListItem>
  208. <ListItem
  209. title={"本地备份"}
  210. subTitle={"20 次对话,100 条消息,200 提示词,20 面具"}
  211. ></ListItem>
  212. <ListItem
  213. title={"Web Dav Server"}
  214. subTitle={Locale.Settings.AccessCode.SubTitle}
  215. >
  216. <input
  217. value={webdav.server}
  218. type="text"
  219. placeholder={"https://example.com"}
  220. onChange={(e) => {
  221. syncStore.update(
  222. (config) => (config.server = e.currentTarget.value),
  223. );
  224. }}
  225. />
  226. </ListItem>
  227. <ListItem title="Web Dav User Name" subTitle="user name here">
  228. <input
  229. value={webdav.username}
  230. type="text"
  231. placeholder={"username"}
  232. onChange={(e) => {
  233. syncStore.update(
  234. (config) => (config.username = e.currentTarget.value),
  235. );
  236. }}
  237. />
  238. </ListItem>
  239. <ListItem title="Web Dav Password" subTitle="password here">
  240. <input
  241. value={webdav.password}
  242. type="text"
  243. placeholder={"password"}
  244. onChange={(e) => {
  245. syncStore.update(
  246. (config) => (config.password = e.currentTarget.value),
  247. );
  248. }}
  249. />
  250. </ListItem>
  251. </List>
  252. );
  253. }
  254. function formatVersionDate(t: string) {
  255. const d = new Date(+t);
  256. const year = d.getUTCFullYear();
  257. const month = d.getUTCMonth() + 1;
  258. const day = d.getUTCDate();
  259. return [
  260. year.toString(),
  261. month.toString().padStart(2, "0"),
  262. day.toString().padStart(2, "0"),
  263. ].join("");
  264. }
  265. export function Settings() {
  266. const navigate = useNavigate();
  267. const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  268. const config = useAppConfig();
  269. const updateConfig = config.update;
  270. const resetConfig = config.reset;
  271. const chatStore = useChatStore();
  272. const updateStore = useUpdateStore();
  273. const [checkingUpdate, setCheckingUpdate] = useState(false);
  274. const currentVersion = formatVersionDate(updateStore.version);
  275. const remoteId = formatVersionDate(updateStore.remoteVersion);
  276. const hasNewVersion = currentVersion !== remoteId;
  277. function checkUpdate(force = false) {
  278. setCheckingUpdate(true);
  279. updateStore.getLatestVersion(force).then(() => {
  280. setCheckingUpdate(false);
  281. });
  282. console.log(
  283. "[Update] local version ",
  284. new Date(+updateStore.version).toLocaleString(),
  285. );
  286. console.log(
  287. "[Update] remote version ",
  288. new Date(+updateStore.remoteVersion).toLocaleString(),
  289. );
  290. }
  291. const usage = {
  292. used: updateStore.used,
  293. subscription: updateStore.subscription,
  294. };
  295. const [loadingUsage, setLoadingUsage] = useState(false);
  296. function checkUsage(force = false) {
  297. setLoadingUsage(true);
  298. updateStore.updateUsage(force).finally(() => {
  299. setLoadingUsage(false);
  300. });
  301. }
  302. const accessStore = useAccessStore();
  303. const enabledAccessControl = useMemo(
  304. () => accessStore.enabledAccessControl(),
  305. // eslint-disable-next-line react-hooks/exhaustive-deps
  306. [],
  307. );
  308. const promptStore = usePromptStore();
  309. const builtinCount = SearchService.count.builtin;
  310. const customCount = promptStore.getUserPrompts().length ?? 0;
  311. const [shouldShowPromptModal, setShowPromptModal] = useState(false);
  312. const showUsage = accessStore.isAuthorized();
  313. useEffect(() => {
  314. // checks per minutes
  315. checkUpdate();
  316. showUsage && checkUsage();
  317. // eslint-disable-next-line react-hooks/exhaustive-deps
  318. }, []);
  319. useEffect(() => {
  320. const keydownEvent = (e: KeyboardEvent) => {
  321. if (e.key === "Escape") {
  322. navigate(Path.Home);
  323. }
  324. };
  325. document.addEventListener("keydown", keydownEvent);
  326. return () => {
  327. document.removeEventListener("keydown", keydownEvent);
  328. };
  329. // eslint-disable-next-line react-hooks/exhaustive-deps
  330. }, []);
  331. const clientConfig = useMemo(() => getClientConfig(), []);
  332. const showAccessCode = enabledAccessControl && !clientConfig?.isApp;
  333. return (
  334. <ErrorBoundary>
  335. <div className="window-header" data-tauri-drag-region>
  336. <div className="window-header-title">
  337. <div className="window-header-main-title">
  338. {Locale.Settings.Title}
  339. </div>
  340. <div className="window-header-sub-title">
  341. {Locale.Settings.SubTitle}
  342. </div>
  343. </div>
  344. <div className="window-actions">
  345. <div className="window-action-button">
  346. <IconButton
  347. icon={<ClearIcon />}
  348. onClick={async () => {
  349. if (
  350. await showConfirm(Locale.Settings.Actions.ConfirmClearAll)
  351. ) {
  352. chatStore.clearAllData();
  353. }
  354. }}
  355. bordered
  356. title={Locale.Settings.Actions.ClearAll}
  357. />
  358. </div>
  359. <div className="window-action-button">
  360. <IconButton
  361. icon={<ResetIcon />}
  362. onClick={async () => {
  363. if (
  364. await showConfirm(Locale.Settings.Actions.ConfirmResetAll)
  365. ) {
  366. resetConfig();
  367. }
  368. }}
  369. bordered
  370. title={Locale.Settings.Actions.ResetAll}
  371. />
  372. </div>
  373. <div className="window-action-button">
  374. <IconButton
  375. icon={<CloseIcon />}
  376. onClick={() => navigate(Path.Home)}
  377. bordered
  378. title={Locale.Settings.Actions.Close}
  379. />
  380. </div>
  381. </div>
  382. </div>
  383. <div className={styles["settings"]}>
  384. <List>
  385. <ListItem title={Locale.Settings.Avatar}>
  386. <Popover
  387. onClose={() => setShowEmojiPicker(false)}
  388. content={
  389. <AvatarPicker
  390. onEmojiClick={(avatar: string) => {
  391. updateConfig((config) => (config.avatar = avatar));
  392. setShowEmojiPicker(false);
  393. }}
  394. />
  395. }
  396. open={showEmojiPicker}
  397. >
  398. <div
  399. className={styles.avatar}
  400. onClick={() => setShowEmojiPicker(true)}
  401. >
  402. <Avatar avatar={config.avatar} />
  403. </div>
  404. </Popover>
  405. </ListItem>
  406. <ListItem
  407. title={Locale.Settings.Update.Version(currentVersion ?? "unknown")}
  408. subTitle={
  409. checkingUpdate
  410. ? Locale.Settings.Update.IsChecking
  411. : hasNewVersion
  412. ? Locale.Settings.Update.FoundUpdate(remoteId ?? "ERROR")
  413. : Locale.Settings.Update.IsLatest
  414. }
  415. >
  416. {checkingUpdate ? (
  417. <LoadingIcon />
  418. ) : hasNewVersion ? (
  419. <Link href={UPDATE_URL} target="_blank" className="link">
  420. {Locale.Settings.Update.GoToUpdate}
  421. </Link>
  422. ) : (
  423. <IconButton
  424. icon={<ResetIcon></ResetIcon>}
  425. text={Locale.Settings.Update.CheckUpdate}
  426. onClick={() => checkUpdate(true)}
  427. />
  428. )}
  429. </ListItem>
  430. <ListItem title={Locale.Settings.SendKey}>
  431. <Select
  432. value={config.submitKey}
  433. onChange={(e) => {
  434. updateConfig(
  435. (config) =>
  436. (config.submitKey = e.target.value as any as SubmitKey),
  437. );
  438. }}
  439. >
  440. {Object.values(SubmitKey).map((v) => (
  441. <option value={v} key={v}>
  442. {v}
  443. </option>
  444. ))}
  445. </Select>
  446. </ListItem>
  447. <ListItem title={Locale.Settings.Theme}>
  448. <Select
  449. value={config.theme}
  450. onChange={(e) => {
  451. updateConfig(
  452. (config) => (config.theme = e.target.value as any as Theme),
  453. );
  454. }}
  455. >
  456. {Object.values(Theme).map((v) => (
  457. <option value={v} key={v}>
  458. {v}
  459. </option>
  460. ))}
  461. </Select>
  462. </ListItem>
  463. <ListItem title={Locale.Settings.Lang.Name}>
  464. <Select
  465. value={getLang()}
  466. onChange={(e) => {
  467. changeLang(e.target.value as any);
  468. }}
  469. >
  470. {AllLangs.map((lang) => (
  471. <option value={lang} key={lang}>
  472. {ALL_LANG_OPTIONS[lang]}
  473. </option>
  474. ))}
  475. </Select>
  476. </ListItem>
  477. <ListItem
  478. title={Locale.Settings.FontSize.Title}
  479. subTitle={Locale.Settings.FontSize.SubTitle}
  480. >
  481. <InputRange
  482. title={`${config.fontSize ?? 14}px`}
  483. value={config.fontSize}
  484. min="12"
  485. max="18"
  486. step="1"
  487. onChange={(e) =>
  488. updateConfig(
  489. (config) =>
  490. (config.fontSize = Number.parseInt(e.currentTarget.value)),
  491. )
  492. }
  493. ></InputRange>
  494. </ListItem>
  495. <ListItem
  496. title={Locale.Settings.SendPreviewBubble.Title}
  497. subTitle={Locale.Settings.SendPreviewBubble.SubTitle}
  498. >
  499. <input
  500. type="checkbox"
  501. checked={config.sendPreviewBubble}
  502. onChange={(e) =>
  503. updateConfig(
  504. (config) =>
  505. (config.sendPreviewBubble = e.currentTarget.checked),
  506. )
  507. }
  508. ></input>
  509. </ListItem>
  510. <ListItem
  511. title={Locale.Settings.Mask.Title}
  512. subTitle={Locale.Settings.Mask.SubTitle}
  513. >
  514. <input
  515. type="checkbox"
  516. checked={!config.dontShowMaskSplashScreen}
  517. onChange={(e) =>
  518. updateConfig(
  519. (config) =>
  520. (config.dontShowMaskSplashScreen =
  521. !e.currentTarget.checked),
  522. )
  523. }
  524. ></input>
  525. </ListItem>
  526. </List>
  527. <List>
  528. {showAccessCode ? (
  529. <ListItem
  530. title={Locale.Settings.AccessCode.Title}
  531. subTitle={Locale.Settings.AccessCode.SubTitle}
  532. >
  533. <PasswordInput
  534. value={accessStore.accessCode}
  535. type="text"
  536. placeholder={Locale.Settings.AccessCode.Placeholder}
  537. onChange={(e) => {
  538. accessStore.updateCode(e.currentTarget.value);
  539. }}
  540. />
  541. </ListItem>
  542. ) : (
  543. <></>
  544. )}
  545. {!accessStore.hideUserApiKey ? (
  546. <ListItem
  547. title={Locale.Settings.Token.Title}
  548. subTitle={Locale.Settings.Token.SubTitle}
  549. >
  550. <PasswordInput
  551. value={accessStore.token}
  552. type="text"
  553. placeholder={Locale.Settings.Token.Placeholder}
  554. onChange={(e) => {
  555. accessStore.updateToken(e.currentTarget.value);
  556. }}
  557. />
  558. </ListItem>
  559. ) : null}
  560. {!accessStore.hideBalanceQuery ? (
  561. <ListItem
  562. title={Locale.Settings.Usage.Title}
  563. subTitle={
  564. showUsage
  565. ? loadingUsage
  566. ? Locale.Settings.Usage.IsChecking
  567. : Locale.Settings.Usage.SubTitle(
  568. usage?.used ?? "[?]",
  569. usage?.subscription ?? "[?]",
  570. )
  571. : Locale.Settings.Usage.NoAccess
  572. }
  573. >
  574. {!showUsage || loadingUsage ? (
  575. <div />
  576. ) : (
  577. <IconButton
  578. icon={<ResetIcon></ResetIcon>}
  579. text={Locale.Settings.Usage.Check}
  580. onClick={() => checkUsage(true)}
  581. />
  582. )}
  583. </ListItem>
  584. ) : null}
  585. {!accessStore.hideUserApiKey ? (
  586. <ListItem
  587. title={Locale.Settings.Endpoint.Title}
  588. subTitle={Locale.Settings.Endpoint.SubTitle}
  589. >
  590. <input
  591. type="text"
  592. value={accessStore.openaiUrl}
  593. placeholder="https://api.openai.com/"
  594. onChange={(e) =>
  595. accessStore.updateOpenAiUrl(e.currentTarget.value)
  596. }
  597. ></input>
  598. </ListItem>
  599. ) : null}
  600. </List>
  601. <List>
  602. <ListItem
  603. title={Locale.Settings.Prompt.Disable.Title}
  604. subTitle={Locale.Settings.Prompt.Disable.SubTitle}
  605. >
  606. <input
  607. type="checkbox"
  608. checked={config.disablePromptHint}
  609. onChange={(e) =>
  610. updateConfig(
  611. (config) =>
  612. (config.disablePromptHint = e.currentTarget.checked),
  613. )
  614. }
  615. ></input>
  616. </ListItem>
  617. <ListItem
  618. title={Locale.Settings.Prompt.List}
  619. subTitle={Locale.Settings.Prompt.ListCount(
  620. builtinCount,
  621. customCount,
  622. )}
  623. >
  624. <IconButton
  625. icon={<EditIcon />}
  626. text={Locale.Settings.Prompt.Edit}
  627. onClick={() => setShowPromptModal(true)}
  628. />
  629. </ListItem>
  630. </List>
  631. <SyncItems />
  632. <List>
  633. <ModelConfigList
  634. modelConfig={config.modelConfig}
  635. updateConfig={(updater) => {
  636. const modelConfig = { ...config.modelConfig };
  637. updater(modelConfig);
  638. config.update((config) => (config.modelConfig = modelConfig));
  639. }}
  640. />
  641. </List>
  642. {shouldShowPromptModal && (
  643. <UserPromptModal onClose={() => setShowPromptModal(false)} />
  644. )}
  645. </div>
  646. </ErrorBoundary>
  647. );
  648. }