settings.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. import { useState, useEffect, useMemo, HTMLProps, useRef } 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. function EditPromptModal(props: { id: number; onClose: () => void }) {
  45. const promptStore = usePromptStore();
  46. const prompt = promptStore.get(props.id);
  47. return prompt ? (
  48. <div className="modal-mask">
  49. <Modal
  50. title={Locale.Settings.Prompt.EditModal.Title}
  51. onClose={props.onClose}
  52. actions={[
  53. <IconButton
  54. key=""
  55. onClick={props.onClose}
  56. text={Locale.UI.Confirm}
  57. bordered
  58. />,
  59. ]}
  60. >
  61. <div className={styles["edit-prompt-modal"]}>
  62. <input
  63. type="text"
  64. value={prompt.title}
  65. readOnly={!prompt.isUser}
  66. className={styles["edit-prompt-title"]}
  67. onInput={(e) =>
  68. promptStore.update(
  69. props.id,
  70. (prompt) => (prompt.title = e.currentTarget.value),
  71. )
  72. }
  73. ></input>
  74. <Input
  75. value={prompt.content}
  76. readOnly={!prompt.isUser}
  77. className={styles["edit-prompt-content"]}
  78. rows={10}
  79. onInput={(e) =>
  80. promptStore.update(
  81. props.id,
  82. (prompt) => (prompt.content = e.currentTarget.value),
  83. )
  84. }
  85. ></Input>
  86. </div>
  87. </Modal>
  88. </div>
  89. ) : null;
  90. }
  91. function UserPromptModal(props: { onClose?: () => void }) {
  92. const promptStore = usePromptStore();
  93. const userPrompts = promptStore.getUserPrompts();
  94. const builtinPrompts = SearchService.builtinPrompts;
  95. const allPrompts = userPrompts.concat(builtinPrompts);
  96. const [searchInput, setSearchInput] = useState("");
  97. const [searchPrompts, setSearchPrompts] = useState<Prompt[]>([]);
  98. const prompts = searchInput.length > 0 ? searchPrompts : allPrompts;
  99. const [editingPromptId, setEditingPromptId] = useState<number>();
  100. useEffect(() => {
  101. if (searchInput.length > 0) {
  102. const searchResult = SearchService.search(searchInput);
  103. setSearchPrompts(searchResult);
  104. } else {
  105. setSearchPrompts([]);
  106. }
  107. }, [searchInput]);
  108. return (
  109. <div className="modal-mask">
  110. <Modal
  111. title={Locale.Settings.Prompt.Modal.Title}
  112. onClose={() => props.onClose?.()}
  113. actions={[
  114. <IconButton
  115. key="add"
  116. onClick={() =>
  117. promptStore.add({
  118. title: "Empty Prompt",
  119. content: "Empty Prompt Content",
  120. })
  121. }
  122. icon={<AddIcon />}
  123. bordered
  124. text={Locale.Settings.Prompt.Modal.Add}
  125. />,
  126. ]}
  127. >
  128. <div className={styles["user-prompt-modal"]}>
  129. <input
  130. type="text"
  131. className={styles["user-prompt-search"]}
  132. placeholder={Locale.Settings.Prompt.Modal.Search}
  133. value={searchInput}
  134. onInput={(e) => setSearchInput(e.currentTarget.value)}
  135. ></input>
  136. <div className={styles["user-prompt-list"]}>
  137. {prompts.map((v, _) => (
  138. <div className={styles["user-prompt-item"]} key={v.id ?? v.title}>
  139. <div className={styles["user-prompt-header"]}>
  140. <div className={styles["user-prompt-title"]}>{v.title}</div>
  141. <div className={styles["user-prompt-content"] + " one-line"}>
  142. {v.content}
  143. </div>
  144. </div>
  145. <div className={styles["user-prompt-buttons"]}>
  146. {v.isUser && (
  147. <IconButton
  148. icon={<ClearIcon />}
  149. className={styles["user-prompt-button"]}
  150. onClick={() => promptStore.remove(v.id!)}
  151. />
  152. )}
  153. {v.isUser ? (
  154. <IconButton
  155. icon={<EditIcon />}
  156. className={styles["user-prompt-button"]}
  157. onClick={() => setEditingPromptId(v.id)}
  158. />
  159. ) : (
  160. <IconButton
  161. icon={<EyeIcon />}
  162. className={styles["user-prompt-button"]}
  163. onClick={() => setEditingPromptId(v.id)}
  164. />
  165. )}
  166. <IconButton
  167. icon={<CopyIcon />}
  168. className={styles["user-prompt-button"]}
  169. onClick={() => copyToClipboard(v.content)}
  170. />
  171. </div>
  172. </div>
  173. ))}
  174. </div>
  175. </div>
  176. </Modal>
  177. {editingPromptId !== undefined && (
  178. <EditPromptModal
  179. id={editingPromptId!}
  180. onClose={() => setEditingPromptId(undefined)}
  181. />
  182. )}
  183. </div>
  184. );
  185. }
  186. function formatVersionDate(t: string) {
  187. const d = new Date(+t);
  188. const year = d.getUTCFullYear();
  189. const month = d.getUTCMonth() + 1;
  190. const day = d.getUTCDate();
  191. return [
  192. year.toString(),
  193. month.toString().padStart(2, "0"),
  194. day.toString().padStart(2, "0"),
  195. ].join("");
  196. }
  197. export function Settings() {
  198. const navigate = useNavigate();
  199. const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  200. const config = useAppConfig();
  201. const updateConfig = config.update;
  202. const resetConfig = config.reset;
  203. const chatStore = useChatStore();
  204. const updateStore = useUpdateStore();
  205. const [checkingUpdate, setCheckingUpdate] = useState(false);
  206. const currentVersion = formatVersionDate(updateStore.version);
  207. const remoteId = formatVersionDate(updateStore.remoteVersion);
  208. const hasNewVersion = currentVersion !== remoteId;
  209. function checkUpdate(force = false) {
  210. setCheckingUpdate(true);
  211. updateStore.getLatestVersion(force).then(() => {
  212. setCheckingUpdate(false);
  213. });
  214. console.log(
  215. "[Update] local version ",
  216. new Date(+updateStore.version).toLocaleString(),
  217. );
  218. console.log(
  219. "[Update] remote version ",
  220. new Date(+updateStore.remoteVersion).toLocaleString(),
  221. );
  222. }
  223. const usage = {
  224. used: updateStore.used,
  225. subscription: updateStore.subscription,
  226. };
  227. const [loadingUsage, setLoadingUsage] = useState(false);
  228. function checkUsage(force = false) {
  229. setLoadingUsage(true);
  230. updateStore.updateUsage(force).finally(() => {
  231. setLoadingUsage(false);
  232. });
  233. }
  234. const accessStore = useAccessStore();
  235. const enabledAccessControl = useMemo(
  236. () => accessStore.enabledAccessControl(),
  237. // eslint-disable-next-line react-hooks/exhaustive-deps
  238. [],
  239. );
  240. const promptStore = usePromptStore();
  241. const builtinCount = SearchService.count.builtin;
  242. const customCount = promptStore.getUserPrompts().length ?? 0;
  243. const [shouldShowPromptModal, setShowPromptModal] = useState(false);
  244. const showUsage = accessStore.isAuthorized();
  245. useEffect(() => {
  246. // checks per minutes
  247. checkUpdate();
  248. showUsage && checkUsage();
  249. // eslint-disable-next-line react-hooks/exhaustive-deps
  250. }, []);
  251. useEffect(() => {
  252. const keydownEvent = (e: KeyboardEvent) => {
  253. if (e.key === "Escape") {
  254. navigate(Path.Home);
  255. }
  256. };
  257. document.addEventListener("keydown", keydownEvent);
  258. return () => {
  259. document.removeEventListener("keydown", keydownEvent);
  260. };
  261. // eslint-disable-next-line react-hooks/exhaustive-deps
  262. }, []);
  263. return (
  264. <ErrorBoundary>
  265. <div className="window-header">
  266. <div className="window-header-title">
  267. <div className="window-header-main-title">
  268. {Locale.Settings.Title}
  269. </div>
  270. <div className="window-header-sub-title">
  271. {Locale.Settings.SubTitle}
  272. </div>
  273. </div>
  274. <div className="window-actions">
  275. <div className="window-action-button">
  276. <IconButton
  277. icon={<ClearIcon />}
  278. onClick={() => {
  279. if (confirm(Locale.Settings.Actions.ConfirmClearAll)) {
  280. chatStore.clearAllData();
  281. }
  282. }}
  283. bordered
  284. title={Locale.Settings.Actions.ClearAll}
  285. />
  286. </div>
  287. <div className="window-action-button">
  288. <IconButton
  289. icon={<ResetIcon />}
  290. onClick={() => {
  291. if (confirm(Locale.Settings.Actions.ConfirmResetAll)) {
  292. resetConfig();
  293. }
  294. }}
  295. bordered
  296. title={Locale.Settings.Actions.ResetAll}
  297. />
  298. </div>
  299. <div className="window-action-button">
  300. <IconButton
  301. icon={<CloseIcon />}
  302. onClick={() => navigate(Path.Home)}
  303. bordered
  304. title={Locale.Settings.Actions.Close}
  305. />
  306. </div>
  307. </div>
  308. </div>
  309. <div className={styles["settings"]}>
  310. <List>
  311. <ListItem title={Locale.Settings.Avatar}>
  312. <Popover
  313. onClose={() => setShowEmojiPicker(false)}
  314. content={
  315. <AvatarPicker
  316. onEmojiClick={(avatar: string) => {
  317. updateConfig((config) => (config.avatar = avatar));
  318. setShowEmojiPicker(false);
  319. }}
  320. />
  321. }
  322. open={showEmojiPicker}
  323. >
  324. <div
  325. className={styles.avatar}
  326. onClick={() => setShowEmojiPicker(true)}
  327. >
  328. <Avatar avatar={config.avatar} />
  329. </div>
  330. </Popover>
  331. </ListItem>
  332. <ListItem
  333. title={Locale.Settings.Update.Version(currentVersion ?? "unknown")}
  334. subTitle={
  335. checkingUpdate
  336. ? Locale.Settings.Update.IsChecking
  337. : hasNewVersion
  338. ? Locale.Settings.Update.FoundUpdate(remoteId ?? "ERROR")
  339. : Locale.Settings.Update.IsLatest
  340. }
  341. >
  342. {checkingUpdate ? (
  343. <LoadingIcon />
  344. ) : hasNewVersion ? (
  345. <Link href={UPDATE_URL} target="_blank" className="link">
  346. {Locale.Settings.Update.GoToUpdate}
  347. </Link>
  348. ) : (
  349. <IconButton
  350. icon={<ResetIcon></ResetIcon>}
  351. text={Locale.Settings.Update.CheckUpdate}
  352. onClick={() => checkUpdate(true)}
  353. />
  354. )}
  355. </ListItem>
  356. <ListItem title={Locale.Settings.SendKey}>
  357. <Select
  358. value={config.submitKey}
  359. onChange={(e) => {
  360. updateConfig(
  361. (config) =>
  362. (config.submitKey = e.target.value as any as SubmitKey),
  363. );
  364. }}
  365. >
  366. {Object.values(SubmitKey).map((v) => (
  367. <option value={v} key={v}>
  368. {v}
  369. </option>
  370. ))}
  371. </Select>
  372. </ListItem>
  373. <ListItem title={Locale.Settings.Theme}>
  374. <Select
  375. value={config.theme}
  376. onChange={(e) => {
  377. updateConfig(
  378. (config) => (config.theme = e.target.value as any as Theme),
  379. );
  380. }}
  381. >
  382. {Object.values(Theme).map((v) => (
  383. <option value={v} key={v}>
  384. {v}
  385. </option>
  386. ))}
  387. </Select>
  388. </ListItem>
  389. <ListItem title={Locale.Settings.Lang.Name}>
  390. <Select
  391. value={getLang()}
  392. onChange={(e) => {
  393. changeLang(e.target.value as any);
  394. }}
  395. >
  396. {AllLangs.map((lang) => (
  397. <option value={lang} key={lang}>
  398. {ALL_LANG_OPTIONS[lang]}
  399. </option>
  400. ))}
  401. </Select>
  402. </ListItem>
  403. <ListItem
  404. title={Locale.Settings.FontSize.Title}
  405. subTitle={Locale.Settings.FontSize.SubTitle}
  406. >
  407. <InputRange
  408. title={`${config.fontSize ?? 14}px`}
  409. value={config.fontSize}
  410. min="12"
  411. max="18"
  412. step="1"
  413. onChange={(e) =>
  414. updateConfig(
  415. (config) =>
  416. (config.fontSize = Number.parseInt(e.currentTarget.value)),
  417. )
  418. }
  419. ></InputRange>
  420. </ListItem>
  421. <ListItem
  422. title={Locale.Settings.SendPreviewBubble.Title}
  423. subTitle={Locale.Settings.SendPreviewBubble.SubTitle}
  424. >
  425. <input
  426. type="checkbox"
  427. checked={config.sendPreviewBubble}
  428. onChange={(e) =>
  429. updateConfig(
  430. (config) =>
  431. (config.sendPreviewBubble = e.currentTarget.checked),
  432. )
  433. }
  434. ></input>
  435. </ListItem>
  436. <ListItem
  437. title={Locale.Settings.Mask.Title}
  438. subTitle={Locale.Settings.Mask.SubTitle}
  439. >
  440. <input
  441. type="checkbox"
  442. checked={!config.dontShowMaskSplashScreen}
  443. onChange={(e) =>
  444. updateConfig(
  445. (config) =>
  446. (config.dontShowMaskSplashScreen =
  447. !e.currentTarget.checked),
  448. )
  449. }
  450. ></input>
  451. </ListItem>
  452. </List>
  453. <List>
  454. {enabledAccessControl ? (
  455. <ListItem
  456. title={Locale.Settings.AccessCode.Title}
  457. subTitle={Locale.Settings.AccessCode.SubTitle}
  458. >
  459. <PasswordInput
  460. value={accessStore.accessCode}
  461. type="text"
  462. placeholder={Locale.Settings.AccessCode.Placeholder}
  463. onChange={(e) => {
  464. accessStore.updateCode(e.currentTarget.value);
  465. }}
  466. />
  467. </ListItem>
  468. ) : (
  469. <></>
  470. )}
  471. {!accessStore.hideUserApiKey ? (
  472. <ListItem
  473. title={Locale.Settings.Token.Title}
  474. subTitle={Locale.Settings.Token.SubTitle}
  475. >
  476. <PasswordInput
  477. value={accessStore.token}
  478. type="text"
  479. placeholder={Locale.Settings.Token.Placeholder}
  480. onChange={(e) => {
  481. accessStore.updateToken(e.currentTarget.value);
  482. }}
  483. />
  484. </ListItem>
  485. ) : null}
  486. <ListItem
  487. title={Locale.Settings.Usage.Title}
  488. subTitle={
  489. showUsage
  490. ? loadingUsage
  491. ? Locale.Settings.Usage.IsChecking
  492. : Locale.Settings.Usage.SubTitle(
  493. usage?.used ?? "[?]",
  494. usage?.subscription ?? "[?]",
  495. )
  496. : Locale.Settings.Usage.NoAccess
  497. }
  498. >
  499. {!showUsage || loadingUsage ? (
  500. <div />
  501. ) : (
  502. <IconButton
  503. icon={<ResetIcon></ResetIcon>}
  504. text={Locale.Settings.Usage.Check}
  505. onClick={() => checkUsage(true)}
  506. />
  507. )}
  508. </ListItem>
  509. </List>
  510. <List>
  511. <ListItem
  512. title={Locale.Settings.Prompt.Disable.Title}
  513. subTitle={Locale.Settings.Prompt.Disable.SubTitle}
  514. >
  515. <input
  516. type="checkbox"
  517. checked={config.disablePromptHint}
  518. onChange={(e) =>
  519. updateConfig(
  520. (config) =>
  521. (config.disablePromptHint = e.currentTarget.checked),
  522. )
  523. }
  524. ></input>
  525. </ListItem>
  526. <ListItem
  527. title={Locale.Settings.Prompt.List}
  528. subTitle={Locale.Settings.Prompt.ListCount(
  529. builtinCount,
  530. customCount,
  531. )}
  532. >
  533. <IconButton
  534. icon={<EditIcon />}
  535. text={Locale.Settings.Prompt.Edit}
  536. onClick={() => setShowPromptModal(true)}
  537. />
  538. </ListItem>
  539. </List>
  540. <List>
  541. <ModelConfigList
  542. modelConfig={config.modelConfig}
  543. updateConfig={(updater) => {
  544. const modelConfig = { ...config.modelConfig };
  545. updater(modelConfig);
  546. config.update((config) => (config.modelConfig = modelConfig));
  547. }}
  548. />
  549. </List>
  550. {shouldShowPromptModal && (
  551. <UserPromptModal onClose={() => setShowPromptModal(false)} />
  552. )}
  553. </div>
  554. </ErrorBoundary>
  555. );
  556. }