Files
kiss-translator/src/views/Options/DownloadButton.js

38 lines
1.0 KiB
JavaScript
Raw Normal View History

2023-10-26 23:55:05 +08:00
import FileDownloadIcon from "@mui/icons-material/FileDownload";
2024-04-16 16:29:59 +08:00
import LoadingButton from "@mui/lab/LoadingButton";
import { useState } from "react";
import { kissLog } from "../../libs/log";
2023-10-26 23:55:05 +08:00
2024-04-16 16:29:59 +08:00
export default function DownloadButton({ handleData, text, fileName }) {
const [loading, setLoading] = useState(false);
const handleClick = async (e) => {
2023-10-26 23:55:05 +08:00
e.preventDefault();
2024-04-16 16:29:59 +08:00
try {
setLoading(true);
const data = await handleData();
2023-10-26 23:55:05 +08:00
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", fileName || `${Date.now()}.json`);
document.body.appendChild(link);
link.click();
link.remove();
2024-04-16 16:29:59 +08:00
} catch (err) {
kissLog(err, "download");
} finally {
setLoading(false);
2023-10-26 23:55:05 +08:00
}
};
return (
2024-04-16 16:29:59 +08:00
<LoadingButton
2023-10-26 23:55:05 +08:00
size="small"
variant="outlined"
onClick={handleClick}
2024-04-16 16:29:59 +08:00
loading={loading}
2023-10-26 23:55:05 +08:00
startIcon={<FileDownloadIcon />}
>
{text}
2024-04-16 16:29:59 +08:00
</LoadingButton>
2023-10-26 23:55:05 +08:00
);
}