mask.tsx 16 KB

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