mask.tsx 21 KB

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