settings.tsx 22 KB

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