mask.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. import { IconButton } from "./button";
  2. import { ErrorBoundary } from "./error";
  3. import styles from "./mask.module.scss";
  4. import DownloadIcon from "../icons/download.svg";
  5. import UploadIcon from "../icons/upload.svg";
  6. import EditIcon from "../icons/edit.svg";
  7. import AddIcon from "../icons/add.svg";
  8. import CloseIcon from "../icons/close.svg";
  9. import DeleteIcon from "../icons/delete.svg";
  10. import EyeIcon from "../icons/eye.svg";
  11. import CopyIcon from "../icons/copy.svg";
  12. import { DEFAULT_MASK_AVATAR, Mask, useMaskStore } from "../store/mask";
  13. import { ChatMessage, ModelConfig, useAppConfig, useChatStore } from "../store";
  14. import { ROLES } from "../client/api";
  15. import { Input, List, ListItem, Modal, Popover, Select } from "./ui-lib";
  16. import { Avatar, AvatarPicker } from "./emoji";
  17. import Locale, { AllLangs, ALL_LANG_OPTIONS, Lang } from "../locales";
  18. import { useNavigate } from "react-router-dom";
  19. import chatStyle from "./chat.module.scss";
  20. import { useEffect, useState } from "react";
  21. import { downloadAs, readFromFile } from "../utils";
  22. import { Updater } from "../typing";
  23. import { ModelConfigList } from "./model-config";
  24. import { FileName, Path } from "../constant";
  25. import { BUILTIN_MASK_STORE } from "../masks";
  26. export function MaskAvatar(props: { mask: Mask }) {
  27. return props.mask.avatar !== DEFAULT_MASK_AVATAR ? (
  28. <Avatar avatar={props.mask.avatar} />
  29. ) : (
  30. <Avatar model={props.mask.modelConfig.model} />
  31. );
  32. }
  33. export function MaskConfig(props: {
  34. mask: Mask;
  35. updateMask: Updater<Mask>;
  36. extraListItems?: JSX.Element;
  37. readonly?: boolean;
  38. shouldSyncFromGlobal?: boolean;
  39. }) {
  40. const [showPicker, setShowPicker] = useState(false);
  41. const updateConfig = (updater: (config: ModelConfig) => void) => {
  42. if (props.readonly) return;
  43. const config = { ...props.mask.modelConfig };
  44. updater(config);
  45. props.updateMask((mask) => {
  46. mask.modelConfig = config;
  47. // if user changed current session mask, it will disable auto sync
  48. mask.syncGlobalConfig = false;
  49. });
  50. };
  51. const globalConfig = useAppConfig();
  52. return (
  53. <>
  54. <ContextPrompts
  55. context={props.mask.context}
  56. updateContext={(updater) => {
  57. const context = props.mask.context.slice();
  58. updater(context);
  59. props.updateMask((mask) => (mask.context = context));
  60. }}
  61. />
  62. <List>
  63. <ListItem title={Locale.Mask.Config.Avatar}>
  64. <Popover
  65. content={
  66. <AvatarPicker
  67. onEmojiClick={(emoji) => {
  68. props.updateMask((mask) => (mask.avatar = emoji));
  69. setShowPicker(false);
  70. }}
  71. ></AvatarPicker>
  72. }
  73. open={showPicker}
  74. onClose={() => setShowPicker(false)}
  75. >
  76. <div
  77. onClick={() => setShowPicker(true)}
  78. style={{ cursor: "pointer" }}
  79. >
  80. <MaskAvatar mask={props.mask} />
  81. </div>
  82. </Popover>
  83. </ListItem>
  84. <ListItem title={Locale.Mask.Config.Name}>
  85. <input
  86. type="text"
  87. value={props.mask.name}
  88. onInput={(e) =>
  89. props.updateMask((mask) => {
  90. mask.name = e.currentTarget.value;
  91. })
  92. }
  93. ></input>
  94. </ListItem>
  95. <ListItem
  96. title={Locale.Mask.Config.HideContext.Title}
  97. subTitle={Locale.Mask.Config.HideContext.SubTitle}
  98. >
  99. <input
  100. type="checkbox"
  101. checked={props.mask.hideContext}
  102. onChange={(e) => {
  103. props.updateMask((mask) => {
  104. mask.hideContext = e.currentTarget.checked;
  105. });
  106. }}
  107. ></input>
  108. </ListItem>
  109. {props.shouldSyncFromGlobal ? (
  110. <ListItem
  111. title={Locale.Mask.Config.Sync.Title}
  112. subTitle={Locale.Mask.Config.Sync.SubTitle}
  113. >
  114. <input
  115. type="checkbox"
  116. checked={props.mask.syncGlobalConfig}
  117. onChange={(e) => {
  118. if (
  119. e.currentTarget.checked &&
  120. confirm(Locale.Mask.Config.Sync.Confirm)
  121. ) {
  122. props.updateMask((mask) => {
  123. mask.syncGlobalConfig = e.currentTarget.checked;
  124. mask.modelConfig = { ...globalConfig.modelConfig };
  125. });
  126. }
  127. }}
  128. ></input>
  129. </ListItem>
  130. ) : null}
  131. </List>
  132. <List>
  133. <ModelConfigList
  134. modelConfig={{ ...props.mask.modelConfig }}
  135. updateConfig={updateConfig}
  136. />
  137. {props.extraListItems}
  138. </List>
  139. </>
  140. );
  141. }
  142. function ContextPromptItem(props: {
  143. prompt: ChatMessage;
  144. update: (prompt: ChatMessage) => void;
  145. remove: () => void;
  146. }) {
  147. const [focusingInput, setFocusingInput] = useState(false);
  148. return (
  149. <div className={chatStyle["context-prompt-row"]}>
  150. {!focusingInput && (
  151. <Select
  152. value={props.prompt.role}
  153. className={chatStyle["context-role"]}
  154. onChange={(e) =>
  155. props.update({
  156. ...props.prompt,
  157. role: e.target.value as any,
  158. })
  159. }
  160. >
  161. {ROLES.map((r) => (
  162. <option key={r} value={r}>
  163. {r}
  164. </option>
  165. ))}
  166. </Select>
  167. )}
  168. <Input
  169. value={props.prompt.content}
  170. type="text"
  171. className={chatStyle["context-content"]}
  172. rows={focusingInput ? 5 : 1}
  173. onFocus={() => setFocusingInput(true)}
  174. onBlur={() => {
  175. setFocusingInput(false);
  176. // If the selection is not removed when the user loses focus, some
  177. // extensions like "Translate" will always display a floating bar
  178. window?.getSelection()?.removeAllRanges();
  179. }}
  180. onInput={(e) =>
  181. props.update({
  182. ...props.prompt,
  183. content: e.currentTarget.value as any,
  184. })
  185. }
  186. />
  187. {!focusingInput && (
  188. <IconButton
  189. icon={<DeleteIcon />}
  190. className={chatStyle["context-delete-button"]}
  191. onClick={() => props.remove()}
  192. bordered
  193. />
  194. )}
  195. </div>
  196. );
  197. }
  198. export function ContextPrompts(props: {
  199. context: ChatMessage[];
  200. updateContext: (updater: (context: ChatMessage[]) => void) => void;
  201. }) {
  202. const context = props.context;
  203. const addContextPrompt = (prompt: ChatMessage) => {
  204. props.updateContext((context) => context.push(prompt));
  205. };
  206. const removeContextPrompt = (i: number) => {
  207. props.updateContext((context) => context.splice(i, 1));
  208. };
  209. const updateContextPrompt = (i: number, prompt: ChatMessage) => {
  210. props.updateContext((context) => (context[i] = prompt));
  211. };
  212. return (
  213. <>
  214. <div className={chatStyle["context-prompt"]} style={{ marginBottom: 20 }}>
  215. {context.map((c, i) => (
  216. <ContextPromptItem
  217. key={i}
  218. prompt={c}
  219. update={(prompt) => updateContextPrompt(i, prompt)}
  220. remove={() => removeContextPrompt(i)}
  221. />
  222. ))}
  223. <div className={chatStyle["context-prompt-row"]}>
  224. <IconButton
  225. icon={<AddIcon />}
  226. text={Locale.Context.Add}
  227. bordered
  228. className={chatStyle["context-prompt-button"]}
  229. onClick={() =>
  230. addContextPrompt({
  231. role: "user",
  232. content: "",
  233. date: "",
  234. })
  235. }
  236. />
  237. </div>
  238. </div>
  239. </>
  240. );
  241. }
  242. export function MaskPage() {
  243. const navigate = useNavigate();
  244. const maskStore = useMaskStore();
  245. const chatStore = useChatStore();
  246. const [filterLang, setFilterLang] = useState<Lang>();
  247. const allMasks = maskStore
  248. .getAll()
  249. .filter((m) => !filterLang || m.lang === filterLang);
  250. const [searchMasks, setSearchMasks] = useState<Mask[]>([]);
  251. const [searchText, setSearchText] = useState("");
  252. const masks = searchText.length > 0 ? searchMasks : allMasks;
  253. // simple search, will refactor later
  254. const onSearch = (text: string) => {
  255. setSearchText(text);
  256. if (text.length > 0) {
  257. const result = allMasks.filter((m) => m.name.includes(text));
  258. setSearchMasks(result);
  259. } else {
  260. setSearchMasks(allMasks);
  261. }
  262. };
  263. const [editingMaskId, setEditingMaskId] = useState<number | undefined>();
  264. const editingMask =
  265. maskStore.get(editingMaskId) ?? BUILTIN_MASK_STORE.get(editingMaskId);
  266. const closeMaskModal = () => setEditingMaskId(undefined);
  267. const downloadAll = () => {
  268. downloadAs(JSON.stringify(masks), FileName.Masks);
  269. };
  270. const importFromFile = () => {
  271. readFromFile().then((content) => {
  272. try {
  273. const importMasks = JSON.parse(content);
  274. if (Array.isArray(importMasks)) {
  275. for (const mask of importMasks) {
  276. if (mask.name) {
  277. maskStore.create(mask);
  278. }
  279. }
  280. return;
  281. }
  282. //if the content is a single mask.
  283. if (importMasks.name) {
  284. maskStore.create(importMasks);
  285. }
  286. } catch {}
  287. });
  288. };
  289. return (
  290. <ErrorBoundary>
  291. <div className={styles["mask-page"]}>
  292. <div className="window-header">
  293. <div className="window-header-title">
  294. <div className="window-header-main-title">
  295. {Locale.Mask.Page.Title}
  296. </div>
  297. <div className="window-header-submai-title">
  298. {Locale.Mask.Page.SubTitle(allMasks.length)}
  299. </div>
  300. </div>
  301. <div className="window-actions">
  302. <div className="window-action-button">
  303. <IconButton
  304. icon={<DownloadIcon />}
  305. bordered
  306. onClick={downloadAll}
  307. />
  308. </div>
  309. <div className="window-action-button">
  310. <IconButton
  311. icon={<UploadIcon />}
  312. bordered
  313. onClick={() => importFromFile()}
  314. />
  315. </div>
  316. <div className="window-action-button">
  317. <IconButton
  318. icon={<CloseIcon />}
  319. bordered
  320. onClick={() => navigate(-1)}
  321. />
  322. </div>
  323. </div>
  324. </div>
  325. <div className={styles["mask-page-body"]}>
  326. <div className={styles["mask-filter"]}>
  327. <input
  328. type="text"
  329. className={styles["search-bar"]}
  330. placeholder={Locale.Mask.Page.Search}
  331. autoFocus
  332. onInput={(e) => onSearch(e.currentTarget.value)}
  333. />
  334. <Select
  335. className={styles["mask-filter-lang"]}
  336. value={filterLang ?? Locale.Settings.Lang.All}
  337. onChange={(e) => {
  338. const value = e.currentTarget.value;
  339. if (value === Locale.Settings.Lang.All) {
  340. setFilterLang(undefined);
  341. } else {
  342. setFilterLang(value as Lang);
  343. }
  344. }}
  345. >
  346. <option key="all" value={Locale.Settings.Lang.All}>
  347. {Locale.Settings.Lang.All}
  348. </option>
  349. {AllLangs.map((lang) => (
  350. <option value={lang} key={lang}>
  351. {ALL_LANG_OPTIONS[lang]}
  352. </option>
  353. ))}
  354. </Select>
  355. <IconButton
  356. className={styles["mask-create"]}
  357. icon={<AddIcon />}
  358. text={Locale.Mask.Page.Create}
  359. bordered
  360. onClick={() => {
  361. const createdMask = maskStore.create();
  362. setEditingMaskId(createdMask.id);
  363. }}
  364. />
  365. </div>
  366. <div>
  367. {masks.map((m) => (
  368. <div className={styles["mask-item"]} key={m.id}>
  369. <div className={styles["mask-header"]}>
  370. <div className={styles["mask-icon"]}>
  371. <MaskAvatar mask={m} />
  372. </div>
  373. <div className={styles["mask-title"]}>
  374. <div className={styles["mask-name"]}>{m.name}</div>
  375. <div className={styles["mask-info"] + " one-line"}>
  376. {`${Locale.Mask.Item.Info(m.context.length)} / ${
  377. ALL_LANG_OPTIONS[m.lang]
  378. } / ${m.modelConfig.model}`}
  379. </div>
  380. </div>
  381. </div>
  382. <div className={styles["mask-actions"]}>
  383. <IconButton
  384. icon={<AddIcon />}
  385. text={Locale.Mask.Item.Chat}
  386. onClick={() => {
  387. chatStore.newSession(m);
  388. navigate(Path.Chat);
  389. }}
  390. />
  391. {m.builtin ? (
  392. <IconButton
  393. icon={<EyeIcon />}
  394. text={Locale.Mask.Item.View}
  395. onClick={() => setEditingMaskId(m.id)}
  396. />
  397. ) : (
  398. <IconButton
  399. icon={<EditIcon />}
  400. text={Locale.Mask.Item.Edit}
  401. onClick={() => setEditingMaskId(m.id)}
  402. />
  403. )}
  404. {!m.builtin && (
  405. <IconButton
  406. icon={<DeleteIcon />}
  407. text={Locale.Mask.Item.Delete}
  408. onClick={() => {
  409. if (confirm(Locale.Mask.Item.DeleteConfirm)) {
  410. maskStore.delete(m.id);
  411. }
  412. }}
  413. />
  414. )}
  415. </div>
  416. </div>
  417. ))}
  418. </div>
  419. </div>
  420. </div>
  421. {editingMask && (
  422. <div className="modal-mask">
  423. <Modal
  424. title={Locale.Mask.EditModal.Title(editingMask?.builtin)}
  425. onClose={closeMaskModal}
  426. actions={[
  427. <IconButton
  428. icon={<DownloadIcon />}
  429. text={Locale.Mask.EditModal.Download}
  430. key="export"
  431. bordered
  432. onClick={() =>
  433. downloadAs(
  434. JSON.stringify(editingMask),
  435. `${editingMask.name}.json`,
  436. )
  437. }
  438. />,
  439. <IconButton
  440. key="copy"
  441. icon={<CopyIcon />}
  442. bordered
  443. text={Locale.Mask.EditModal.Clone}
  444. onClick={() => {
  445. navigate(Path.Masks);
  446. maskStore.create(editingMask);
  447. setEditingMaskId(undefined);
  448. }}
  449. />,
  450. ]}
  451. >
  452. <MaskConfig
  453. mask={editingMask}
  454. updateMask={(updater) =>
  455. maskStore.update(editingMaskId!, updater)
  456. }
  457. readonly={editingMask.builtin}
  458. />
  459. </Modal>
  460. </div>
  461. )}
  462. </ErrorBoundary>
  463. );
  464. }