mask.tsx 13 KB

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