settings.tsx 18 KB

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