exporter.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. /* eslint-disable @next/next/no-img-element */
  2. import { ChatMessage, ModelType, useAppConfig, useChatStore } from "../store";
  3. import Locale from "../locales";
  4. import styles from "./exporter.module.scss";
  5. import {
  6. List,
  7. ListItem,
  8. Modal,
  9. Select,
  10. showImageModal,
  11. showModal,
  12. showToast,
  13. } from "./ui-lib";
  14. import { IconButton } from "./button";
  15. import {
  16. copyToClipboard,
  17. downloadAs,
  18. getMessageImages,
  19. useMobileScreen,
  20. } from "../utils";
  21. import CopyIcon from "../icons/copy.svg";
  22. import LoadingIcon from "../icons/three-dots.svg";
  23. import ChatGptIcon from "../icons/chatgpt.png";
  24. import ShareIcon from "../icons/share.svg";
  25. import BotIcon from "../icons/bot.png";
  26. import DownloadIcon from "../icons/download.svg";
  27. import { useEffect, useMemo, useRef, useState } from "react";
  28. import { MessageSelector, useMessageSelector } from "./message-selector";
  29. import { Avatar } from "./emoji";
  30. import dynamic from "next/dynamic";
  31. import NextImage from "next/image";
  32. import { toBlob, toPng } from "html-to-image";
  33. import { DEFAULT_MASK_AVATAR } from "../store/mask";
  34. import { prettyObject } from "../utils/format";
  35. import { EXPORT_MESSAGE_CLASS_NAME } from "../constant";
  36. import { getClientConfig } from "../config/client";
  37. import { type ClientApi, getClientApi } from "../client/api";
  38. import { getMessageTextContent } from "../utils";
  39. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  40. loading: () => <LoadingIcon />,
  41. });
  42. export function ExportMessageModal(props: { onClose: () => void }) {
  43. return (
  44. <div className="modal-mask">
  45. <Modal
  46. title={Locale.Export.Title}
  47. onClose={props.onClose}
  48. footer={
  49. <div
  50. style={{
  51. width: "100%",
  52. textAlign: "center",
  53. fontSize: 14,
  54. opacity: 0.5,
  55. }}
  56. >
  57. {Locale.Exporter.Description.Title}
  58. </div>
  59. }
  60. >
  61. <div style={{ minHeight: "40vh" }}>
  62. <MessageExporter />
  63. </div>
  64. </Modal>
  65. </div>
  66. );
  67. }
  68. function useSteps(
  69. steps: Array<{
  70. name: string;
  71. value: string;
  72. }>,
  73. ) {
  74. const stepCount = steps.length;
  75. const [currentStepIndex, setCurrentStepIndex] = useState(0);
  76. const nextStep = () =>
  77. setCurrentStepIndex((currentStepIndex + 1) % stepCount);
  78. const prevStep = () =>
  79. setCurrentStepIndex((currentStepIndex - 1 + stepCount) % stepCount);
  80. return {
  81. currentStepIndex,
  82. setCurrentStepIndex,
  83. nextStep,
  84. prevStep,
  85. currentStep: steps[currentStepIndex],
  86. };
  87. }
  88. function Steps<
  89. T extends {
  90. name: string;
  91. value: string;
  92. }[],
  93. >(props: { steps: T; onStepChange?: (index: number) => void; index: number }) {
  94. const steps = props.steps;
  95. const stepCount = steps.length;
  96. return (
  97. <div className={styles["steps"]}>
  98. <div className={styles["steps-progress"]}>
  99. <div
  100. className={styles["steps-progress-inner"]}
  101. style={{
  102. width: `${((props.index + 1) / stepCount) * 100}%`,
  103. }}
  104. ></div>
  105. </div>
  106. <div className={styles["steps-inner"]}>
  107. {steps.map((step, i) => {
  108. return (
  109. <div
  110. key={i}
  111. className={`${styles["step"]} ${
  112. styles[i <= props.index ? "step-finished" : ""]
  113. } ${i === props.index && styles["step-current"]} clickable`}
  114. onClick={() => {
  115. props.onStepChange?.(i);
  116. }}
  117. role="button"
  118. >
  119. <span className={styles["step-index"]}>{i + 1}</span>
  120. <span className={styles["step-name"]}>{step.name}</span>
  121. </div>
  122. );
  123. })}
  124. </div>
  125. </div>
  126. );
  127. }
  128. export function MessageExporter() {
  129. const steps = [
  130. {
  131. name: Locale.Export.Steps.Select,
  132. value: "select",
  133. },
  134. {
  135. name: Locale.Export.Steps.Preview,
  136. value: "preview",
  137. },
  138. ];
  139. const { currentStep, setCurrentStepIndex, currentStepIndex } =
  140. useSteps(steps);
  141. const formats = ["text", "image", "json"] as const;
  142. type ExportFormat = (typeof formats)[number];
  143. const [exportConfig, setExportConfig] = useState({
  144. format: "image" as ExportFormat,
  145. includeContext: true,
  146. });
  147. function updateExportConfig(updater: (config: typeof exportConfig) => void) {
  148. const config = { ...exportConfig };
  149. updater(config);
  150. setExportConfig(config);
  151. }
  152. const chatStore = useChatStore();
  153. const session = chatStore.currentSession();
  154. const { selection, updateSelection } = useMessageSelector();
  155. const selectedMessages = useMemo(() => {
  156. const ret: ChatMessage[] = [];
  157. if (exportConfig.includeContext) {
  158. ret.push(...session.mask.context);
  159. }
  160. ret.push(...session.messages.filter((m) => selection.has(m.id)));
  161. return ret;
  162. }, [
  163. exportConfig.includeContext,
  164. session.messages,
  165. session.mask.context,
  166. selection,
  167. ]);
  168. function preview() {
  169. if (exportConfig.format === "text") {
  170. return (
  171. <MarkdownPreviewer messages={selectedMessages} topic={session.topic} />
  172. );
  173. } else if (exportConfig.format === "json") {
  174. return (
  175. <JsonPreviewer messages={selectedMessages} topic={session.topic} />
  176. );
  177. } else {
  178. return (
  179. <ImagePreviewer messages={selectedMessages} topic={session.topic} />
  180. );
  181. }
  182. }
  183. return (
  184. <>
  185. <Steps
  186. steps={steps}
  187. index={currentStepIndex}
  188. onStepChange={setCurrentStepIndex}
  189. />
  190. <div
  191. className={styles["message-exporter-body"]}
  192. style={currentStep.value !== "select" ? { display: "none" } : {}}
  193. >
  194. <List>
  195. <ListItem
  196. title={Locale.Export.Format.Title}
  197. subTitle={Locale.Export.Format.SubTitle}
  198. >
  199. <Select
  200. value={exportConfig.format}
  201. onChange={(e) =>
  202. updateExportConfig(
  203. (config) =>
  204. (config.format = e.currentTarget.value as ExportFormat),
  205. )
  206. }
  207. >
  208. {formats.map((f) => (
  209. <option key={f} value={f}>
  210. {f}
  211. </option>
  212. ))}
  213. </Select>
  214. </ListItem>
  215. <ListItem
  216. title={Locale.Export.IncludeContext.Title}
  217. subTitle={Locale.Export.IncludeContext.SubTitle}
  218. >
  219. <input
  220. type="checkbox"
  221. checked={exportConfig.includeContext}
  222. onChange={(e) => {
  223. updateExportConfig(
  224. (config) => (config.includeContext = e.currentTarget.checked),
  225. );
  226. }}
  227. ></input>
  228. </ListItem>
  229. </List>
  230. <MessageSelector
  231. selection={selection}
  232. updateSelection={updateSelection}
  233. defaultSelectAll
  234. />
  235. </div>
  236. {currentStep.value === "preview" && (
  237. <div className={styles["message-exporter-body"]}>{preview()}</div>
  238. )}
  239. </>
  240. );
  241. }
  242. export function RenderExport(props: {
  243. messages: ChatMessage[];
  244. onRender: (messages: ChatMessage[]) => void;
  245. }) {
  246. const domRef = useRef<HTMLDivElement>(null);
  247. useEffect(() => {
  248. if (!domRef.current) return;
  249. const dom = domRef.current;
  250. const messages = Array.from(
  251. dom.getElementsByClassName(EXPORT_MESSAGE_CLASS_NAME),
  252. );
  253. if (messages.length !== props.messages.length) {
  254. return;
  255. }
  256. const renderMsgs = messages.map((v, i) => {
  257. const [role, _] = v.id.split(":");
  258. return {
  259. id: i.toString(),
  260. role: role as any,
  261. content: role === "user" ? v.textContent ?? "" : v.innerHTML,
  262. date: "",
  263. };
  264. });
  265. props.onRender(renderMsgs);
  266. // eslint-disable-next-line react-hooks/exhaustive-deps
  267. }, []);
  268. return (
  269. <div ref={domRef}>
  270. {props.messages.map((m, i) => (
  271. <div
  272. key={i}
  273. id={`${m.role}:${i}`}
  274. className={EXPORT_MESSAGE_CLASS_NAME}
  275. >
  276. <Markdown content={getMessageTextContent(m)} defaultShow />
  277. </div>
  278. ))}
  279. </div>
  280. );
  281. }
  282. export function PreviewActions(props: {
  283. download: () => void;
  284. copy: () => void;
  285. showCopy?: boolean;
  286. messages?: ChatMessage[];
  287. }) {
  288. const [loading, setLoading] = useState(false);
  289. const [shouldExport, setShouldExport] = useState(false);
  290. const config = useAppConfig();
  291. const onRenderMsgs = (msgs: ChatMessage[]) => {
  292. setShouldExport(false);
  293. const api: ClientApi = getClientApi(config.modelConfig.providerName);
  294. api
  295. .share(msgs)
  296. .then((res) => {
  297. if (!res) return;
  298. showModal({
  299. title: Locale.Export.Share,
  300. children: [
  301. <input
  302. type="text"
  303. value={res}
  304. key="input"
  305. style={{
  306. width: "100%",
  307. maxWidth: "unset",
  308. }}
  309. readOnly
  310. onClick={(e) => e.currentTarget.select()}
  311. ></input>,
  312. ],
  313. actions: [
  314. <IconButton
  315. icon={<CopyIcon />}
  316. text={Locale.Chat.Actions.Copy}
  317. key="copy"
  318. onClick={() => copyToClipboard(res)}
  319. />,
  320. ],
  321. });
  322. setTimeout(() => {
  323. window.open(res, "_blank");
  324. }, 800);
  325. })
  326. .catch((e) => {
  327. console.error("[Share]", e);
  328. showToast(prettyObject(e));
  329. })
  330. .finally(() => setLoading(false));
  331. };
  332. const share = async () => {
  333. if (props.messages?.length) {
  334. setLoading(true);
  335. setShouldExport(true);
  336. }
  337. };
  338. return (
  339. <>
  340. <div className={styles["preview-actions"]}>
  341. {props.showCopy && (
  342. <IconButton
  343. text={Locale.Export.Copy}
  344. bordered
  345. shadow
  346. icon={<CopyIcon />}
  347. onClick={props.copy}
  348. ></IconButton>
  349. )}
  350. <IconButton
  351. text={Locale.Export.Download}
  352. bordered
  353. shadow
  354. icon={<DownloadIcon />}
  355. onClick={props.download}
  356. ></IconButton>
  357. <IconButton
  358. text={Locale.Export.Share}
  359. bordered
  360. shadow
  361. icon={loading ? <LoadingIcon /> : <ShareIcon />}
  362. onClick={share}
  363. ></IconButton>
  364. </div>
  365. <div
  366. style={{
  367. position: "fixed",
  368. right: "200vw",
  369. pointerEvents: "none",
  370. }}
  371. >
  372. {shouldExport && (
  373. <RenderExport
  374. messages={props.messages ?? []}
  375. onRender={onRenderMsgs}
  376. />
  377. )}
  378. </div>
  379. </>
  380. );
  381. }
  382. function ExportAvatar(props: { avatar: string }) {
  383. if (props.avatar === DEFAULT_MASK_AVATAR) {
  384. return (
  385. <img
  386. src={BotIcon.src}
  387. width={30}
  388. height={30}
  389. alt="bot"
  390. className="user-avatar"
  391. />
  392. );
  393. }
  394. return <Avatar avatar={props.avatar} />;
  395. }
  396. export function ImagePreviewer(props: {
  397. messages: ChatMessage[];
  398. topic: string;
  399. }) {
  400. const chatStore = useChatStore();
  401. const session = chatStore.currentSession();
  402. const mask = session.mask;
  403. const config = useAppConfig();
  404. const previewRef = useRef<HTMLDivElement>(null);
  405. const copy = () => {
  406. showToast(Locale.Export.Image.Toast);
  407. const dom = previewRef.current;
  408. if (!dom) return;
  409. toBlob(dom).then((blob) => {
  410. if (!blob) return;
  411. try {
  412. navigator.clipboard
  413. .write([
  414. new ClipboardItem({
  415. "image/png": blob,
  416. }),
  417. ])
  418. .then(() => {
  419. showToast(Locale.Copy.Success);
  420. refreshPreview();
  421. });
  422. } catch (e) {
  423. console.error("[Copy Image] ", e);
  424. showToast(Locale.Copy.Failed);
  425. }
  426. });
  427. };
  428. const isMobile = useMobileScreen();
  429. const download = async () => {
  430. showToast(Locale.Export.Image.Toast);
  431. const dom = previewRef.current;
  432. if (!dom) return;
  433. const isApp = getClientConfig()?.isApp;
  434. try {
  435. const blob = await toPng(dom);
  436. if (!blob) return;
  437. if (isMobile || (isApp && window.__TAURI__)) {
  438. if (isApp && window.__TAURI__) {
  439. const result = await window.__TAURI__.dialog.save({
  440. defaultPath: `${props.topic}.png`,
  441. filters: [
  442. {
  443. name: "PNG Files",
  444. extensions: ["png"],
  445. },
  446. {
  447. name: "All Files",
  448. extensions: ["*"],
  449. },
  450. ],
  451. });
  452. if (result !== null) {
  453. const response = await fetch(blob);
  454. const buffer = await response.arrayBuffer();
  455. const uint8Array = new Uint8Array(buffer);
  456. await window.__TAURI__.fs.writeBinaryFile(result, uint8Array);
  457. showToast(Locale.Download.Success);
  458. } else {
  459. showToast(Locale.Download.Failed);
  460. }
  461. } else {
  462. showImageModal(blob);
  463. }
  464. } else {
  465. const link = document.createElement("a");
  466. link.download = `${props.topic}.png`;
  467. link.href = blob;
  468. link.click();
  469. refreshPreview();
  470. }
  471. } catch (error) {
  472. showToast(Locale.Download.Failed);
  473. }
  474. };
  475. const refreshPreview = () => {
  476. const dom = previewRef.current;
  477. if (dom) {
  478. dom.innerHTML = dom.innerHTML; // Refresh the content of the preview by resetting its HTML for fix a bug glitching
  479. }
  480. };
  481. return (
  482. <div className={styles["image-previewer"]}>
  483. <PreviewActions
  484. copy={copy}
  485. download={download}
  486. showCopy={!isMobile}
  487. messages={props.messages}
  488. />
  489. <div
  490. className={`${styles["preview-body"]} ${styles["default-theme"]}`}
  491. ref={previewRef}
  492. >
  493. <div className={styles["chat-info"]}>
  494. <div className={styles["logo"] + " no-dark"}>
  495. <NextImage
  496. src={ChatGptIcon.src}
  497. alt="logo"
  498. width={50}
  499. height={50}
  500. />
  501. </div>
  502. <div>
  503. <div className={styles["main-title"]}>NextChat</div>
  504. <div className={styles["sub-title"]}>
  505. github.com/ChatGPTNextWeb/ChatGPT-Next-Web
  506. </div>
  507. <div className={styles["icons"]}>
  508. <ExportAvatar avatar={config.avatar} />
  509. <span className={styles["icon-space"]}>&</span>
  510. <ExportAvatar avatar={mask.avatar} />
  511. </div>
  512. </div>
  513. <div>
  514. <div className={styles["chat-info-item"]}>
  515. {Locale.Exporter.Model}: {mask.modelConfig.model}
  516. </div>
  517. <div className={styles["chat-info-item"]}>
  518. {Locale.Exporter.Messages}: {props.messages.length}
  519. </div>
  520. <div className={styles["chat-info-item"]}>
  521. {Locale.Exporter.Topic}: {session.topic}
  522. </div>
  523. <div className={styles["chat-info-item"]}>
  524. {Locale.Exporter.Time}:{" "}
  525. {new Date(
  526. props.messages.at(-1)?.date ?? Date.now(),
  527. ).toLocaleString()}
  528. </div>
  529. </div>
  530. </div>
  531. {props.messages.map((m, i) => {
  532. return (
  533. <div
  534. className={styles["message"] + " " + styles["message-" + m.role]}
  535. key={i}
  536. >
  537. <div className={styles["avatar"]}>
  538. <ExportAvatar
  539. avatar={m.role === "user" ? config.avatar : mask.avatar}
  540. />
  541. </div>
  542. <div className={styles["body"]}>
  543. <Markdown
  544. content={getMessageTextContent(m)}
  545. fontSize={config.fontSize}
  546. fontFamily={config.fontFamily}
  547. defaultShow
  548. />
  549. {getMessageImages(m).length == 1 && (
  550. <img
  551. key={i}
  552. src={getMessageImages(m)[0]}
  553. alt="message"
  554. className={styles["message-image"]}
  555. />
  556. )}
  557. {getMessageImages(m).length > 1 && (
  558. <div
  559. className={styles["message-images"]}
  560. style={
  561. {
  562. "--image-count": getMessageImages(m).length,
  563. } as React.CSSProperties
  564. }
  565. >
  566. {getMessageImages(m).map((src, i) => (
  567. <img
  568. key={i}
  569. src={src}
  570. alt="message"
  571. className={styles["message-image-multi"]}
  572. />
  573. ))}
  574. </div>
  575. )}
  576. </div>
  577. </div>
  578. );
  579. })}
  580. </div>
  581. </div>
  582. );
  583. }
  584. export function MarkdownPreviewer(props: {
  585. messages: ChatMessage[];
  586. topic: string;
  587. }) {
  588. const mdText =
  589. `# ${props.topic}\n\n` +
  590. props.messages
  591. .map((m) => {
  592. return m.role === "user"
  593. ? `## ${Locale.Export.MessageFromYou}:\n${getMessageTextContent(m)}`
  594. : `## ${Locale.Export.MessageFromChatGPT}:\n${getMessageTextContent(
  595. m,
  596. ).trim()}`;
  597. })
  598. .join("\n\n");
  599. const copy = () => {
  600. copyToClipboard(mdText);
  601. };
  602. const download = () => {
  603. downloadAs(mdText, `${props.topic}.md`);
  604. };
  605. return (
  606. <>
  607. <PreviewActions
  608. copy={copy}
  609. download={download}
  610. showCopy={true}
  611. messages={props.messages}
  612. />
  613. <div className="markdown-body">
  614. <pre className={styles["export-content"]}>{mdText}</pre>
  615. </div>
  616. </>
  617. );
  618. }
  619. export function JsonPreviewer(props: {
  620. messages: ChatMessage[];
  621. topic: string;
  622. }) {
  623. const msgs = {
  624. messages: [
  625. {
  626. role: "system",
  627. content: `${Locale.FineTuned.Sysmessage} ${props.topic}`,
  628. },
  629. ...props.messages.map((m) => ({
  630. role: m.role,
  631. content: m.content,
  632. })),
  633. ],
  634. };
  635. const mdText = "```json\n" + JSON.stringify(msgs, null, 2) + "\n```";
  636. const minifiedJson = JSON.stringify(msgs);
  637. const copy = () => {
  638. copyToClipboard(minifiedJson);
  639. };
  640. const download = () => {
  641. downloadAs(JSON.stringify(msgs), `${props.topic}.json`);
  642. };
  643. return (
  644. <>
  645. <PreviewActions
  646. copy={copy}
  647. download={download}
  648. showCopy={false}
  649. messages={props.messages}
  650. />
  651. <div className="markdown-body" onClick={copy}>
  652. <Markdown content={mdText} />
  653. </div>
  654. </>
  655. );
  656. }