mask.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. // simple search, will refactor later
  366. const onSearch = (text: string) => {
  367. setSearchText(text);
  368. if (text.length > 0) {
  369. const result = allMasks.filter((m) => m.name.includes(text));
  370. setSearchMasks(result);
  371. } else {
  372. setSearchMasks(allMasks);
  373. }
  374. };
  375. const [editingMaskId, setEditingMaskId] = useState<string | undefined>();
  376. const editingMask =
  377. maskStore.get(editingMaskId) ?? BUILTIN_MASK_STORE.get(editingMaskId);
  378. const closeMaskModal = () => setEditingMaskId(undefined);
  379. const downloadAll = () => {
  380. downloadAs(JSON.stringify(masks), FileName.Masks);
  381. };
  382. const importFromFile = () => {
  383. readFromFile().then((content) => {
  384. try {
  385. const importMasks = JSON.parse(content);
  386. if (Array.isArray(importMasks)) {
  387. for (const mask of importMasks) {
  388. if (mask.name) {
  389. maskStore.create(mask);
  390. }
  391. }
  392. return;
  393. }
  394. //if the content is a single mask.
  395. if (importMasks.name) {
  396. maskStore.create(importMasks);
  397. }
  398. } catch {}
  399. });
  400. };
  401. return (
  402. <ErrorBoundary>
  403. <div className={styles["mask-page"]}>
  404. <div className="window-header">
  405. <div className="window-header-title">
  406. <div className="window-header-main-title">
  407. {Locale.Mask.Page.Title}
  408. </div>
  409. <div className="window-header-submai-title">
  410. {Locale.Mask.Page.SubTitle(allMasks.length)}
  411. </div>
  412. </div>
  413. <div className="window-actions">
  414. <div className="window-action-button">
  415. <IconButton
  416. icon={<DownloadIcon />}
  417. bordered
  418. onClick={downloadAll}
  419. />
  420. </div>
  421. <div className="window-action-button">
  422. <IconButton
  423. icon={<UploadIcon />}
  424. bordered
  425. onClick={() => importFromFile()}
  426. />
  427. </div>
  428. <div className="window-action-button">
  429. <IconButton
  430. icon={<CloseIcon />}
  431. bordered
  432. onClick={() => navigate(-1)}
  433. />
  434. </div>
  435. </div>
  436. </div>
  437. <div className={styles["mask-page-body"]}>
  438. <div className={styles["mask-filter"]}>
  439. <input
  440. type="text"
  441. className={styles["search-bar"]}
  442. placeholder={Locale.Mask.Page.Search}
  443. autoFocus
  444. onInput={(e) => onSearch(e.currentTarget.value)}
  445. />
  446. <Select
  447. className={styles["mask-filter-lang"]}
  448. value={filterLang ?? Locale.Settings.Lang.All}
  449. onChange={(e) => {
  450. const value = e.currentTarget.value;
  451. if (value === Locale.Settings.Lang.All) {
  452. setFilterLang(undefined);
  453. } else {
  454. setFilterLang(value as Lang);
  455. }
  456. }}
  457. >
  458. <option key="all" value={Locale.Settings.Lang.All}>
  459. {Locale.Settings.Lang.All}
  460. </option>
  461. {AllLangs.map((lang) => (
  462. <option value={lang} key={lang}>
  463. {ALL_LANG_OPTIONS[lang]}
  464. </option>
  465. ))}
  466. </Select>
  467. <IconButton
  468. className={styles["mask-create"]}
  469. icon={<AddIcon />}
  470. text={Locale.Mask.Page.Create}
  471. bordered
  472. onClick={() => {
  473. const createdMask = maskStore.create();
  474. setEditingMaskId(createdMask.id);
  475. }}
  476. />
  477. </div>
  478. <div>
  479. {masks.map((m) => (
  480. <div className={styles["mask-item"]} key={m.id}>
  481. <div className={styles["mask-header"]}>
  482. <div className={styles["mask-icon"]}>
  483. <MaskAvatar mask={m} />
  484. </div>
  485. <div className={styles["mask-title"]}>
  486. <div className={styles["mask-name"]}>{m.name}</div>
  487. <div className={styles["mask-info"] + " one-line"}>
  488. {`${Locale.Mask.Item.Info(m.context.length)} / ${
  489. ALL_LANG_OPTIONS[m.lang]
  490. } / ${m.modelConfig.model}`}
  491. </div>
  492. </div>
  493. </div>
  494. <div className={styles["mask-actions"]}>
  495. <IconButton
  496. icon={<AddIcon />}
  497. text={Locale.Mask.Item.Chat}
  498. onClick={() => {
  499. chatStore.newSession(m);
  500. navigate(Path.Chat);
  501. }}
  502. />
  503. {m.builtin ? (
  504. <IconButton
  505. icon={<EyeIcon />}
  506. text={Locale.Mask.Item.View}
  507. onClick={() => setEditingMaskId(m.id)}
  508. />
  509. ) : (
  510. <IconButton
  511. icon={<EditIcon />}
  512. text={Locale.Mask.Item.Edit}
  513. onClick={() => setEditingMaskId(m.id)}
  514. />
  515. )}
  516. {!m.builtin && (
  517. <IconButton
  518. icon={<DeleteIcon />}
  519. text={Locale.Mask.Item.Delete}
  520. onClick={async () => {
  521. if (await showConfirm(Locale.Mask.Item.DeleteConfirm)) {
  522. maskStore.delete(m.id);
  523. }
  524. }}
  525. />
  526. )}
  527. </div>
  528. </div>
  529. ))}
  530. </div>
  531. </div>
  532. </div>
  533. {editingMask && (
  534. <div className="modal-mask">
  535. <Modal
  536. title={Locale.Mask.EditModal.Title(editingMask?.builtin)}
  537. onClose={closeMaskModal}
  538. actions={[
  539. <IconButton
  540. icon={<DownloadIcon />}
  541. text={Locale.Mask.EditModal.Download}
  542. key="export"
  543. bordered
  544. onClick={() =>
  545. downloadAs(
  546. JSON.stringify(editingMask),
  547. `${editingMask.name}.json`,
  548. )
  549. }
  550. />,
  551. <IconButton
  552. key="copy"
  553. icon={<CopyIcon />}
  554. bordered
  555. text={Locale.Mask.EditModal.Clone}
  556. onClick={() => {
  557. navigate(Path.Masks);
  558. maskStore.create(editingMask);
  559. setEditingMaskId(undefined);
  560. }}
  561. />,
  562. ]}
  563. >
  564. <MaskConfig
  565. mask={editingMask}
  566. updateMask={(updater) =>
  567. maskStore.update(editingMaskId!, updater)
  568. }
  569. readonly={editingMask.builtin}
  570. />
  571. </Modal>
  572. </div>
  573. )}
  574. </ErrorBoundary>
  575. );
  576. }