mask.tsx 19 KB

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