mask.tsx 20 KB

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