Skip to content

Commit

Permalink
feat: Download image button is changed to be a legend when downloading
Browse files Browse the repository at this point in the history
  • Loading branch information
ptbrowne committed Nov 28, 2024
1 parent 688c8a6 commit fda9db9
Showing 1 changed file with 44 additions and 19 deletions.
63 changes: 44 additions & 19 deletions src/components/detail-page/download-image.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Trans } from "@lingui/macro";
import { Link as MUILink } from "@mui/material";
import { Box, Link as MUILink, Typography } from "@mui/material";
import html2canvas from "html2canvas";
import * as React from "react";

Expand All @@ -16,6 +16,10 @@ const getImageDataFromElement = async (elementId: string): Promise<string> => {
return canvas.toDataURL("image/png");
};

// helper to wait a frame
const nextFrame = () =>
new Promise((resolve) => requestAnimationFrame(resolve));

/**
* Used to download an image of a specific element or from an element
* that directly defines a way to get the image data.
Expand All @@ -32,30 +36,51 @@ export const DownloadImage = ({
elementId?: string;
getImageData?: () => Promise<string | undefined>;
}) => {
const [downloading, setDownloading] = React.useState(false);
const onDownload: React.MouseEventHandler = async (ev) => {
ev.preventDefault();
const imageData = elementId
? await getImageDataFromElement(elementId)
: await getImageData!();
setDownloading(true);
try {
await nextFrame();
const imageData = elementId
? await getImageDataFromElement(elementId)
: await getImageData!();

if (!imageData) {
return;
if (!imageData) {
return;
}
const a = document.createElement("a");
a.href = imageData;
a.download = fileName;
a.click();
} finally {
setDownloading(false);
}
const a = document.createElement("a");
a.href = imageData;
a.download = fileName;
a.click();
};

return (
<MUILink
variant="inline"
onClick={onDownload}
target="_blank"
rel="noopener noreferrer"
href="#"
>
<Trans id="image.download">Bild herunterladen</Trans>
</MUILink>
<Box>
{downloading ? null : (
<MUILink
variant="inline"
onClick={onDownload}
target="_blank"
rel="noopener noreferrer"
href="#"
>
<Trans id="image.download">Bild herunterladen</Trans>
</MUILink>
)}
{/* This text is shown only when the image is downloading, this is done through
a global class on body */}
{downloading ? (
<Typography variant="meta" sx={{ mt: 4 }}>
<Trans id="image.download.source">
Eidgenössische Elektrizitätskommission ElCom
</Trans>{" "}
-<Trans id="image.download.unit">Tarifvergleich in Rp./kWh</Trans>
</Typography>
) : null}
</Box>
);
};

0 comments on commit fda9db9

Please sign in to comment.