mask.tsx 18 KB

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