on-codemerge
Version:
A WYSIWYG editor for on-codemerge is a user-friendly interface that allows users to edit and view their code in real time, exactly as it will appear in the final product
90 lines (89 loc) • 2.92 kB
JavaScript
var d = Object.defineProperty;
var c = (n, e, o) => e in n ? d(n, e, { enumerable: !0, configurable: !0, writable: !0, value: o }) : n[e] = o;
var a = (n, e, o) => c(n, typeof e != "symbol" ? e + "" : e, o);
import { defaultConfig as r } from "../config/UploadConfig.mjs";
import { createLink as w } from "../../../utils/helpers.mjs";
class m {
constructor(e = {}) {
a(this, "files", /* @__PURE__ */ new Map());
a(this, "config");
this.config = { ...r, ...e };
}
async uploadFile(e) {
var o;
if (e.size > (this.config.maxFileSize || r.maxFileSize))
throw new Error(`File size exceeds ${this.formatFileSize(this.config.maxFileSize)}`);
if (!this.isFileTypeAllowed(e))
throw new Error("File type not allowed");
return (o = this.config.endpoints) != null && o.upload && !this.config.useEmulation ? this.uploadToServer(e) : this.emulateUpload(e);
}
async downloadFile(e) {
var o;
if ((o = this.config.endpoints) != null && o.download && !this.config.useEmulation) {
await this.downloadFromServer(e);
return;
}
await this.emulateDownload(e);
}
async uploadToServer(e) {
const o = new FormData();
o.append("file", e);
const t = await fetch(this.config.endpoints.upload, {
method: "POST",
body: o
});
if (!t.ok)
throw new Error("Upload failed");
return {
id: (await t.json()).id,
name: e.name,
size: e.size,
type: e.type,
data: await e.arrayBuffer()
};
}
async downloadFromServer(e) {
var s;
const o = await fetch(`${this.config.endpoints.download}/${e}`);
if (!o.ok)
throw new Error("Download failed");
const t = await o.blob(), i = URL.createObjectURL(t), l = ((s = o.headers.get("content-disposition")) == null ? void 0 : s.split("filename=")[1]) || "download";
this.triggerDownload(i, l);
}
async emulateUpload(e) {
await new Promise((t) => setTimeout(t, 1e3));
const o = {
id: crypto.randomUUID(),
name: e.name,
size: e.size,
type: e.type,
data: await e.arrayBuffer()
};
return this.files.set(o.id, o), o;
}
async emulateDownload(e) {
const o = this.files.get(e);
if (!o)
throw new Error("File not found");
const t = new Blob([o.data], { type: o.type }), i = URL.createObjectURL(t);
this.triggerDownload(i, o.name);
}
triggerDownload(e, o) {
const t = w("", e);
t.download = o, document.body.appendChild(t), t.click(), document.body.removeChild(t), URL.revokeObjectURL(e);
}
isFileTypeAllowed(e) {
const o = this.config.allowedTypes || r.allowedTypes;
return o.includes("*/*") || o.includes(e.type);
}
formatFileSize(e) {
const o = ["B", "KB", "MB", "GB"];
let t = e, i = 0;
for (; t >= 1024 && i < o.length - 1; )
t /= 1024, i++;
return `${t.toFixed(1)} ${o[i]}`;
}
}
export {
m as FileUploader
};