mask.tsx 20 KB

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