mask.tsx 21 KB

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