Files
ShellBook/apps/web/src/ArtifactDownload.tsx
T

84 lines
2.3 KiB
TypeScript

import { useRef } from "react";
import type { DownloadState } from "./events";
export function ArtifactDownload({
name,
url,
sensitive,
state,
onState,
}: {
name: string;
url: string;
sensitive: boolean;
state?: DownloadState;
onState(state: DownloadState): void;
}) {
const busy = useRef(false);
const disabled =
state === "downloading" ||
state === "unavailable" ||
(sensitive && !!state);
async function download() {
if (busy.current || disabled) return;
busy.current = true;
onState("downloading");
try {
// A single GET both retrieves the bytes and detects expired/consumed files.
const response = await fetch(url, {
credentials: "same-origin",
cache: "no-store",
});
if (response.status === 410) {
onState("unavailable");
return;
}
if (!response.ok) throw new Error(`Download failed (${response.status})`);
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = objectUrl;
link.download = name;
document.body.append(link);
link.click();
link.remove();
// Give the browser time to start saving before releasing the blob.
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
onState("downloaded");
} catch {
onState("error");
} finally {
busy.current = false;
}
}
return (
<span className="artifact">
<a
href={disabled ? undefined : url}
role="link"
aria-disabled={disabled}
tabIndex={disabled ? -1 : 0}
onClick={(event) => {
event.preventDefault();
void download();
}}
download={name}
>
↓ {name}
</a>
{sensitive && <span className="badge">sensitive · one download</span>}
{state === "downloaded" && sensitive && (
<small> Downloaded / consumed</small>
)}
{state === "downloading" && <small> Downloading…</small>}
{state === "unavailable" && <small> no longer available</small>}
{state === "error" && (
<small role="alert">
{sensitive
? "Download failed; one-shot download may have been consumed."
: "Download failed. Try again."}
</small>
)}
</span>
);
}