mask.tsx 21 KB

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