mask.tsx 14 KB

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