53 lines
2.8 KiB
JavaScript
53 lines
2.8 KiB
JavaScript
// File sharing never falls back to sending a private artifact URL. Keep prepared
|
|
// files local to the owning button so a slow fetch can be shared on a fresh tap.
|
|
const prepared = new WeakMap();
|
|
const pending = new WeakSet();
|
|
|
|
export function canShareFiles(environment = globalThis) {
|
|
return typeof environment.navigator?.share === "function" &&
|
|
typeof environment.navigator?.canShare === "function" &&
|
|
typeof environment.File === "function";
|
|
}
|
|
|
|
export async function shareArtifactFile(resolved, artifact, owner, environment = globalThis) {
|
|
if (!resolved || !canShareFiles(environment)) return { state: "error", message: "File sharing is not supported in this browser. Use Open in browser to save the file." };
|
|
if (pending.has(owner)) return { state: "busy", message: "Preparing file…" };
|
|
pending.add(owner);
|
|
try {
|
|
let entry = prepared.get(owner);
|
|
if (!entry || entry.url !== resolved) {
|
|
const response = await environment.fetch(resolved, { credentials: "same-origin", redirect: "error" });
|
|
if (!response.ok) throw new Error(`Could not fetch the artifact (HTTP ${response.status}).`);
|
|
const blob = await response.blob();
|
|
const name = String(artifact?.name || new URL(resolved).pathname.split("/").pop() || "artifact")
|
|
.split(/[\\/]/).pop().replace(/[\x00-\x1f\x7f]/g, "_") || "artifact";
|
|
const file = new environment.File([blob], name, { type: blob.type || artifact?.content_type || "application/octet-stream" });
|
|
entry = { url: resolved, file };
|
|
if (!environment.navigator.canShare({ files: [file] })) {
|
|
return { state: "error", message: "This browser cannot share this file type. Use Open in browser to save the file." };
|
|
}
|
|
prepared.set(owner, entry);
|
|
}
|
|
if (owner.isConnected === false) {
|
|
prepared.delete(owner);
|
|
return { state: "canceled", message: "Sharing canceled." };
|
|
}
|
|
// Fetching may outlast the browser's transient activation. Do not attempt a
|
|
// doomed share or substitute a URL: the next tap uses the prepared file.
|
|
if (environment.navigator.userActivation?.isActive === false) {
|
|
return { state: "ready", message: "File ready. Tap Share again to choose where to send it." };
|
|
}
|
|
await environment.navigator.share({ files: [entry.file] });
|
|
prepared.delete(owner);
|
|
return { state: "shared", message: "File shared." };
|
|
} catch (error) {
|
|
if (error?.name === "AbortError") return { state: "canceled", message: "Sharing canceled." };
|
|
if (error?.name === "NotAllowedError" && prepared.has(owner)) {
|
|
return { state: "ready", message: "Sharing was blocked. Tap Share again, or use Open in browser to save the file." };
|
|
}
|
|
return { state: "error", message: "Could not share the file. Use Open in browser to save it, or try Share again." };
|
|
} finally {
|
|
pending.delete(owner);
|
|
}
|
|
}
|