mask.tsx 17 KB

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