useExportDashboardAsPNG.tsx
1 import html2canvas from "html2canvas"; 2 import { useRef } from "react"; 3 4 export const PoolsType = { 5 default: "default", 6 sprout: "sprout", 7 sap: "sapling", 8 ord: "orchard", 9 }; 10 11 /// This hook is use to handle the export of the dashboard chart 12 const useExportDashboardAsPNG = () => { 13 const divChartRef = useRef<HTMLDivElement>(null); 14 15 const handleSaveToPng = async (label: string) => { 16 try { 17 const canvas = await html2canvas(divChartRef.current!, { 18 scale: 3, // renders at 3x resolution 19 useCORS: true, 20 }); 21 22 const link = document.createElement("a"); 23 link.href = canvas.toDataURL("image/png"); 24 link.download = `${label}-chart.png`; 25 link.click(); 26 27 } catch (err) { 28 alert("Error exporting chart!"); 29 console.error("Error saving chart: ", err); 30 } 31 }; 32 33 return { divChartRef, handleSaveToPng }; 34 }; 35 36 const useExportDashboardAsPNGBackup = () => { 37 const divChartRef = useRef<HTMLDivElement>(null); 38 39 const handleSaveToPng = async ( 40 poolType: string, 41 poolData: 42 | Record<string, { timestamp: string; supply: number } | null> 43 | string, 44 toolType: string 45 ) => { 46 const poolQty = document.createTextNode(""); 47 48 if (typeof poolData != "string") { 49 if (poolType == PoolsType.sprout) { 50 poolQty.textContent = `${poolData[ 51 "sproutSupply" 52 ]?.supply.toLocaleString()} ZEC in Sprout Pool`; 53 } else if (poolType == PoolsType.ord) { 54 poolQty.textContent = `${poolData[ 55 "orchardSupply" 56 ]?.supply.toLocaleString()} ZEC in Orchard Pool`; 57 } else if (poolType == PoolsType.sap) { 58 poolQty.textContent = `${poolData[ 59 "saplingSupply" 60 ]?.supply.toLocaleString()} ZEC in Sapling Pool`; 61 } else { 62 poolQty.textContent = ""; 63 } 64 } 65 66 const span = document.createElement("span"); 67 span.style.color = "#eee"; 68 span.style.position = "absolute"; 69 span.style.top = "20px"; 70 span.style.paddingLeft = "24px"; 71 span.style.zIndex = "1000"; 72 span.appendChild(poolQty); 73 74 // if (divChartRef.current && toolType == "supply") { 75 // divChartRef.current.appendChild(span); 76 // } 77 78 try { 79 const canvas = await html2canvas(divChartRef.current!, { 80 scale: 3, // renders at 3x resolution 81 useCORS: true, 82 }); 83 84 const link = document.createElement("a"); 85 86 link.href = canvas.toDataURL("image/png"); 87 // if(toolType == 'supply') link.download = `zcash-${poolType}-pool-chart.png`; 88 // else link.download = `zcash-${poolType}-transaction-chart.png`; 89 link.download = `${poolType}-chart.png`; 90 link.click(); 91 92 // Clean up 93 // divChartRef.current?.removeChild(span); 94 } catch (err) { 95 console.error("Error saving chart: ", err); 96 } 97 }; 98 99 return { divChartRef, handleSaveToPng }; 100 }; 101 102 export default useExportDashboardAsPNG;