exporter.tsx 17 KB

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