Created
September 27, 2024 15:42
-
-
Save stefanoverna/e2c135968b8251b22a21664b53725a64 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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