mask.tsx 20 KB

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