exporter.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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, ModelProvider } from "../constant";
  36. import { getClientConfig } from "../config/client";
  37. import { ClientApi } 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. var api: ClientApi;
  294. if (config.modelConfig.model.startsWith("gemini")) {
  295. api = new ClientApi(ModelProvider.GeminiPro);
  296. } else {
  297. api = new ClientApi(ModelProvider.GPT);
  298. }
  299. api
  300. .share(msgs)
  301. .then((res) => {
  302. if (!res) return;
  303. showModal({
  304. title: Locale.Export.Share,
  305. children: [
  306. <input
  307. type="text"
  308. value={res}
  309. key="input"
  310. style={{
  311. width: "100%",
  312. maxWidth: "unset",
  313. }}
  314. readOnly
  315. onClick={(e) => e.currentTarget.select()}
  316. ></input>,
  317. ],
  318. actions: [
  319. <IconButton
  320. icon={<CopyIcon />}
  321. text={Locale.Chat.Actions.Copy}
  322. key="copy"
  323. onClick={() => copyToClipboard(res)}
  324. />,
  325. ],
  326. });
  327. setTimeout(() => {
  328. window.open(res, "_blank");
  329. }, 800);
  330. })
  331. .catch((e) => {
  332. console.error("[Share]", e);
  333. showToast(prettyObject(e));
  334. })
  335. .finally(() => setLoading(false));
  336. };
  337. const share = async () => {
  338. if (props.messages?.length) {
  339. setLoading(true);
  340. setShouldExport(true);
  341. }
  342. };
  343. return (
  344. <>
  345. <div className={styles["preview-actions"]}>
  346. {props.showCopy && (
  347. <IconButton
  348. text={Locale.Export.Copy}
  349. bordered
  350. shadow
  351. icon={<CopyIcon />}
  352. onClick={props.copy}
  353. ></IconButton>
  354. )}
  355. <IconButton
  356. text={Locale.Export.Download}
  357. bordered
  358. shadow
  359. icon={<DownloadIcon />}
  360. onClick={props.download}
  361. ></IconButton>
  362. <IconButton
  363. text={Locale.Export.Share}
  364. bordered
  365. shadow
  366. icon={loading ? <LoadingIcon /> : <ShareIcon />}
  367. onClick={share}
  368. ></IconButton>
  369. </div>
  370. <div
  371. style={{
  372. position: "fixed",
  373. right: "200vw",
  374. pointerEvents: "none",
  375. }}
  376. >
  377. {shouldExport && (
  378. <RenderExport
  379. messages={props.messages ?? []}
  380. onRender={onRenderMsgs}
  381. />
  382. )}
  383. </div>
  384. </>
  385. );
  386. }
  387. function ExportAvatar(props: { avatar: string }) {
  388. if (props.avatar === DEFAULT_MASK_AVATAR) {
  389. return (
  390. <img
  391. src={BotIcon.src}
  392. width={30}
  393. height={30}
  394. alt="bot"
  395. className="user-avatar"
  396. />
  397. );
  398. }
  399. return <Avatar avatar={props.avatar} />;
  400. }
  401. export function ImagePreviewer(props: {
  402. messages: ChatMessage[];
  403. topic: string;
  404. }) {
  405. const chatStore = useChatStore();
  406. const session = chatStore.currentSession();
  407. const mask = session.mask;
  408. const config = useAppConfig();
  409. const previewRef = useRef<HTMLDivElement>(null);
  410. const copy = () => {
  411. showToast(Locale.Export.Image.Toast);
  412. const dom = previewRef.current;
  413. if (!dom) return;
  414. toBlob(dom).then((blob) => {
  415. if (!blob) return;
  416. try {
  417. navigator.clipboard
  418. .write([
  419. new ClipboardItem({
  420. "image/png": blob,
  421. }),
  422. ])
  423. .then(() => {
  424. showToast(Locale.Copy.Success);
  425. refreshPreview();
  426. });
  427. } catch (e) {
  428. console.error("[Copy Image] ", e);
  429. showToast(Locale.Copy.Failed);
  430. }
  431. });
  432. };
  433. const isMobile = useMobileScreen();
  434. const download = async () => {
  435. showToast(Locale.Export.Image.Toast);
  436. const dom = previewRef.current;
  437. if (!dom) return;
  438. const isApp = getClientConfig()?.isApp;
  439. try {
  440. const blob = await toPng(dom);
  441. if (!blob) return;
  442. if (isMobile || (isApp && window.__TAURI__)) {
  443. if (isApp && window.__TAURI__) {
  444. const result = await window.__TAURI__.dialog.save({
  445. defaultPath: `${props.topic}.png`,
  446. filters: [
  447. {
  448. name: "PNG Files",
  449. extensions: ["png"],
  450. },
  451. {
  452. name: "All Files",
  453. extensions: ["*"],
  454. },
  455. ],
  456. });
  457. if (result !== null) {
  458. const response = await fetch(blob);
  459. const buffer = await response.arrayBuffer();
  460. const uint8Array = new Uint8Array(buffer);
  461. await window.__TAURI__.fs.writeBinaryFile(result, uint8Array);
  462. showToast(Locale.Download.Success);
  463. } else {
  464. showToast(Locale.Download.Failed);
  465. }
  466. } else {
  467. showImageModal(blob);
  468. }
  469. } else {
  470. const link = document.createElement("a");
  471. link.download = `${props.topic}.png`;
  472. link.href = blob;
  473. link.click();
  474. refreshPreview();
  475. }
  476. } catch (error) {
  477. showToast(Locale.Download.Failed);
  478. }
  479. };
  480. const refreshPreview = () => {
  481. const dom = previewRef.current;
  482. if (dom) {
  483. dom.innerHTML = dom.innerHTML; // Refresh the content of the preview by resetting its HTML for fix a bug glitching
  484. }
  485. };
  486. return (
  487. <div className={styles["image-previewer"]}>
  488. <PreviewActions
  489. copy={copy}
  490. download={download}
  491. showCopy={!isMobile}
  492. messages={props.messages}
  493. />
  494. <div
  495. className={`${styles["preview-body"]} ${styles["default-theme"]}`}
  496. ref={previewRef}
  497. >
  498. <div className={styles["chat-info"]}>
  499. <div className={styles["logo"] + " no-dark"}>
  500. <NextImage
  501. src={ChatGptIcon.src}
  502. alt="logo"
  503. width={50}
  504. height={50}
  505. />
  506. </div>
  507. <div>
  508. <div className={styles["main-title"]}>NextChat</div>
  509. <div className={styles["sub-title"]}>
  510. github.com/Yidadaa/ChatGPT-Next-Web
  511. </div>
  512. <div className={styles["icons"]}>
  513. <ExportAvatar avatar={config.avatar} />
  514. <span className={styles["icon-space"]}>&</span>
  515. <ExportAvatar avatar={mask.avatar} />
  516. </div>
  517. </div>
  518. <div>
  519. <div className={styles["chat-info-item"]}>
  520. {Locale.Exporter.Model}: {mask.modelConfig.model}
  521. </div>
  522. <div className={styles["chat-info-item"]}>
  523. {Locale.Exporter.Messages}: {props.messages.length}
  524. </div>
  525. <div className={styles["chat-info-item"]}>
  526. {Locale.Exporter.Topic}: {session.topic}
  527. </div>
  528. <div className={styles["chat-info-item"]}>
  529. {Locale.Exporter.Time}:{" "}
  530. {new Date(
  531. props.messages.at(-1)?.date ?? Date.now(),
  532. ).toLocaleString()}
  533. </div>
  534. </div>
  535. </div>
  536. {props.messages.map((m, i) => {
  537. return (
  538. <div
  539. className={styles["message"] + " " + styles["message-" + m.role]}
  540. key={i}
  541. >
  542. <div className={styles["avatar"]}>
  543. <ExportAvatar
  544. avatar={m.role === "user" ? config.avatar : mask.avatar}
  545. />
  546. </div>
  547. <div className={styles["body"]}>
  548. <Markdown
  549. content={getMessageTextContent(m)}
  550. fontSize={config.fontSize}
  551. defaultShow
  552. />
  553. {getMessageImages(m).length == 1 && (
  554. <img
  555. key={i}
  556. src={getMessageImages(m)[0]}
  557. alt="message"
  558. className={styles["message-image"]}
  559. />
  560. )}
  561. {getMessageImages(m).length > 1 && (
  562. <div
  563. className={styles["message-images"]}
  564. style={
  565. {
  566. "--image-count": getMessageImages(m).length,
  567. } as React.CSSProperties
  568. }
  569. >
  570. {getMessageImages(m).map((src, i) => (
  571. <img
  572. key={i}
  573. src={src}
  574. alt="message"
  575. className={styles["message-image-multi"]}
  576. />
  577. ))}
  578. </div>
  579. )}
  580. </div>
  581. </div>
  582. );
  583. })}
  584. </div>
  585. </div>
  586. );
  587. }
  588. export function MarkdownPreviewer(props: {
  589. messages: ChatMessage[];
  590. topic: string;
  591. }) {
  592. const mdText =
  593. `# ${props.topic}\n\n` +
  594. props.messages
  595. .map((m) => {
  596. return m.role === "user"
  597. ? `## ${Locale.Export.MessageFromYou}:\n${getMessageTextContent(m)}`
  598. : `## ${Locale.Export.MessageFromChatGPT}:\n${getMessageTextContent(
  599. m,
  600. ).trim()}`;
  601. })
  602. .join("\n\n");
  603. const copy = () => {
  604. copyToClipboard(mdText);
  605. };
  606. const download = () => {
  607. downloadAs(mdText, `${props.topic}.md`);
  608. };
  609. return (
  610. <>
  611. <PreviewActions
  612. copy={copy}
  613. download={download}
  614. showCopy={true}
  615. messages={props.messages}
  616. />
  617. <div className="markdown-body">
  618. <pre className={styles["export-content"]}>{mdText}</pre>
  619. </div>
  620. </>
  621. );
  622. }
  623. export function JsonPreviewer(props: {
  624. messages: ChatMessage[];
  625. topic: string;
  626. }) {
  627. const msgs = {
  628. messages: [
  629. {
  630. role: "system",
  631. content: `${Locale.FineTuned.Sysmessage} ${props.topic}`,
  632. },
  633. ...props.messages.map((m) => ({
  634. role: m.role,
  635. content: m.content,
  636. })),
  637. ],
  638. };
  639. const mdText = "```json\n" + JSON.stringify(msgs, null, 2) + "\n```";
  640. const minifiedJson = JSON.stringify(msgs);
  641. const copy = () => {
  642. copyToClipboard(minifiedJson);
  643. };
  644. const download = () => {
  645. downloadAs(JSON.stringify(msgs), `${props.topic}.json`);
  646. };
  647. return (
  648. <>
  649. <PreviewActions
  650. copy={copy}
  651. download={download}
  652. showCopy={false}
  653. messages={props.messages}
  654. />
  655. <div className="markdown-body" onClick={copy}>
  656. <Markdown content={mdText} />
  657. </div>
  658. </>
  659. );
  660. }