Hello!
I’m trying to create new editTab plugin and are having trouble inserting new blocks onto the page. In digging through the context object, I see that there is context.designerState.editingContentModel?.allBlocks?.forEach which allows you to iterate over existing blocks and mutate them. However, I can’t figure out how to insert new blocks to the page. How would I do that?
Code stack you are integrating Builder with
NextJS/React
Hi Mike, you’d want to modify the content snapshot and make your modification then apply it back:
// mobx-state-tree is an external lib builder provide when initializing plugin
// make sure to mark it as external when building your plugin
import { applySnapshot} from 'mobx-state-tree'
const snapshot = context.designerState.editingContentModel;
// modify what you need on the snapshot, then
applySnapshot(context.designerState.editingContentModel, modifiedSnapshot)
You’ll have to forgive me that I’m not super familiar with mobx or the inner workings of the Builder.io context API.
How do I create the modified snapshot with the element(s) added?
Let’s imagine that my plugin just wants to add a new Text component every time the every time I click on a button. How would I fill in the middle of it?
(I know this is a contrived example, but just trying to use it to wrap my head around things)
import React from 'react';
import { applySnapshot} from 'mobx-state-tree';
import { ApplicationContext } from '@builder.io/app-context';
import { Builder } from '@builder.io/react';
function AddTextPlugin({context}: {context: ApplicationContext}) {
const handleClick = () => {
const snapshot = context.designerState.editingContentModel;
// I WANT TO ADD A BLOCK HERE. HOW DO I DO THAT?
applySnapshot(context.designerState.editingContentModel, snapshot);
}
return <button onClick={handleClick}></button>
}
Builder.register('editor.editTab', { name: 'AddText', component: AddTextPlugin } );
We’re actually working in an editTab plugin and adding children to the page entirely through interaction with @builder.io/application-context. The components are already registered with Builder.
I may be missing it, but I don’t think that the documentation has anything about how to use context to programmatically add blocks with children to the page from a plugin.
We ended up figuring it out though! If we want to add a Section with Text inside, it would look like this.
I was getting tripped up figuring out where the children property goes for the component and had been trying to set it inside of component property. It turns out that it needs to be a sibling property of component.
In general we found that there isn’t much documentation about how to work with @builder.io/application-context, which made plugin development a little tough. In the end though, we got it to work, which we’re pretty excited about!