From 7fa49ca3c1e4c9050fce6d96287efa23a416ac11 Mon Sep 17 00:00:00 2001 From: dakai Date: Wed, 19 Apr 2023 20:37:06 +0800 Subject: [PATCH] chat export to image --- app/components/chat.tsx | 74 +++++++++++++++++++++++++++++------------ 1 file changed, 53 insertions(+), 21 deletions(-) diff --git a/app/components/chat.tsx b/app/components/chat.tsx index 764139aef..ac34fd9bc 100644 --- a/app/components/chat.tsx +++ b/app/components/chat.tsx @@ -1,5 +1,6 @@ import { useDebounce, useDebouncedCallback } from "use-debounce"; import { memo, useState, useRef, useEffect, useLayoutEffect } from "react"; +import html2canvas from "html2canvas"; import SendWhiteIcon from "../icons/send-white.svg"; import BrainIcon from "../icons/brain.svg"; @@ -558,6 +559,35 @@ export function Chat(props: { ); }; + const exportToImage = () => { + if (divRef.current) { + //get the color style from a div by classname 'markdown-body' + const divElement = document.querySelector( + ".markdown-body", + ) as HTMLDivElement; + const color = window + .getComputedStyle(divElement) + .getPropertyValue("color"); + console.log(color); + if (color !== "rgb(36, 41, 47)") { + divRef.current.style.backgroundColor = "#1e1e1e"; + } + + divRef.current.style.padding = "10px 10px 0px 10px"; + html2canvas(divRef.current).then((canvas) => { + const imgData = canvas.toDataURL("image/png"); + const img = new Image(); + img.src = imgData; + const link = document.createElement("a"); + link.href = imgData; + link.download = "chat.png"; + link.click(); + }); + divRef.current.style.padding = "0px"; + divRef.current.style.backgroundColor = ""; + } + }; + const onDelete = (botMessageId: number) => { const userIndex = findLastUesrIndex(botMessageId); if (userIndex === null) return; @@ -639,6 +669,7 @@ export function Chat(props: { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + const divRef = useRef(null); return (
@@ -746,13 +777,6 @@ export function Chat(props: {
) : ( <> -
onDelete(message.id ?? i)} - > - {Locale.Chat.Actions.Delete} -
-
onDelete(message.id ?? i)} @@ -774,22 +798,30 @@ export function Chat(props: { > {Locale.Chat.Actions.Copy}
+
exportToImage()} + > + {"Image"} +
)} - onRightClick(e, message)} - onDoubleClickCapture={() => { - if (!isMobileScreen()) return; - setUserInput(message.content); - }} - fontSize={fontSize} - parentRef={scrollRef} - /> +
+ onRightClick(e, message)} + onDoubleClickCapture={() => { + if (!isMobileScreen()) return; + setUserInput(message.content); + }} + fontSize={fontSize} + parentRef={scrollRef} + /> +
{!isUser && !message.preview && (