function dataInput({
value = [],
initialValue = undefined,
accept = "",
delimiter = ",",
format = "auto",
label
} = {}) {
if (initialValue !== undefined && value.length === 0) {
value = initialValue;
}
const processFile = (data) => {
if (format === "auto") {
try {
return loadJSON(data, delimiter);
} catch {
console.log("Failed with json");
}
try {
return loadMongoExport(data);
} catch {
console.log("Failed with MongoExport");
}
try {
return loadCSVAutoType(data, delimiter);
} catch {
console.log("Failed with CSV AutoType");
}
try {
return loadCSV(data);
} catch {
console.log("Failed with CSV");
}
return value;
} else {
switch (format.toUpperCase()) {
case "JSON":
try {
return loadJSON(data, delimiter);
} catch {
console.log("Failed with json");
return initialValue;
}
case "MONGOEXPORT":
try {
return loadMongoExport(data);
} catch {
console.log("Failed with MongoExport");
return value;
}
case "CSV":
try {
return loadCSVAutoType(data, delimiter);
} catch {
console.log("Failed with CSV AutoType");
return value;
}
case "CSVNOAUTO":
try {
return loadCSV(data);
} catch {
console.log("Failed with CSV");
return value;
}
}
}
};
const fileInput = htl.html`<input type="file" accept="${accept}">`;
let holder;
if (label) {
fileInput.style.display = "none";
const labelButton = htl.html`<button>${label}
</button>`;
holder = htl.html`<label>
${labelButton}
${fileInput}
</label>`;
labelButton.addEventListener("click", (evt) => {
evt.preventDefault();
fileInput.click();
});
} else {
holder = htl.html`${fileInput}`;
}
const form = htl.html`<form>
${holder}
<form>`;
async function parseFile() {
widget.setValue(
await Files.text(
fileInput.multiple ? fileInput.files : fileInput.files[0]
).then(processFile)
);
}
const widget = ReactiveWidget(form, { value });
fileInput.addEventListener("change", async (evt) => {
evt.preventDefault();
parseFile();
});
return form;
}