mask.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. useAppConfig,
  19. useChatStore,
  20. } from "../store";
  21. import {
  22. Input,
  23. List,
  24. ListItem,
  25. Modal,
  26. Popover,
  27. Select,
  28. showConfirm,
  29. } from "./ui-lib";
  30. import { Avatar, AvatarPicker } from "./emoji";
  31. import Locale, { AllLangs, ALL_LANG_OPTIONS, Lang } from "../locales";
  32. import { useNavigate } from "react-router-dom";
  33. import chatStyle from "./chat.module.scss";
  34. import { useState } from "react";
  35. import { copyToClipboard, downloadAs, readFromFile } from "../utils";
  36. import { Updater } from "../typing";
  37. import { FileName, Path } from "../constant";
  38. import { BUILTIN_MASK_STORE } from "../masks";
  39. import {
  40. DragDropContext,
  41. Droppable,
  42. Draggable,
  43. OnDragEndResponder,
  44. } from "@hello-pangea/dnd";
  45. import { ROLES } from "../client";
  46. import { deepClone } from "../utils/clone";
  47. import { ChatConfigList, ModelConfigList, ProviderSelectItem } from "./config";
  48. // drag and drop helper function
  49. function reorder<T>(list: T[], startIndex: number, endIndex: number): T[] {
  50. const result = [...list];
  51. const [removed] = result.splice(startIndex, 1);
  52. result.splice(endIndex, 0, removed);
  53. return result;
  54. }
  55. export function MaskAvatar(props: { avatar: string; model: string }) {
  56. return props.avatar !== DEFAULT_MASK_AVATAR ? (
  57. <Avatar avatar={props.avatar} />
  58. ) : (
  59. <Avatar model={props.model} />
  60. );
  61. }
  62. export function MaskConfig(props: {
  63. mask: Mask;
  64. updateMask: Updater<Mask>;
  65. extraListItems?: JSX.Element;
  66. readonly?: boolean;
  67. shouldSyncFromGlobal?: boolean;
  68. }) {
  69. const [showPicker, setShowPicker] = useState(false);
  70. const modelConfig = useChatStore().extractModelConfig(props.mask.config);
  71. const updateConfig = (updater: (config: ModelConfig) => void) => {
  72. if (props.readonly) return;
  73. const config = deepClone(props.mask.config);
  74. updater(config.modelConfig);
  75. props.updateMask((mask) => {
  76. mask.config = 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={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.config = deepClone(globalConfig.globalMaskConfig);
  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. <ProviderSelectItem
  188. value={props.mask.config.provider}
  189. update={(value) => {
  190. props.updateMask((mask) => (mask.config.provider = value));
  191. }}
  192. />
  193. <ModelConfigList
  194. provider={props.mask.config.provider}
  195. config={props.mask.config.modelConfig}
  196. updateConfig={updateConfig}
  197. />
  198. </List>
  199. <List>
  200. <ChatConfigList
  201. config={props.mask.config.chatConfig}
  202. updateConfig={(updater) => {
  203. const chatConfig = deepClone(props.mask.config.chatConfig);
  204. updater(chatConfig);
  205. props.updateMask((mask) => (mask.config.chatConfig = chatConfig));
  206. }}
  207. />
  208. {props.extraListItems}
  209. </List>
  210. </>
  211. );
  212. }
  213. function ContextPromptItem(props: {
  214. index: number;
  215. prompt: ChatMessage;
  216. update: (prompt: ChatMessage) => void;
  217. remove: () => void;
  218. }) {
  219. const [focusingInput, setFocusingInput] = useState(false);
  220. return (
  221. <div className={chatStyle["context-prompt-row"]}>
  222. {!focusingInput && (
  223. <>
  224. <div className={chatStyle["context-drag"]}>
  225. <DragIcon />
  226. </div>
  227. <Select
  228. value={props.prompt.role}
  229. className={chatStyle["context-role"]}
  230. onChange={(e) =>
  231. props.update({
  232. ...props.prompt,
  233. role: e.target.value as any,
  234. })
  235. }
  236. >
  237. {ROLES.map((r) => (
  238. <option key={r} value={r}>
  239. {r}
  240. </option>
  241. ))}
  242. </Select>
  243. </>
  244. )}
  245. <Input
  246. value={props.prompt.content}
  247. type="text"
  248. className={chatStyle["context-content"]}
  249. rows={focusingInput ? 5 : 1}
  250. onFocus={() => setFocusingInput(true)}
  251. onBlur={() => {
  252. setFocusingInput(false);
  253. // If the selection is not removed when the user loses focus, some
  254. // extensions like "Translate" will always display a floating bar
  255. window?.getSelection()?.removeAllRanges();
  256. }}
  257. onInput={(e) =>
  258. props.update({
  259. ...props.prompt,
  260. content: e.currentTarget.value as any,
  261. })
  262. }
  263. />
  264. {!focusingInput && (
  265. <IconButton
  266. icon={<DeleteIcon />}
  267. className={chatStyle["context-delete-button"]}
  268. onClick={() => props.remove()}
  269. bordered
  270. />
  271. )}
  272. </div>
  273. );
  274. }
  275. export function ContextPrompts(props: {
  276. context: ChatMessage[];
  277. updateContext: (updater: (context: ChatMessage[]) => void) => void;
  278. }) {
  279. const context = props.context;
  280. const addContextPrompt = (prompt: ChatMessage, i: number) => {
  281. props.updateContext((context) => context.splice(i, 0, prompt));
  282. };
  283. const removeContextPrompt = (i: number) => {
  284. props.updateContext((context) => context.splice(i, 1));
  285. };
  286. const updateContextPrompt = (i: number, prompt: ChatMessage) => {
  287. props.updateContext((context) => (context[i] = prompt));
  288. };
  289. const onDragEnd: OnDragEndResponder = (result) => {
  290. if (!result.destination) {
  291. return;
  292. }
  293. const newContext = reorder(
  294. context,
  295. result.source.index,
  296. result.destination.index,
  297. );
  298. props.updateContext((context) => {
  299. context.splice(0, context.length, ...newContext);
  300. });
  301. };
  302. return (
  303. <>
  304. <div className={chatStyle["context-prompt"]} style={{ marginBottom: 20 }}>
  305. <DragDropContext onDragEnd={onDragEnd}>
  306. <Droppable droppableId="context-prompt-list">
  307. {(provided) => (
  308. <div ref={provided.innerRef} {...provided.droppableProps}>
  309. {context.map((c, i) => (
  310. <Draggable
  311. draggableId={c.id || i.toString()}
  312. index={i}
  313. key={c.id}
  314. >
  315. {(provided) => (
  316. <div
  317. ref={provided.innerRef}
  318. {...provided.draggableProps}
  319. {...provided.dragHandleProps}
  320. >
  321. <ContextPromptItem
  322. index={i}
  323. prompt={c}
  324. update={(prompt) => updateContextPrompt(i, prompt)}
  325. remove={() => removeContextPrompt(i)}
  326. />
  327. <div
  328. className={chatStyle["context-prompt-insert"]}
  329. onClick={() => {
  330. addContextPrompt(
  331. createMessage({
  332. role: "user",
  333. content: "",
  334. date: new Date().toLocaleString(),
  335. }),
  336. i + 1,
  337. );
  338. }}
  339. >
  340. <AddIcon />
  341. </div>
  342. </div>
  343. )}
  344. </Draggable>
  345. ))}
  346. {provided.placeholder}
  347. </div>
  348. )}
  349. </Droppable>
  350. </DragDropContext>
  351. {props.context.length === 0 && (
  352. <div className={chatStyle["context-prompt-row"]}>
  353. <IconButton
  354. icon={<AddIcon />}
  355. text={Locale.Context.Add}
  356. bordered
  357. className={chatStyle["context-prompt-button"]}
  358. onClick={() =>
  359. addContextPrompt(
  360. createMessage({
  361. role: "user",
  362. content: "",
  363. date: "",
  364. }),
  365. props.context.length,
  366. )
  367. }
  368. />
  369. </div>
  370. )}
  371. </div>
  372. </>
  373. );
  374. }
  375. export function MaskPage() {
  376. const navigate = useNavigate();
  377. const maskStore = useMaskStore();
  378. const chatStore = useChatStore();
  379. const [filterLang, setFilterLang] = useState<Lang>();
  380. const allMasks = maskStore
  381. .getAll()
  382. .filter((m) => !filterLang || m.lang === filterLang);
  383. const [searchMasks, setSearchMasks] = useState<Mask[]>([]);
  384. const [searchText, setSearchText] = useState("");
  385. const masks = searchText.length > 0 ? searchMasks : allMasks;
  386. // refactored already, now it accurate
  387. const onSearch = (text: string) => {
  388. setSearchText(text);
  389. if (text.length > 0) {
  390. const result = allMasks.filter((m) =>
  391. m.name.toLowerCase().includes(text.toLowerCase()),
  392. );
  393. setSearchMasks(result);
  394. } else {
  395. setSearchMasks(allMasks);
  396. }
  397. };
  398. const [editingMaskId, setEditingMaskId] = useState<string | undefined>();
  399. const editingMask =
  400. maskStore.get(editingMaskId) ?? BUILTIN_MASK_STORE.get(editingMaskId);
  401. const closeMaskModal = () => setEditingMaskId(undefined);
  402. const downloadAll = () => {
  403. downloadAs(JSON.stringify(masks.filter((v) => !v.builtin)), FileName.Masks);
  404. };
  405. const importFromFile = () => {
  406. readFromFile().then((content) => {
  407. try {
  408. const importMasks = JSON.parse(content);
  409. if (Array.isArray(importMasks)) {
  410. for (const mask of importMasks) {
  411. if (mask.name) {
  412. maskStore.create(mask);
  413. }
  414. }
  415. return;
  416. }
  417. //if the content is a single mask.
  418. if (importMasks.name) {
  419. maskStore.create(importMasks);
  420. }
  421. } catch {}
  422. });
  423. };
  424. return (
  425. <ErrorBoundary>
  426. <div className={styles["mask-page"]}>
  427. <div className="window-header">
  428. <div className="window-header-title">
  429. <div className="window-header-main-title">
  430. {Locale.Mask.Page.Title}
  431. </div>
  432. <div className="window-header-submai-title">
  433. {Locale.Mask.Page.SubTitle(allMasks.length)}
  434. </div>
  435. </div>
  436. <div className="window-actions">
  437. <div className="window-action-button">
  438. <IconButton
  439. icon={<DownloadIcon />}
  440. bordered
  441. onClick={downloadAll}
  442. text={Locale.UI.Export}
  443. />
  444. </div>
  445. <div className="window-action-button">
  446. <IconButton
  447. icon={<UploadIcon />}
  448. text={Locale.UI.Import}
  449. bordered
  450. onClick={() => importFromFile()}
  451. />
  452. </div>
  453. <div className="window-action-button">
  454. <IconButton
  455. icon={<CloseIcon />}
  456. bordered
  457. onClick={() => navigate(-1)}
  458. />
  459. </div>
  460. </div>
  461. </div>
  462. <div className={styles["mask-page-body"]}>
  463. <div className={styles["mask-filter"]}>
  464. <input
  465. type="text"
  466. className={styles["search-bar"]}
  467. placeholder={Locale.Mask.Page.Search}
  468. autoFocus
  469. onInput={(e) => onSearch(e.currentTarget.value)}
  470. />
  471. <Select
  472. className={styles["mask-filter-lang"]}
  473. value={filterLang ?? Locale.Settings.Lang.All}
  474. onChange={(e) => {
  475. const value = e.currentTarget.value;
  476. if (value === Locale.Settings.Lang.All) {
  477. setFilterLang(undefined);
  478. } else {
  479. setFilterLang(value as Lang);
  480. }
  481. }}
  482. >
  483. <option key="all" value={Locale.Settings.Lang.All}>
  484. {Locale.Settings.Lang.All}
  485. </option>
  486. {AllLangs.map((lang) => (
  487. <option value={lang} key={lang}>
  488. {ALL_LANG_OPTIONS[lang]}
  489. </option>
  490. ))}
  491. </Select>
  492. <IconButton
  493. className={styles["mask-create"]}
  494. icon={<AddIcon />}
  495. text={Locale.Mask.Page.Create}
  496. bordered
  497. onClick={() => {
  498. const createdMask = maskStore.create();
  499. setEditingMaskId(createdMask.id);
  500. }}
  501. />
  502. </div>
  503. <div>
  504. {masks.map((m) => (
  505. <div className={styles["mask-item"]} key={m.id}>
  506. <div className={styles["mask-header"]}>
  507. <div className={styles["mask-icon"]}>
  508. <MaskAvatar
  509. avatar={m.avatar}
  510. model={chatStore.extractModelConfig(m.config).model}
  511. />
  512. </div>
  513. <div className={styles["mask-title"]}>
  514. <div className={styles["mask-name"]}>{m.name}</div>
  515. <div className={styles["mask-info"] + " one-line"}>
  516. {`${Locale.Mask.Item.Info(m.context.length)} / ${
  517. ALL_LANG_OPTIONS[m.lang]
  518. } / ${chatStore.extractModelConfig(m.config).model}`}
  519. </div>
  520. </div>
  521. </div>
  522. <div className={styles["mask-actions"]}>
  523. <IconButton
  524. icon={<AddIcon />}
  525. text={Locale.Mask.Item.Chat}
  526. onClick={() => {
  527. chatStore.newSession(m);
  528. navigate(Path.Chat);
  529. }}
  530. />
  531. {m.builtin ? (
  532. <IconButton
  533. icon={<EyeIcon />}
  534. text={Locale.Mask.Item.View}
  535. onClick={() => setEditingMaskId(m.id)}
  536. />
  537. ) : (
  538. <IconButton
  539. icon={<EditIcon />}
  540. text={Locale.Mask.Item.Edit}
  541. onClick={() => setEditingMaskId(m.id)}
  542. />
  543. )}
  544. {!m.builtin && (
  545. <IconButton
  546. icon={<DeleteIcon />}
  547. text={Locale.Mask.Item.Delete}
  548. onClick={async () => {
  549. if (await showConfirm(Locale.Mask.Item.DeleteConfirm)) {
  550. maskStore.delete(m.id);
  551. }
  552. }}
  553. />
  554. )}
  555. </div>
  556. </div>
  557. ))}
  558. </div>
  559. </div>
  560. </div>
  561. {editingMask && (
  562. <div className="modal-mask">
  563. <Modal
  564. title={Locale.Mask.EditModal.Title(editingMask?.builtin)}
  565. onClose={closeMaskModal}
  566. actions={[
  567. <IconButton
  568. icon={<DownloadIcon />}
  569. text={Locale.Mask.EditModal.Download}
  570. key="export"
  571. bordered
  572. onClick={() =>
  573. downloadAs(
  574. JSON.stringify(editingMask),
  575. `${editingMask.name}.json`,
  576. )
  577. }
  578. />,
  579. <IconButton
  580. key="copy"
  581. icon={<CopyIcon />}
  582. bordered
  583. text={Locale.Mask.EditModal.Clone}
  584. onClick={() => {
  585. navigate(Path.Masks);
  586. maskStore.create(editingMask);
  587. setEditingMaskId(undefined);
  588. }}
  589. />,
  590. ]}
  591. >
  592. <MaskConfig
  593. mask={editingMask}
  594. updateMask={(updater) =>
  595. maskStore.updateMask(editingMaskId!, updater)
  596. }
  597. readonly={editingMask.builtin}
  598. />
  599. </Modal>
  600. </div>
  601. )}
  602. </ErrorBoundary>
  603. );
  604. }