mask.tsx 20 KB

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