Skip to main content

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;
TermMeaning
DocumentThe whole source string.
ContainerThe element whose <section> children are the sections: id="app-container", or the containerId you pass.
SectionOne <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 itemA 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 App instance, and the document's top level runs once per section. So state kept in App or in a top-level variable is separate in each section on the canvas, while Live.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. An onClick in a section doesn't run on the canvas; try handlers in Live.Preview.

Elements, ids and bindings​

Inside a section, the panel edits elements through their bindings.

TermMeaning
data-idAn 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.
BindingA declaration that one property of an element can be edited, with a label, a type and constraints. Its type is BindingItem.
PropertyWhat a binding edits: an attribute such as src, or one of innerText, innerHTML, children and items. See Properties.
FieldThe 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:

  1. its own data-binding attribute,
  2. the entry its data-binding-key names in bindingKeys (Binding by key),
  3. 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...LevelWhat changes
Drop, move, copy or delete a sectionDocumentThe list of sections inside the container
Change a field in the panelSectionThe span of the selected section that holds that property
Move, copy, add or delete a row in an Items or Children editorValueThe array literal or the JSX children, which then goes through the section level

At the section level, the editor:

  1. finds the element by its data-id in the selected section,
  2. finds the binding for that property,
  3. replaces the span of source that holds the value, and nothing else,
  4. writes the new document to your onChange and to Live.

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-binding doesn'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 inLive.PreviewLive.Dnd canvas
useState in the document's AppSharedOne copy per section
A top-level variable in the documentShared1One copy per section
A store you pass in modulesSharedShared
Your app's state, through a context hook you pass in modulesSharedShared
Your app's state, through propsSharedShared
State created inside providerSharedOne 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:

WhereMeans
Live.Dnd's items prop, useDndPalette().itemsPalette items: section templates
BindingItemOne binding
useDndItems, the items propertyThe rows of an array value
useDndPanel().itemThe selected section

Footnotes​

  1. Changing a variable doesn't re-render anything, and it's reset whenever the document is compiled again. ↩