@oberoncms/plugin-uploadthing
Version:
An Puck component and OberonCMS plugin for embeding uploadthing images
75 lines (74 loc) • 2.32 kB
JavaScript
import { jsxs, Fragment, jsx } from "react/jsx-runtime";
import { FieldLabel } from "../node_modules/.pnpm/@measured_puck@0.18.0_@types_react@18.3.12_react-dom@18.3.1_react@18.3.1/node_modules/@measured/puck/dist/index.js";
import { useState, useEffect } from "react";
import { useOberonImages } from "@oberoncms/core/editor";
import { UploadDropzone } from "../uploadthing/components.js";
const useImages = (value, onChange) => {
const { images, loading, addImage } = useOberonImages();
const [imageKey, setImageKey] = useState(
(value == null ? void 0 : value.key) || ""
);
useEffect(() => {
if (!imageKey) {
return onChange(null);
}
onChange((images == null ? void 0 : images.find((image) => image.key === imageKey)) || null);
}, [images, imageKey, onChange]);
return {
images,
loading,
imageKey,
setImageKey,
addImage
};
};
const ImageField = ({
value,
onChange
}) => {
const { images, loading, imageKey, setImageKey, addImage } = useImages(
value,
onChange
);
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(FieldLabel, { label: "Image", children: /* @__PURE__ */ jsxs("select", { value: imageKey, onChange: (e) => setImageKey(e.target.value), children: [
/* @__PURE__ */ jsx("option", { value: "", children: loading ? "Loading Images" : "Select an image" }),
images == null ? void 0 : images.map(({ key, alt }) => /* @__PURE__ */ jsx("option", { value: key, children: alt }, key))
] }) }),
/* @__PURE__ */ jsx(
UploadDropzone,
{
endpoint: "singleImageUploader",
onClientUploadComplete: async (res) => {
if (!res[0]) {
return;
}
const {
key,
name,
size,
url,
serverData: { width, height }
} = res[0];
addImage({
key,
url,
alt: name,
size,
width,
height,
updatedAt: /* @__PURE__ */ new Date(),
updatedBy: "unknown"
});
setImageKey == null ? void 0 : setImageKey(key || "");
},
onUploadError: (error) => {
alert(`ERROR! ${error.message}`);
}
}
)
] });
};
export {
ImageField
};