Files

38 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2026-10-06 15:58:02 +02:00
// @ts-check
/**
* Files without the local program: when Kokkoja is opened from a web
* site, an image file comes from the browser's own file chooser, and
* anything to be saved is a download.
*/
/**
* Let the user choose an image file.
* @returns {Promise<File | null>} Null if none was chosen.
*/
export function pickImageFile() {
return new Promise((resolve) => {
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = 'image/*';
picker.addEventListener('change', () => resolve(picker.files?.[0] ?? null));
picker.addEventListener('cancel', () => resolve(null));
picker.click();
});
}
/**
* Give the user a file, through the browser's downloads.
* @param {string} name
* @param {Blob} content
*/
export function download(name, content) {
const address = URL.createObjectURL(content);
const link = document.createElement('a');
link.href = address;
link.download = name;
document.body.append(link);
link.click();
link.remove();
// The browser has begun the download; the address can go a moment later.
setTimeout(() => URL.revokeObjectURL(address), 10000);
}