mask.tsx 20 KB

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