mask.tsx 16 KB

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