import { useState } from "react";
import { JoyDoc } from "@joyfill/components";
function MyForm() {
const [document, setDocument] = useState(initialDocument);
const handleUploadAsync = async (params, fileUploads) => {
console.log("onUploadAsync: ", params, fileUploads);
const resultPromises = await fileUploads.map(async (fileUpload) => {
console.log("files uploaded");
const dataUri = await getDataUriForFileUpload(fileUpload);
return uploadFileAsync(params.identifier, dataUri);
});
return Promise.all(resultPromises)
.then((responses) => {
const finalResponse = Array.isArray(responses[0])
? responses[0]
: responses;
return finalResponse;
})
.catch((error) => {
if (error) return;
});
};
const handleChange = (changelogs, updatedDoc) => {
console.log("Document changed:", changelogs);
// Process each changelog
changelogs.forEach((changelog) => {
if (changelog.target === "field.update") {
console.log("Field updated:", changelog.fieldId);
console.log("Multi upload:", changelog.multi);
// Check if this was a table field upload
if (changelog.rowId && changelog.columnId) {
console.log("Table field upload:", {
fieldId: changelog.fieldId,
rowId: changelog.rowId,
columnId: changelog.columnId,
});
} else if (changelog.multi === true) {
console.log(
"Multiple images uploaded to normal field:",
changelog.fieldId
);
}
}
});
// Update document state
setDocument(updatedDoc);
};
return (
<JoyDoc
doc={document}
onChange={handleChange}
onUploadAsync={handleUploadAsync}
/>
);
}
// Helper functions
const getDataUriForFileUpload = async (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
};
const uploadFileAsync = async (identifier, dataUri, tableContext = null) => {
const uploadData = {
identifier,
dataUri,
...(tableContext && {
rowId: tableContext.rowId,
columnId: tableContext.columnId,
}),
};
const response = await fetch("/api/upload", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(uploadData),
});
const result = await response.json();
return {
_id: `upload-${Date.now()}`,
url: result.url,
fileName: result.fileName,
filePath: result.filePath,
};
};