Skip to content

Instantly share code, notes, and snippets.

@stefanoverna
Created September 27, 2024 15:42
Show Gist options
  • Save stefanoverna/e2c135968b8251b22a21664b53725a64 to your computer and use it in GitHub Desktop.
Save stefanoverna/e2c135968b8251b22a21664b53725a64 to your computer and use it in GitHub Desktop.
import type { RenderFieldExtensionCtx } from "datocms-plugin-sdk";
import { Canvas } from "datocms-react-ui";
import { useEffect, useState } from "react";
type Props = {
ctx: RenderFieldExtensionCtx;
};
export default function Editor({ ctx }: Props) {
const key = JSON.stringify([ctx.item?.id, ctx.fieldPath]);
const [editorType, setEditorType] = useState<string>(
localStorage.getItem(key) || "a",
);
useEffect(() => {
const onStorageChange = () => {
setEditorType(localStorage.getItem(key) || "a");
};
window.addEventListener("storage", onStorageChange);
() => {
window.removeEventListener("storage", onStorageChange);
};
}, [key]);
return (
<Canvas ctx={ctx}>
<div
style={{
background: editorType === "a" ? "paleturquoise" : "palegoldenrod",
padding: 10,
}}
>
This is the editor {editorType.toUpperCase()}
</div>
</Canvas>
);
}
import { connect } from "datocms-plugin-sdk";
import "datocms-react-ui/styles.css";
import Editor from "./entrypoints/Editor";
import { render } from "./utils/render";
connect({
fieldDropdownActions(field, ctx) {
if (field.attributes.field_type !== "string") {
return [];
}
return [
{
id: "changeEditor",
label: "Editor A",
icon: "a",
parameters: { editorType: "a" },
},
{
id: "changeEditor",
label: "Editor B",
icon: "b",
parameters: { editorType: "b" },
},
];
},
async executeFieldDropdownAction(actionId, ctx) {
const key = JSON.stringify([ctx.item?.id, ctx.fieldPath]);
localStorage.setItem(key, ctx.parameters?.editorType as string);
},
overrideFieldExtensions(field, ctx) {
if (field.attributes.field_type !== "string") {
return undefined;
}
return {
editor: {
id: "foobar",
},
};
},
renderFieldExtension(fieldExtensionId, ctx) {
return render(<Editor ctx={ctx} />);
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment