exporter.tsx 15 KB

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