settings.tsx 18 KB

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