mask.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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={() => setFocusingInput(false)}
  175. onInput={(e) =>
  176. props.update({
  177. ...props.prompt,
  178. content: e.currentTarget.value as any,
  179. })
  180. }
  181. />
  182. {!focusingInput && (
  183. <IconButton
  184. icon={<DeleteIcon />}
  185. className={chatStyle["context-delete-button"]}
  186. onClick={() => props.remove()}
  187. bordered
  188. />
  189. )}
  190. </div>
  191. );
  192. }
  193. export function ContextPrompts(props: {
  194. context: ChatMessage[];
  195. updateContext: (updater: (context: ChatMessage[]) => void) => void;
  196. }) {
  197. const context = props.context;
  198. const addContextPrompt = (prompt: ChatMessage) => {
  199. props.updateContext((context) => context.push(prompt));
  200. };
  201. const removeContextPrompt = (i: number) => {
  202. props.updateContext((context) => context.splice(i, 1));
  203. };
  204. const updateContextPrompt = (i: number, prompt: ChatMessage) => {
  205. props.updateContext((context) => (context[i] = prompt));
  206. };
  207. return (
  208. <>
  209. <div className={chatStyle["context-prompt"]} style={{ marginBottom: 20 }}>
  210. {context.map((c, i) => (
  211. <ContextPromptItem
  212. key={i}
  213. prompt={c}
  214. update={(prompt) => updateContextPrompt(i, prompt)}
  215. remove={() => removeContextPrompt(i)}
  216. />
  217. ))}
  218. <div className={chatStyle["context-prompt-row"]}>
  219. <IconButton
  220. icon={<AddIcon />}
  221. text={Locale.Context.Add}
  222. bordered
  223. className={chatStyle["context-prompt-button"]}
  224. onClick={() =>
  225. addContextPrompt({
  226. role: "user",
  227. content: "",
  228. date: "",
  229. })
  230. }
  231. />
  232. </div>
  233. </div>
  234. </>
  235. );
  236. }
  237. export function MaskPage() {
  238. const navigate = useNavigate();
  239. const maskStore = useMaskStore();
  240. const chatStore = useChatStore();
  241. const [filterLang, setFilterLang] = useState<Lang>();
  242. const allMasks = maskStore
  243. .getAll()
  244. .filter((m) => !filterLang || m.lang === filterLang);
  245. const [searchMasks, setSearchMasks] = useState<Mask[]>([]);
  246. const [searchText, setSearchText] = useState("");
  247. const masks = searchText.length > 0 ? searchMasks : allMasks;
  248. // simple search, will refactor later
  249. const onSearch = (text: string) => {
  250. setSearchText(text);
  251. if (text.length > 0) {
  252. const result = allMasks.filter((m) => m.name.includes(text));
  253. setSearchMasks(result);
  254. } else {
  255. setSearchMasks(allMasks);
  256. }
  257. };
  258. const [editingMaskId, setEditingMaskId] = useState<number | undefined>();
  259. const editingMask =
  260. maskStore.get(editingMaskId) ?? BUILTIN_MASK_STORE.get(editingMaskId);
  261. const closeMaskModal = () => setEditingMaskId(undefined);
  262. const downloadAll = () => {
  263. downloadAs(JSON.stringify(masks), FileName.Masks);
  264. };
  265. const importFromFile = () => {
  266. readFromFile().then((content) => {
  267. try {
  268. const importMasks = JSON.parse(content);
  269. if (Array.isArray(importMasks)) {
  270. for (const mask of importMasks) {
  271. if (mask.name) {
  272. maskStore.create(mask);
  273. }
  274. }
  275. return;
  276. }
  277. //if the content is a single mask.
  278. if (importMasks.name) {
  279. maskStore.create(importMasks);
  280. }
  281. } catch {}
  282. });
  283. };
  284. return (
  285. <ErrorBoundary>
  286. <div className={styles["mask-page"]}>
  287. <div className="window-header">
  288. <div className="window-header-title">
  289. <div className="window-header-main-title">
  290. {Locale.Mask.Page.Title}
  291. </div>
  292. <div className="window-header-submai-title">
  293. {Locale.Mask.Page.SubTitle(allMasks.length)}
  294. </div>
  295. </div>
  296. <div className="window-actions">
  297. <div className="window-action-button">
  298. <IconButton
  299. icon={<DownloadIcon />}
  300. bordered
  301. onClick={downloadAll}
  302. />
  303. </div>
  304. <div className="window-action-button">
  305. <IconButton
  306. icon={<UploadIcon />}
  307. bordered
  308. onClick={() => importFromFile()}
  309. />
  310. </div>
  311. <div className="window-action-button">
  312. <IconButton
  313. icon={<CloseIcon />}
  314. bordered
  315. onClick={() => navigate(-1)}
  316. />
  317. </div>
  318. </div>
  319. </div>
  320. <div className={styles["mask-page-body"]}>
  321. <div className={styles["mask-filter"]}>
  322. <input
  323. type="text"
  324. className={styles["search-bar"]}
  325. placeholder={Locale.Mask.Page.Search}
  326. autoFocus
  327. onInput={(e) => onSearch(e.currentTarget.value)}
  328. />
  329. <Select
  330. className={styles["mask-filter-lang"]}
  331. value={filterLang ?? Locale.Settings.Lang.All}
  332. onChange={(e) => {
  333. const value = e.currentTarget.value;
  334. if (value === Locale.Settings.Lang.All) {
  335. setFilterLang(undefined);
  336. } else {
  337. setFilterLang(value as Lang);
  338. }
  339. }}
  340. >
  341. <option key="all" value={Locale.Settings.Lang.All}>
  342. {Locale.Settings.Lang.All}
  343. </option>
  344. {AllLangs.map((lang) => (
  345. <option value={lang} key={lang}>
  346. {ALL_LANG_OPTIONS[lang]}
  347. </option>
  348. ))}
  349. </Select>
  350. <IconButton
  351. className={styles["mask-create"]}
  352. icon={<AddIcon />}
  353. text={Locale.Mask.Page.Create}
  354. bordered
  355. onClick={() => {
  356. const createdMask = maskStore.create();
  357. setEditingMaskId(createdMask.id);
  358. }}
  359. />
  360. </div>
  361. <div>
  362. {masks.map((m) => (
  363. <div className={styles["mask-item"]} key={m.id}>
  364. <div className={styles["mask-header"]}>
  365. <div className={styles["mask-icon"]}>
  366. <MaskAvatar mask={m} />
  367. </div>
  368. <div className={styles["mask-title"]}>
  369. <div className={styles["mask-name"]}>{m.name}</div>
  370. <div className={styles["mask-info"] + " one-line"}>
  371. {`${Locale.Mask.Item.Info(m.context.length)} / ${
  372. ALL_LANG_OPTIONS[m.lang]
  373. } / ${m.modelConfig.model}`}
  374. </div>
  375. </div>
  376. </div>
  377. <div className={styles["mask-actions"]}>
  378. <IconButton
  379. icon={<AddIcon />}
  380. text={Locale.Mask.Item.Chat}
  381. onClick={() => {
  382. chatStore.newSession(m);
  383. navigate(Path.Chat);
  384. }}
  385. />
  386. {m.builtin ? (
  387. <IconButton
  388. icon={<EyeIcon />}
  389. text={Locale.Mask.Item.View}
  390. onClick={() => setEditingMaskId(m.id)}
  391. />
  392. ) : (
  393. <IconButton
  394. icon={<EditIcon />}
  395. text={Locale.Mask.Item.Edit}
  396. onClick={() => setEditingMaskId(m.id)}
  397. />
  398. )}
  399. {!m.builtin && (
  400. <IconButton
  401. icon={<DeleteIcon />}
  402. text={Locale.Mask.Item.Delete}
  403. onClick={() => {
  404. if (confirm(Locale.Mask.Item.DeleteConfirm)) {
  405. maskStore.delete(m.id);
  406. }
  407. }}
  408. />
  409. )}
  410. </div>
  411. </div>
  412. ))}
  413. </div>
  414. </div>
  415. </div>
  416. {editingMask && (
  417. <div className="modal-mask">
  418. <Modal
  419. title={Locale.Mask.EditModal.Title(editingMask?.builtin)}
  420. onClose={closeMaskModal}
  421. actions={[
  422. <IconButton
  423. icon={<DownloadIcon />}
  424. text={Locale.Mask.EditModal.Download}
  425. key="export"
  426. bordered
  427. onClick={() =>
  428. downloadAs(
  429. JSON.stringify(editingMask),
  430. `${editingMask.name}.json`,
  431. )
  432. }
  433. />,
  434. <IconButton
  435. key="copy"
  436. icon={<CopyIcon />}
  437. bordered
  438. text={Locale.Mask.EditModal.Clone}
  439. onClick={() => {
  440. navigate(Path.Masks);
  441. maskStore.create(editingMask);
  442. setEditingMaskId(undefined);
  443. }}
  444. />,
  445. ]}
  446. >
  447. <MaskConfig
  448. mask={editingMask}
  449. updateMask={(updater) =>
  450. maskStore.update(editingMaskId!, updater)
  451. }
  452. readonly={editingMask.builtin}
  453. />
  454. </Modal>
  455. </div>
  456. )}
  457. </ErrorBoundary>
  458. );
  459. }