mask.tsx 21 KB

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