How It Works
This page explains the model behind Live Editor: what the editor reads, what an edit changes, and the words the API uses for each part. It's worth reading before building a custom panel or debugging an edit that didn't land.
To change Live Editor itself, the repository's ARCHITECTURE.md walks through the same model file by file.
The source is the state
Live Editor keeps one piece of state: the source code string. Everything on screen is read from it, and every edit is a change to it.
- The canvas re-reads its sections from the code whenever the code changes.
- The panel reads each field's value from the selected section's code.
- An edit finds the exact span of source that holds the value and replaces only that span. Formatting, comments and code the editor doesn't understand stay as they were.
That's why Live.Editor, Live.Dnd and Live.Preview stay in sync without
any extra wiring: they all read the same string from Live, and an edit on
any of them writes a new string back.
Live (provider) — holds the code
▲ │ ▲ │ │
typing │ │ │edit │ │
│ ▼ │ ▼ ▼
Live.Editor Live.Dnd Live.Preview
│
└─► your onChange (when you pass `value`)
When you pass value and onChange to Live.Dnd, your app owns the code and
Live passes it on to the other surfaces.
The document model
Live.Dnd doesn't edit any component tree you give it. It edits a
document: a module whose default export is a component.
const App = () => (
<main id="app-container">
{/* each <section> in here is one section on the canvas */}
<section data-id="hero" data-name="Hero">
<h1
data-id="title"
data-binding={[{ label: 'Title', property: 'innerText' }]}
>
Hello
</h1>
</section>
</main>
);
export default App;
| Term | Meaning |
|---|---|
| Document | The whole source string. |
| Container | The element whose <section> children are the sections: id="app-container", or the containerId you pass. |
| Section | One <section> directly inside the container. The API's Section type is { id, name, code }: its data-id, its data-name, and its JSX source. |
| Palette item | A section template the palette offers. Live.Dnd's items prop is a list of them. Dropping one inserts its code into the container. |
The canvas renders each section separately, as the document with only that section in the container. Imports and helper components at the top of the document work in every section, a section that didn't change isn't rendered again, and a section that fails shows its error in its own slot without affecting the others. See Sections that fail.
Two things follow from that:
- Each section runs the document on its own. It has its own
Appinstance, and the document's top level runs once per section. So state kept inAppor in a top-level variable is separate in each section on the canvas, whileLive.Preview, which renders the whole document once, shares it. See State across sections. - The canvas doesn't run a section's interactions. Each section is
covered, so a click or drag selects and moves the section instead of
reaching its content. Its content is also
inert, so the keyboard can't focus it either: Tab goes from section to section, and Enter selects the section. AnonClickin a section doesn't run on the canvas; try handlers inLive.Preview.
Elements, ids and bindings
Inside a section, the panel edits elements through their bindings.
| Term | Meaning |
|---|---|
data-id | An element's identity. It connects the element you click in the preview with its JSX in the source, and every edit addresses its target by it. Leave it empty (data-id="") and the editor fills it in, writing it into the source with the first edit to a field in that section. An element with no data-id at all can't be edited. |
| Binding | A declaration that one property of an element can be edited, with a label, a type and constraints. Its type is BindingItem. |
| Property | What a binding edits: an attribute such as src, or one of innerText, innerHTML, children and items. See Properties. |
| Field | The control the panel draws for one binding. useDndPanel().bindings gives each one as a PanelBinding, with its current value and an onChange. |
An element's bindings come from the first of these it has:
- its own
data-bindingattribute, - the entry its
data-binding-keynames inbindingKeys(Binding by key), - its component's entry in
bindings(Binding every element of a component).
What happens when you edit
Every edit ends as a new document, but it can start at three levels:
| You... | Level | What changes |
|---|---|---|
| Drop, move, copy or delete a section | Document | The list of sections inside the container |
| Change a field in the panel | Section | The span of the selected section that holds that property |
| Move, copy, add or delete a row in an Items or Children editor | Value | The array literal or the JSX children, which then goes through the section level |
At the section level, the editor:
- finds the element by its
data-idin the selected section, - finds the binding for that property,
- replaces the span of source that holds the value, and nothing else,
- writes the new document to your
onChangeand toLive.
If it can't do this safely, it refuses the edit and leaves the source
unchanged, and you get a DndEditError through onEditError (or a toast)
that says why. Common reasons:
- The element's
data-bindingdoesn't declare that property. - The value is written in a way the editor won't rewrite, such as a variable, a spread or a function call. Editable Syntax lists what's supported.
- The document has a syntax error. While it does, the canvas and panel keep showing the last version that parsed, read-only, until you fix it in the code.
Where the code runs
Live.Preview and each canvas section compile the code in the browser
with Babel and run it in your page's JavaScript context. The result renders
into an iframe, a shadow root, or in place (Preview Modes).
The iframe isolates DOM and CSS, not JavaScript: the code can reach your page like any other script. Only run code you trust. Security says what a document can do, and how to show documents to visitors from a separate site.
Compiled code can import react and whatever you pass in modules.
uiKitModules from @jbpark/live-editor/ui-kit adds ui-kit and
ui-kit/utils.
State across sections
A handler in one section can change what another section shows, as long as the state lives somewhere every section reads. Where that is depends on what renders the document:
| State lives in | Live.Preview | Live.Dnd canvas |
|---|---|---|
useState in the document's App | Shared | One copy per section |
| A top-level variable in the document | Shared1 | One copy per section |
A store you pass in modules | Shared | Shared |
Your app's state, through a context hook you pass in modules | Shared | Shared |
Your app's state, through props | Shared | Shared |
State created inside provider | Shared | One copy per section |
provider is called once per section, so a component it returns that holds
its own state is mounted once per section. Keep the state in your app, above
Live, and have the provider only pass it down.
For state every section shares, create a store once in your app, pass it in
modules, and refer to what each handler changes by a key rather than by
where it sits, so the link survives moving a section:
// Your app: one store, created once.
const store = createKeyedStore(); // get(key), set(key, value), subscribe(listener)
const modules = { 'app-store': store };
<Live.Dnd value={value} onChange={setValue} modules={modules} />;
// The document
import { useSyncExternalStore } from 'react';
import store from 'app-store';
const Tabs = () => {
const tab = useSyncExternalStore(store.subscribe, () =>
store.get('hero-tab'),
);
// ...
};
// In another section
<button onClick={() => store.set('hero-tab', 2)}>Show pricing</button>;
If the document only ever runs in Live.Preview, useState in App is
enough.
Values inside modules must stay the same objects between renders. The
document is compiled again whenever one of them changes, which resets its
top-level variables; see
Keeping edits fast.
Fetching data in a section
To show data from an API or a CMS, pass a hook in modules and call it in the
section's component. The canvas renders each section on its own, so cache
requests in your module, not in the hook, or a request goes out once per
section:
// Your app
const cache = new Map<string, Promise<Product[]>>();
const fetchProducts = (collection: string) => {
if (!cache.has(collection)) {
cache.set(collection, api.products(collection));
}
return cache.get(collection)!;
};
const useProducts = (collection: string) => {
const [items, setItems] = useState<Product[]>([]);
useEffect(() => {
let active = true;
fetchProducts(collection).then(next => active && setItems(next));
return () => {
active = false;
};
}, [collection]);
return items;
};
const modules = { data: { useProducts } };
// The document
import { useProducts } from 'data';
const Products = ({ collection }) => {
const items = useProducts(collection);
return <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>;
};
// In a section, with the collection editable from the panel
<Products
data-id=""
data-binding={[{ label: 'Collection', property: 'collection' }]}
collection="featured"
/>;
Side effects while editing
On the canvas, an effect in the document runs once per section, since each
section runs the whole document. Effects that should run once per page, such
as analytics or a timer that changes the page, can skip the canvas.
Live.Dnd's props reach the document's default export, and Live.Preview
doesn't pass them, so a flag tells the two apart:
<Live.Dnd value={value} onChange={setValue} props={{ editing: true }} />;
// The document
const App = ({ editing }) => {
useEffect(() => {
if (editing) {
return;
}
return analytics.start();
}, [editing]);
// ...
};
One word, several meanings
"Item" appears in several unrelated places in the API:
| Where | Means |
|---|---|
Live.Dnd's items prop, useDndPalette().items | Palette items: section templates |
BindingItem | One binding |
useDndItems, the items property | The rows of an array value |
useDndPanel().item | The selected section |