mask.tsx 19 KB

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