mask.tsx 19 KB

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