mask.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 !== false}
  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 = maskStore.language;
  401. const allMasks = maskStore
  402. .getAll()
  403. .filter((m) => !filterLang || m.lang === filterLang);
  404. const [searchMasks, setSearchMasks] = useState<Mask[]>([]);
  405. const [searchText, setSearchText] = useState("");
  406. const masks = searchText.length > 0 ? searchMasks : allMasks;
  407. // refactored already, now it accurate
  408. const onSearch = (text: string) => {
  409. setSearchText(text);
  410. if (text.length > 0) {
  411. const result = allMasks.filter((m) =>
  412. m.name.toLowerCase().includes(text.toLowerCase()),
  413. );
  414. setSearchMasks(result);
  415. } else {
  416. setSearchMasks(allMasks);
  417. }
  418. };
  419. const [editingMaskId, setEditingMaskId] = useState<string | undefined>();
  420. const editingMask =
  421. maskStore.get(editingMaskId) ?? BUILTIN_MASK_STORE.get(editingMaskId);
  422. const closeMaskModal = () => setEditingMaskId(undefined);
  423. const downloadAll = () => {
  424. downloadAs(JSON.stringify(masks.filter((v) => !v.builtin)), FileName.Masks);
  425. };
  426. const importFromFile = () => {
  427. readFromFile().then((content) => {
  428. try {
  429. const importMasks = JSON.parse(content);
  430. if (Array.isArray(importMasks)) {
  431. for (const mask of importMasks) {
  432. if (mask.name) {
  433. maskStore.create(mask);
  434. }
  435. }
  436. return;
  437. }
  438. //if the content is a single mask.
  439. if (importMasks.name) {
  440. maskStore.create(importMasks);
  441. }
  442. } catch {}
  443. });
  444. };
  445. return (
  446. <ErrorBoundary>
  447. <div className={styles["mask-page"]}>
  448. <div className="window-header">
  449. <div className="window-header-title">
  450. <div className="window-header-main-title">
  451. {Locale.Mask.Page.Title}
  452. </div>
  453. <div className="window-header-submai-title">
  454. {Locale.Mask.Page.SubTitle(allMasks.length)}
  455. </div>
  456. </div>
  457. <div className="window-actions">
  458. <div className="window-action-button">
  459. <IconButton
  460. icon={<DownloadIcon />}
  461. bordered
  462. onClick={downloadAll}
  463. text={Locale.UI.Export}
  464. />
  465. </div>
  466. <div className="window-action-button">
  467. <IconButton
  468. icon={<UploadIcon />}
  469. text={Locale.UI.Import}
  470. bordered
  471. onClick={() => importFromFile()}
  472. />
  473. </div>
  474. <div className="window-action-button">
  475. <IconButton
  476. icon={<CloseIcon />}
  477. bordered
  478. onClick={() => navigate(-1)}
  479. />
  480. </div>
  481. </div>
  482. </div>
  483. <div className={styles["mask-page-body"]}>
  484. <div className={styles["mask-filter"]}>
  485. <input
  486. type="text"
  487. className={styles["search-bar"]}
  488. placeholder={Locale.Mask.Page.Search}
  489. autoFocus
  490. onInput={(e) => onSearch(e.currentTarget.value)}
  491. />
  492. <Select
  493. className={styles["mask-filter-lang"]}
  494. value={filterLang ?? Locale.Settings.Lang.All}
  495. onChange={(e) => {
  496. const value = e.currentTarget.value;
  497. if (value === Locale.Settings.Lang.All) {
  498. maskStore.setLanguage(undefined);
  499. } else {
  500. maskStore.setLanguage(value as Lang);
  501. }
  502. }}
  503. >
  504. <option key="all" value={Locale.Settings.Lang.All}>
  505. {Locale.Settings.Lang.All}
  506. </option>
  507. {AllLangs.map((lang) => (
  508. <option value={lang} key={lang}>
  509. {ALL_LANG_OPTIONS[lang]}
  510. </option>
  511. ))}
  512. </Select>
  513. <IconButton
  514. className={styles["mask-create"]}
  515. icon={<AddIcon />}
  516. text={Locale.Mask.Page.Create}
  517. bordered
  518. onClick={() => {
  519. const createdMask = maskStore.create();
  520. setEditingMaskId(createdMask.id);
  521. }}
  522. />
  523. </div>
  524. <div>
  525. {masks.map((m) => (
  526. <div className={styles["mask-item"]} key={m.id}>
  527. <div className={styles["mask-header"]}>
  528. <div className={styles["mask-icon"]}>
  529. <MaskAvatar avatar={m.avatar} model={m.modelConfig.model} />
  530. </div>
  531. <div className={styles["mask-title"]}>
  532. <div className={styles["mask-name"]}>{m.name}</div>
  533. <div className={styles["mask-info"] + " one-line"}>
  534. {`${Locale.Mask.Item.Info(m.context.length)} / ${
  535. ALL_LANG_OPTIONS[m.lang]
  536. } / ${m.modelConfig.model}`}
  537. </div>
  538. </div>
  539. </div>
  540. <div className={styles["mask-actions"]}>
  541. <IconButton
  542. icon={<AddIcon />}
  543. text={Locale.Mask.Item.Chat}
  544. onClick={() => {
  545. chatStore.newSession(m);
  546. navigate(Path.Chat);
  547. }}
  548. />
  549. {m.builtin ? (
  550. <IconButton
  551. icon={<EyeIcon />}
  552. text={Locale.Mask.Item.View}
  553. onClick={() => setEditingMaskId(m.id)}
  554. />
  555. ) : (
  556. <IconButton
  557. icon={<EditIcon />}
  558. text={Locale.Mask.Item.Edit}
  559. onClick={() => setEditingMaskId(m.id)}
  560. />
  561. )}
  562. {!m.builtin && (
  563. <IconButton
  564. icon={<DeleteIcon />}
  565. text={Locale.Mask.Item.Delete}
  566. onClick={async () => {
  567. if (await showConfirm(Locale.Mask.Item.DeleteConfirm)) {
  568. maskStore.delete(m.id);
  569. }
  570. }}
  571. />
  572. )}
  573. </div>
  574. </div>
  575. ))}
  576. </div>
  577. </div>
  578. </div>
  579. {editingMask && (
  580. <div className="modal-mask">
  581. <Modal
  582. title={Locale.Mask.EditModal.Title(editingMask?.builtin)}
  583. onClose={closeMaskModal}
  584. actions={[
  585. <IconButton
  586. icon={<DownloadIcon />}
  587. text={Locale.Mask.EditModal.Download}
  588. key="export"
  589. bordered
  590. onClick={() =>
  591. downloadAs(
  592. JSON.stringify(editingMask),
  593. `${editingMask.name}.json`,
  594. )
  595. }
  596. />,
  597. <IconButton
  598. key="copy"
  599. icon={<CopyIcon />}
  600. bordered
  601. text={Locale.Mask.EditModal.Clone}
  602. onClick={() => {
  603. navigate(Path.Masks);
  604. maskStore.create(editingMask);
  605. setEditingMaskId(undefined);
  606. }}
  607. />,
  608. ]}
  609. >
  610. <MaskConfig
  611. mask={editingMask}
  612. updateMask={(updater) =>
  613. maskStore.updateMask(editingMaskId!, updater)
  614. }
  615. readonly={editingMask.builtin}
  616. />
  617. </Modal>
  618. </div>
  619. )}
  620. </ErrorBoundary>
  621. );
  622. }