Files

49 lines
3.2 KiB
JavaScript

// File selection stays inside the authenticated server scope. No vendor bundle
// is modified: both the File System Access API and hidden file inputs are bridged.
(() => {
"use strict";
const parts = location.pathname.split("/"), id = parts[parts.lastIndexOf("addons") + 1];
if (parent === window || new URLSearchParams(location.search).get("host") !== "parent") return;
const jobs = new Map(); let sequence = 0;
const request = (accept, intent = "choose") => new Promise((resolve, reject) => {
if (jobs.size) { reject(new DOMException("Selection already pending", "AbortError")); return; }
const requestId = `picker-${++sequence}`;
jobs.set(requestId, { resolve, reject });
parent.postMessage({ type: id + ":pick-request", requestId, accept: String(accept || "").slice(0, 2048), intent }, location.origin);
});
addEventListener("message", event => {
if (event.source !== parent || event.origin !== location.origin || event.data?.type !== id + ":pick-result") return;
const message = event.data, job = jobs.get(message.requestId); if (!job) return;
jobs.delete(message.requestId);
if (!Array.isArray(message.files)) { job.reject(new DOMException("Selection cancelled", "AbortError")); return; }
const files = message.files.filter(f => typeof f.name === "string" && f.bytes instanceof ArrayBuffer && f.bytes.byteLength <= 64 * 1024 * 1024)
.map(f => new File([f.bytes], f.name, { type: typeof f.mime === "string" ? f.mime : "" }));
if (!files.length) job.reject(new DOMException("No file selected", "AbortError")); else job.resolve(files);
});
const chooseInput = input => {
request(input.accept).then(files => {
const transfer = new DataTransfer(); for (const file of files) transfer.items.add(file);
input.files = transfer.files;
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
}).catch(() => input.dispatchEvent(new Event("cancel", { bubbles: true })));
};
const click = HTMLInputElement.prototype.click;
HTMLInputElement.prototype.click = function () { if (this.type === "file") return chooseInput(this); return click.call(this); };
if (HTMLInputElement.prototype.showPicker) {
const show = HTMLInputElement.prototype.showPicker;
HTMLInputElement.prototype.showPicker = function () { if (this.type === "file") return chooseInput(this); return show.call(this); };
}
addEventListener("click", event => { if (event.target instanceof HTMLInputElement && event.target.type === "file") { event.preventDefault(); event.stopImmediatePropagation(); chooseInput(event.target); } }, true);
window.showOpenFilePicker = async options => {
const accept = (options?.types || []).flatMap(t => Object.values(t.accept || {}).flat()).join(",");
const files = await request(accept);
return files.map(file => ({ kind: "file", name: file.name, getFile: async () => file, queryPermission: async () => "granted", requestPermission: async () => "granted" }));
};
addEventListener("keydown", event => {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "o") {
event.preventDefault(); event.stopImmediatePropagation(); request("", "open").catch(() => {});
}
}, true);
})();