web/download: support downloading and sharing raw files

This commit is contained in:
wukko
2024-09-09 02:30:03 +06:00
parent b1f41cae41
commit 853bc26587
5 changed files with 120 additions and 50 deletions

View File

@@ -8,23 +8,47 @@ import { t } from "$lib/i18n/translations";
import { createDialog } from "$lib/dialogs";
import type { DialogInfo } from "$lib/types/dialog";
export const openSavingDialog = (url: string, body: string | void) => {
const openSavingDialog = ({ url, file, body }: { url?: string, file?: File, body?: string }) => {
const dialogData: DialogInfo = {
type: "saving",
id: "saving",
url
file,
url,
}
if (body) dialogData.bodyText = body;
createDialog(dialogData)
}
export const openFile = async (file: File) => {
const a = document.createElement("a");
const url = URL.createObjectURL(file);
a.href = url;
a.download = file.name;
a.click();
URL.revokeObjectURL(url);
}
export const shareFile = async (file: File) => {
return await navigator?.share({
files: [
new File([file], file.name, {
type: file.type,
}),
],
});
}
export const openURL = (url: string) => {
const open = window.open(url, "_blank");
/* if new tab got blocked by user agent, show a saving dialog */
if (!open) {
return openSavingDialog(url, get(t)("dialog.saving.blocked"));
return openSavingDialog({
url,
body: get(t)("dialog.saving.blocked")
});
}
}
@@ -36,7 +60,9 @@ export const copyURL = async (url: string) => {
return await navigator?.clipboard?.writeText(url);
}
export const downloadFile = (url: string) => {
export const downloadFile = ({ url, file }: { url?: string, file?: File }) => {
if (!url && !file) throw new Error("attempted to download void");
const pref = get(settings).save.savingMethod;
/*
@@ -50,18 +76,28 @@ export const downloadFile = (url: string) => {
*/
if (pref === "ask" || !navigator.userActivation.isActive) {
return openSavingDialog(url);
return openSavingDialog({ url, file });
}
try {
if (pref === "share" && device.supports.share) {
return shareURL(url);
} else if (pref === "download" && device.supports.directDownload) {
return openURL(url);
} else if (pref === "copy") {
return copyURL(url);
if (file) {
if (pref === "share" && device.supports.share) {
return shareFile(file);
} else if (pref === "download" && device.supports.directDownload) {
return openFile(file);
}
}
} catch {}
return openSavingDialog(url);
if (url) {
if (pref === "share" && device.supports.share) {
return shareURL(url);
} else if (pref === "download" && device.supports.directDownload) {
return openURL(url);
} else if (pref === "copy" && !file) {
return copyURL(url);
}
}
} catch { /* catch & ignore */ }
return openSavingDialog({ url, file });
}

View File

@@ -40,8 +40,9 @@ type PickerDialog = Dialog & {
type SavingDialog = Dialog & {
type: "saving",
url: string,
bodyText?: string,
url?: string,
file?: File,
};
export type DialogInfo = SmallDialog | PickerDialog | SavingDialog;