Custom Palette & Panel
Live.Dnd ships a complete editor — three resizable panes on desktop, a stacked
canvas with Drawers on mobile — and renders it whenever you don't say
otherwise. Everything behind that layout is also reachable as plain data
through hooks (useDndPalette(), useDndPanel(), useDndLayout(),
useDndSections()), so
replacing the palette, the property panel, or the arrangement of the whole
thing is a matter of writing an ordinary component and rendering it inside
Live.Dnd. Drag-and-drop and field editing keep working exactly as before.
There are two ways in, and they compose:
- Keep the built-in layout, swap a region. Render
<Live.Dnd.Layout palette={...} panel={...} />and fill only the slot you care about. The resizable panes, the mobile FAB, and both Drawers stay. - Replace the layout. Pass your own
childrenand placeLive.Dnd.Canvas(plus whatever you want around it) wherever you like.
Drag in the demo's Hero item and select it to see its "Background
Style" field — an object-shaped binding with no declared type at all —
rendered as one input per key instead of an opaque string, by inferring
structure from the parsed value rather than requiring it upfront. Try
Stats or FAQ too: their items bindings are arrays of objects
whose own children/label fields are further, separately data-bound
JSX elements — each array entry gets its own group of fields instead of
one opaque blob for the whole array.
Custom layout
By default Live.Dnd renders three resizable panes (palette / canvas / panel)
on desktop, and on mobile a full-width canvas with the palette and property
panel in Drawers. Pass children to design that layout yourself, composing
the three regions wherever you want them:
import { Splitter } from '@jbpark/ui-kit';
<Live.Dnd value={value} onChange={setValue}>
<Splitter withHandle orientation="horizontal">
<Splitter.Panel defaultSize="15%">
<Live.Dnd.Palette />
</Splitter.Panel>
<Splitter.Panel defaultSize="55%">
<Live.Dnd.Canvas />
</Splitter.Panel>
<Splitter.Panel defaultSize="30%">
<Live.Dnd.Panel />
</Splitter.Panel>
</Splitter>
</Live.Dnd>;
Nothing about the layout is prescribed — a vertical stack, tabs, a
collapsible sidebar of your own, panels in a modal, three CSS grid areas —
as long as each region renders somewhere inside Live.Dnd, which owns the
drag context they share.
| Region | Renders |
|---|---|
Live.Dnd.Palette | The built-in palette draggables, in a scroll container. |
Live.Dnd.Canvas | The drop target and the sortable list of sections. |
Live.Dnd.Panel | The built-in property panel, in a scroll container. |
Live.Dnd.Layout | The built-in arrangement, so you can wrap it (a toolbar above it, say) rather than rebuild it, and replace one region through its palette/panel slots. Also how to get the built-in resizable layout without building it yourself. |
Each takes the props of a div (the region's own styles sit in the
components cascade layer, so a Tailwind utility or a rule outside any layer
in your className overrides them), and each should be
rendered at most once — Canvas in particular carries the scroll container
the section iframes size themselves against, plus fixed drag ids that a
second copy would duplicate.
Two things to know:
Canvasneeds a height-constrained parent. It fills one (height: 100%), so a parent with no height of its own collapses it.childrenreplaces the mobile chrome too — the floating palette button and both Drawers are part of the default layout, not ofLive.Dnd. TheuseDndLayout()hook returns what drove them (isMobile,selectedId,clearSelection,paletteOpen,setPaletteOpen) so a custom layout can build its own:
import { useDndLayout } from '@jbpark/live-editor/dnd';
const MyLayout = () => {
const { isMobile, selectedId, clearSelection } = useDndLayout();
return isMobile ? <Live.Dnd.Canvas /> : /* ... */;
};
useDndLayout() also returns documentError: 'parse-error' while the
source doesn't parse and the canvas shows the last version that did,
'container-not-found' when the document has no container, and null
otherwise. A custom layout can use it to show its own notice. See
Document structure.
It also returns canvasWidth, the Live.Dnd prop of that name, or
undefined when the sections fill the canvas, for a width control of your own.
Live.Dnd.Canvas applies the width itself. See
Previewing at a width.
Keeping the built-in layout and swapping one region
Replacing the palette or the panel usually doesn't mean you want a different
arrangement. Live.Dnd.Layout is the built-in one, exported with two slots
so you can hand it your own component and keep everything else:
<Live.Dnd value={value} onChange={setValue}>
<Live.Dnd.Layout panel={<MyPanel />} />
</Live.Dnd>
That keeps the desktop panes, the mobile FAB, and both Drawers — your
panel is placed in the right-hand pane on desktop and in the properties
Drawer on mobile. A slot goes in raw, so it owns its own container (the
built-in regions bring theirs); palette works the same way.
Document settings: useDndDocument
useDndDocument() returns the fields Live.Dnd's
documentBindings declares, for a
custom panel that shows the document's settings somewhere of its own:
| Field | Type | Description |
|---|---|---|
bindings | PanelBinding[] | One per declared field, in order. A field's id is its settings object's name, such as settings. onChange writes the key in place. |
readOnly | boolean | true while the document doesn't parse; every edit is refused. |
import { Field, useDndDocument } from '@jbpark/live-editor/dnd';
const DocumentSettings = () => {
const { bindings } = useDndDocument();
return bindings.map(binding => (
<label key={`${binding.id}-${binding.property}`}>
{binding.label}
<Field binding={binding} />
</label>
));
};
Sections outline: useDndSections
useDndPanel() reaches the selected section only. useDndSections() lists
every section and acts on any of them, selected or not, so a layers list, an
outline, a "jump to section" menu or a right-click menu of your own can do what
the section toolbar does:
| Field | Type | Description |
|---|---|---|
sections | Section[] | In document order, with the ids and names the canvas uses. |
selectedId | string | null | The selected section, or null. Also null once the selected section has left the document. |
select | (id: string | null) => void | Selects a section without toggling and scrolls it into view. null clears the selection; an unknown id does nothing. Keyboard focus stays where it is, so your list keeps it. |
move | (id: string, direction: 'up' | 'down') => void | One place up or down. Nothing happens at either end. |
moveTo | (id: string, index: number) => void | To a position in sections, clamped to the list, for a sortable list of your own. |
duplicate | (id: string) => void | Copies the section below itself and selects the copy. |
remove | (id: string) => void | Deletes the section, asking onBeforeDelete first. |
readOnly | boolean | true while the document doesn't parse: sections is the last version that did, and every change is refused and reported through onEditError. |
import { useDndSections } from '@jbpark/live-editor/dnd';
const Outline = () => {
const { sections, selectedId, select, move, readOnly } = useDndSections();
return (
<ol>
{sections.map(section => (
<li key={section.id}>
<button
aria-current={section.id === selectedId}
onClick={() => select(section.id)}
>
{section.name}
</button>
<button disabled={readOnly} onClick={() => move(section.id, 'up')}>
Up
</button>
</li>
))}
</ol>
);
};
To react to the selection outside Live.Dnd, pass onSelectionChange. It
gets the selected section, or null, whenever the selection changes: a click,
the keyboard, select(), or the selected section leaving the document through
a delete or an undo. It isn't called for the initial empty selection, nor when
only the function you pass changes.
<Live.Dnd
value={value}
onChange={setValue}
onSelectionChange={section => setTitle(section?.name ?? 'Nothing selected')}
/>
Adding a section stays on useDndPalette().onAdd.
Saving a section as a template
useDndSections() gives each section's code, and palette items are
sections, so a "save as template" button needs no other API. Empty the
data-ids before saving, as palette sections are written: each copy dropped
from the palette then gets ids of its own, filled from its section's id. A
saved section with its ids still in place would give every copy the same
ones.
const SaveTemplate = ({ onSave }: { onSave: (item: Section) => void }) => {
const { sections, selectedId } = useDndSections();
const section = sections.find(item => item.id === selectedId);
return (
<button
disabled={!section}
onClick={() =>
onSave({
id: `template-${Date.now()}`,
name: section!.name,
code: section!.code.replace(/data-id="[^"]*"/g, 'data-id=""'),
})
}
>
Save as template
</button>
);
};
// Your app keeps the templates and passes them after its own items.
// `items` replaces the default palette, so list everything you offer.
const [templates, setTemplates] = useState<Section[]>([]);
<Live.Dnd value={value} onChange={setValue} items={[...myItems, ...templates]}>
<SaveTemplate onSave={item => setTemplates(list => [...list, item])} />
<Live.Dnd.Layout />
</Live.Dnd>;
Custom palette
useDndPalette() returns what drives the palette:
| Field | Type | Description |
|---|---|---|
items | Section[] | The palette's available sections. |
onAdd | (item: Section) => void | Add a section to the canvas. |
Wrap your own markup in the exported Live.Dnd.DraggableItem so items stay
draggable — it owns the dnd-kit wiring and hands back ref / dragProps /
isDragging. For "tap to add", take isMobile from useDndLayout(): at a
mobile breakpoint a tap can't be read as a failed drag attempt (in the
built-in layout the palette sits in a Drawer with the canvas stacked behind
it, so there's nothing to drag onto) and native dblclick synthesis from
double-tap is unreliable anyway. Treat a single click/tap as "add" there
instead of relying on onDoubleClick, as below.
import { useDndLayout, useDndPalette } from '@jbpark/live-editor/dnd';
const MyPalette = () => {
const { items, onAdd } = useDndPalette();
const { isMobile } = useDndLayout();
return (
<div>
{items.map(item => (
<Live.Dnd.DraggableItem key={item.id} item={item}>
{({ ref, dragProps, isDragging }) => (
<div
ref={ref}
{...dragProps}
onClick={isMobile ? () => onAdd(item) : undefined}
onDoubleClick={() => onAdd(item)}
style={{ opacity: isDragging ? 0.5 : 1 }}
>
{item.name}
</div>
)}
</Live.Dnd.DraggableItem>
))}
</div>
);
};
<Live.Dnd value={value} onChange={setValue}>
<Live.Dnd.Layout palette={<MyPalette />} />
</Live.Dnd>;
The card that follows the pointer: renderPaletteOverlay
While an item is dragged, a card follows the pointer. By default it's the
built-in palette card, whatever your items look like. Pass
renderPaletteOverlay to draw your own; it gets the item being dragged:
const renderPaletteCard = (item: Section) => (
<div className="my-card my-card--dragging">{item.name}</div>
);
<Live.Dnd value={value} onChange={setValue} renderPaletteOverlay={renderPaletteCard}>
<Live.Dnd.Layout palette={<MyPalette />} />
</Live.Dnd>;
- Return
undefinedto keep the built-in card, for some items or all. - It only draws the card: the drag is already under way, so it needs no
refordragProps. Rendering your item's component in it, even one that usesLive.Dnd.DraggableItem, is fine; nothing inside the overlay starts a drag. - A canvas section dragged to a new position keeps its own preview.
Custom panel
useDndPanel() returns what drives the property panel:
| Field | Type | Description |
|---|---|---|
item | Section? | The currently selected section, or undefined if none is selected. |
bindings | PanelBinding[] | The selected section's editable data-binding fields, flattened to one entry per bound property. See the table below. |
onChange | (next: Partial<Section>) => void | Update fields of the selected section directly (not through a binding). |
onDelete | (id: string) => void | Delete a section by id. |
onMoveUp | () => void | Move the selected section up. Alternative to drag-reordering — needed because the canvas sits behind the mobile Drawer this panel renders in, so there's nothing visible to drag onto there. |
onMoveDown | () => void | Move the selected section down, same rationale as onMoveUp. |
canMoveUp | boolean | Whether onMoveUp would do anything right now — disable your move-up control when false. |
canMoveDown | boolean | Whether onMoveDown would do anything right now — disable your move-down control when false. |
onNodeChange | (params: { id: string; label: string; property: string; value: unknown }) => void | Commit an edit to an element addressed by its own data-id, rather than through a binding you were handed. Needed for the nested elements bindings can't reach — pass it to Live.Dnd.Field along with the binding. See below. |
onNodesChange | (changes: { id: string; label: string; property: string; value: unknown }[]) => void | Commit several node-level edits as one change. They apply in array order, all or none: if any is refused, nothing is committed and the error names the one that failed. See below. |
readOnly | boolean | true while the document doesn't parse. item and bindings are from the last version that did, and every commit is refused and reported through onEditError until it parses again. Disable your controls, or say why edits aren't landing. |
bindingOptions | { bindings?, bindingKeys? } | Live.Dnd's component registry and key map. Pass it to extract() when the panel reads a section's elements itself, so they get the same fields the built-in panel shows. |
bindings carries each field's type, current value, options (when
present), and an onChange wired straight into the same AST-update pipeline
the built-in panel uses. Switch on binding.type to render your own control:
import { useDndPanel } from '@jbpark/live-editor/dnd';
const MyPanel = () => {
const {
item,
bindings,
onDelete,
onMoveUp,
onMoveDown,
canMoveUp,
canMoveDown,
} = useDndPanel();
return (
<div>
<header>
{item?.name}
<button disabled={!canMoveUp} onClick={onMoveUp}>
Up
</button>
<button disabled={!canMoveDown} onClick={onMoveDown}>
Down
</button>
{item && <button onClick={() => onDelete(item.id)}>Delete</button>}
</header>
{bindings.map(binding => (
<label key={`${binding.id}-${binding.property}`}>
<span>{binding.label}</span>
{binding.options ? (
<select
value={binding.rawValue}
onChange={e => binding.onChange(e.target.value)}
>
{binding.options.map(o => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
) : binding.type === 'jsx' ||
binding.type === 'richtext' ||
binding.type === 'function' ? (
<textarea
defaultValue={binding.rawValue}
onBlur={e => binding.onChange(e.target.value)}
/>
) : (
<input
defaultValue={binding.rawValue}
onBlur={e => binding.onChange(e.target.value)}
/>
)}
</label>
))}
</div>
);
};
Being an ordinary component rather than a callback is the point: a panel can
hold its own state — a validation message, an open/closed group, a
multi-select — without hoisting any of it into the component that renders
Live.Dnd.
Showing one element at a time
bindings is flat: one entry per bound property, across every data-bound
element in the section, in document order. Each entry's id is the data-id
of the element it belongs to, so grouping by id gives one group per element.
The built-in panel draws one box per group this way. A panel can instead keep
a selected element in its own state and show only that element's fields:
import { useState } from 'react';
import { useDndPanel } from '@jbpark/live-editor/dnd';
const ElementSwitcher = () => {
const { item, bindings } = useDndPanel();
const [selectedId, setSelectedId] = useState<string | null>(null);
// One group per element, in document order.
const groups = new Map<string, typeof bindings>();
for (const binding of bindings) {
groups.set(binding.id, [...(groups.get(binding.id) ?? []), binding]);
}
const ids = [...groups.keys()];
const current = selectedId && groups.has(selectedId) ? selectedId : ids[0];
return (
<div>
{ids.length > 1 && (
<nav>
{ids.map(id => (
<button
key={id}
aria-pressed={id === current}
onClick={() => setSelectedId(id)}
>
{id === item?.id ? 'Section' : groups.get(id)![0]!.label}
</button>
))}
</nav>
)}
{current &&
groups.get(current)!.map(binding => (
<label key={`${binding.id}-${binding.property}`}>
<span>{binding.label}</span>
<input
defaultValue={binding.rawValue}
onBlur={e => binding.onChange(e.target.value)}
/>
</label>
))}
</div>
);
};
- A section with one editable element needs no switcher.
- The section's own bindings, when its
<section>has adata-binding, share the section's id (item.id) and come first. See Binding the section itself. - Nested elements inside an
itemsorchildrenvalue aren't inbindings. Reach them throughuseDndItems/useDndChildren(below). - Keep the selection in your panel's state rather than asking
Live.Dndfor one.bindingsstays the full list either way, soLive.Dnd.Fieldand the rest of your panel keep working unchanged.
Wrapping the built-in panel instead of starting from zero
You don't have to replace the panel to add to it. Live.Dnd.Panel is the
built-in one, so keep it and put your own chrome around it:
const MyPanel = () => (
<div>
<MyCustomHeader />
<Live.Dnd.Panel className="h-auto" />
</div>
);
It reads useDndPanel() itself, so wrapping it can't drop a callback on the
way through — onNodeChange included. (className overrides the region's
own styles, so h-auto replaces its height: 100% and the header above it
doesn't push it out of view.)
onNodeChange matters more than it looks. bindings covers the elements
extract() finds by walking the section's markup, which does not include
JSX nested inside an attribute value — the elements held in an items or
children binding. The built-in array/children editors discover those by
re-extracting that value themselves, and commit them through onNodeChange,
addressing each by its own data-id. No single PanelBinding.onChange can
stand in for it, because each one is bound to a fixed element.
Most shipped sections are affected: in stats, 9 of the section's 10
editable elements are only reachable this way. Drop onNodeChange and those
edits are silent no-ops — the fields still render and accept typing, but
nothing commits.
Writing several bindings at once
A control that owns more than one binding, an image picker that sets src and
alt for example, can call onChange on each. That works, and the edits
don't overwrite each other. But each call reaches Live.Dnd's onChange as
its own change, and if the second one is refused the first stays applied.
onNodesChange commits them together:
const { onNodesChange } = useDndPanel();
const pick = image =>
onNodesChange([
{ id: 'hero-image', label: 'Image', property: 'src', value: image.url },
{ id: 'hero-image', label: 'Alt', property: 'alt', value: image.title },
]);
- The edits apply in array order, each on the source the one before it left. Later edits to the same property win.
- It's all or none. If any edit is refused, nothing is committed and
onEditError(or the toast) reports the first one that failed. - On success
Live.Dnd'sonChangeis called once. - An empty array does nothing.
- The edits can target any element of the selected section, by
data-id. To write several keys of one object, pass the whole object to one binding'sonChange: the key order you send is the order written.
updateAll(code, entries) in @jbpark/live-editor/utils/ast is the same
operation on a source string. It returns { success: true, code }, or
{ success: false, code, failure, index } with the original source.
Reusing the built-in control for one binding
Keeping Live.Dnd.Panel is all-or-nothing: you get the built-in panel for
every field. When you want your own controls for most bindings but not all
of them, Live.Dnd.Field renders the built-in control for a single
binding:
import { getFieldKind, isStructuralFieldKind } from '@jbpark/live-editor/dnd';
const MyPanel = () => {
const { bindings, onNodeChange } = useDndPanel();
return (
<div>
{bindings.map(binding => (
<label key={`${binding.id}-${binding.property}`}>
<span>{binding.label}</span>
{isStructuralFieldKind(getFieldKind(binding)) ? (
<Live.Dnd.Field binding={binding} onNodeChange={onNodeChange} />
) : (
<MyOwnControl binding={binding} />
)}
</label>
))}
</div>
);
};
Field takes nothing but a PanelBinding out of bindings and the same
onNodeChange — both already part of what useDndPanel() returns, so no
internal wiring is involved.
It renders the control only. The built-in panel's Label (property)
heading comes from the row around it, not from Field, so supply your own
as above.
This is worth the most on items/children/array bindings. Those hold
nested data-bound JSX that bindings can't reach, and reproducing the
editor means re-parsing the value's JSX, walking it for data-id /
data-binding pairs, and translating item positions back to array element
positions before every edit. Field already does that. For a plain string,
number or option binding there's little reason to reach for it — a bare
<input> wired to binding.onChange is the simpler answer.
Which control Field picks: getFieldKind
getFieldKind(binding) returns the built-in control Field would render
for a binding. Field makes its choice with this same function, so routing
on it can't drift from the built-in panel:
| Kind | Built-in control | Chosen when (first match wins) |
|---|---|---|
'readonly' | Preserved source with a note to use the code editor | canEditValue is false |
'items' | Items editor (useDndItems for your own markup) | type is array, or property is items or data unless type is object or value is a plain object |
'richtext' | Text area with the HTML source | type is richtext |
'html' | Code editor, HTML mode | property is innerHTML |
'jsx' | Code editor | type is jsx |
'function' | Code editor, without formatting | type is function, unless the select below applies |
'children' | Children editor (useDndChildren for your own markup) | property is children and value is an array of nodes |
'object' | One nested field per key | value is a plain object |
'boolean' | Checkbox | type is boolean, or value is a boolean |
'select' | Select | options is set; for function, also value is listed or '', or optionsOnly is set |
'image' | URL input, thumbnail, and a file picker with onUpload | type is image |
'color' | Color input | type is color, or property contains color |
'date' | Date input | type is date |
'time' | Time input | type is time |
'datetime' | Date and time input | type is datetime |
'url' | URL input | type is url |
'email' | Email input | type is email |
'tel' | Phone input | type is tel |
'number' | Number input | type is number, or value is a number |
'text' | Text area | anything else |
isStructuralFieldKind(kind) is true for 'items' and 'children'. Those
are the two kinds whose value holds further data-bound elements, which a flat
input can't edit. A children binding whose value is plain text is 'text',
not 'children'.
The kind describes the built-in control only. renderField runs first and
can draw something else, and widget doesn't affect the kind.
Switching on the kind also lets a headless panel recurse. The fields inside
an item or child can be structural too. For example, Stats' "Stats Cards"
children binding sits inside a "Stats Items" entry. Route those through the
same switch so they get your markup at every depth:
const StructuralField = ({ binding, onNodeChange }) =>
getFieldKind(binding) === 'children' ? (
<MyChildren binding={binding} onNodeChange={onNodeChange} />
) : (
<MyItems binding={binding} onNodeChange={onNodeChange} />
);
// Inside MyItems / MyChildren, for each nested binding:
isStructuralFieldKind(getFieldKind(nested)) ? (
<StructuralField binding={nested} onNodeChange={onNodeChange} />
) : (
<Live.Dnd.Field binding={nested} onNodeChange={onNodeChange} />
);
The Custom Palette & Panel demo's "Headless" mode is built this way.
Arranging the built-in panel: panelLayout
The built-in panel reads no meta key. Live.Dnd's panelLayout says which
fields show, which share a box, and what describes each, with three functions
that all receive a PanelBinding:
| Function | Returns | Without it |
|---|---|---|
isVisible(binding, bindings) | false to leave the field out. An element left with no fields gets no card. Applied to a section's top-level fields. | Every field shows. |
groupOf(binding) | A name. An element's fields with the same name share a box headed by it, where the first of them was. undefined leaves a field unboxed. | No boxes. |
describe(binding) | A node shown under the field's label, which the control names as its description for screen readers. undefined shows none. | No descriptions. |
metaPanelLayout implements the common meta keys
visible, group and description. Pass it as is, spread it to replace one
function, or write your own:
import { metaPanelLayout } from '@jbpark/live-editor/dnd';
<Live.Dnd panelLayout={metaPanelLayout} />;
<Live.Dnd
panelLayout={{
...metaPanelLayout,
groupOf: binding => binding.meta?.section as string | undefined,
}}
/>;
A custom panel reads binding.meta itself, and can use the same visibility check,
isBindingVisible(binding, bindings):
import { isBindingVisible, useDndPanel } from '@jbpark/live-editor/dnd';
const MyPanel = () => {
const { bindings } = useDndPanel();
const shown = bindings.filter(binding => isBindingVisible(binding, bindings));
return /* render `shown` */;
};
Replacing one control everywhere: renderField
To keep the built-in panel and change only how some fields are drawn, pass
renderField to Live.Dnd. It is called before the built-in control for
every field, including the keys inside an object value and the properties
of each array item, and in a custom panel's Live.Dnd.Field as well:
<Live.Dnd
value={value}
onChange={setValue}
renderField={({ binding }, builtin) => {
if (binding.widget?.type === 'slider') {
return (
<input
type="range"
min={binding.min}
max={binding.max}
step={binding.widget.step ?? 1}
value={Number(binding.value)}
onChange={e => binding.onChange(Number(e.target.value))}
/>
);
}
if (binding.type === 'color') {
return <MyColorPicker binding={binding} />;
}
// Anything else keeps the built-in control.
return undefined;
}}
/>
What the function returns decides what renders:
| Return | Result |
|---|---|
undefined | The built-in control. |
| a node | That node instead. |
null | Nothing. The field's heading still shows in the built-in panel. |
The second argument, builtin, is the control that would have rendered, so
you can wrap it instead of replacing it (<Hint>{builtin}</Hint>). Don't
render <Live.Dnd.Field> from inside renderField: it calls renderField
again.
A replacement commits through binding.onChange like any other control, so
validate first with validateBindingValue(binding, value) if the field
declares constraints.
ui-kit controls: uiKitFields
The built-in controls are native inputs, selects and text areas, so the
editor needs no UI kit to edit fields. @jbpark/live-editor/ui-kit exports
uiKitFields, a renderField that draws the rich text, checkbox, select,
color, date, datetime and time fields with @jbpark/ui-kit instead, and
keeps the built-in control for the rest.
@jbpark/ui-kit is an optional peer dependency, so install it, and import
its stylesheet once next to the editor's:
npm install @jbpark/ui-kit
import '@jbpark/live-editor/style.css';
import '@jbpark/live-editor/ui-kit/style.css';
Import it through @jbpark/live-editor/ui-kit/style.css rather than
@jbpark/ui-kit/style.css: this copy sits in its own ui-kit cascade layer,
below the editor's, so ui-kit's reset doesn't restyle the editor and its
utilities don't mix with your own Tailwind's.
import { uiKitFields } from '@jbpark/live-editor/ui-kit';
<Live.Dnd value={value} onChange={setValue} renderField={uiKitFields} />;
The labels and validation messages are tied to these controls the same way
as to the built-in ones. To combine uiKitFields with your own replacements,
call it for the fields yours leave alone:
<Live.Dnd
value={value}
onChange={setValue}
renderField={(props, builtin) =>
props.binding.widget?.type === 'slider' ? (
<MySlider binding={props.binding} />
) : (
uiKitFields(props, builtin)
)
}
/>
ui-kit sections and modules
The rest of @jbpark/live-editor/ui-kit brings back the editor's
ui-kit-based defaults in one place:
| Export | What it is |
|---|---|
uiKitModules | The ui-kit and ui-kit/utils modules, for modules. Compiled code imports neither without it. |
uiKitPaletteSections | The default palette's sections built with ui-kit, for items. They use ui and cn. |
createUiKitDocument(options?) | createDocument() with import * as ui from 'ui-kit' and cn imported, for those sections. |
uiKitFields | The ui-kit field controls, for renderField (above). |
import {
createUiKitDocument,
uiKitFields,
uiKitModules,
uiKitPaletteSections,
} from '@jbpark/live-editor/ui-kit';
import '@jbpark/live-editor/ui-kit/style.css';
const [value, setValue] = useState(createUiKitDocument);
<Live.Dnd
value={value}
onChange={setValue}
items={uiKitPaletteSections}
modules={uiKitModules}
renderField={uiKitFields}
/>;
Pass uiKitModules to Live.Preview too when its code imports ui-kit, and
keep the ui-kit stylesheet imported for its components. To
add modules of your own, spread them in: modules={{ ...uiKitModules, chart }}.
Handling edit errors: onEditError
When an edit can't be applied, the editor shows a toast and leaves the source
unchanged. Pass onEditError to handle it yourself instead. The toast is then
not shown:
<Live.Dnd
value={value}
onChange={setValue}
onEditError={error => {
notify(error.title, error.description);
logEditError(error);
}}
/>
title and description are the toast's own messages. type says what
failed:
type | When | Extra fields |
|---|---|---|
'update' | A field edit was rejected, usually because the element's data-binding names a property or label its markup doesn't have, or because text was written to a self-closing element (self-closing). | id, label, property, failure (with failure.reason) |
'parse' | The selected section, or an items value inside it, doesn't parse. | target ('section' or 'items'), error |
'items' | An array edit would have lost source (a spread, a hole), so it was refused. | — |
'upload' | onUpload rejected for an image field. The value is unchanged. See Images. | id, label, property, error |
Your own markup for an array binding: useDndItems
:::note Renamed hooks
Releases before 5.0 called these two hooks useItemsEditor and
useChildrenEditor, with types named ItemsEditor* and ChildrenEditor*.
5.0 removed those names. To migrate, rename useItemsEditor → useDndItems,
useChildrenEditor → useDndChildren, ItemsEditor → DndItems and
ChildrenEditor → DndChildren wherever they appear.
:::
Field gives you the built-in control. When you want the same engine but
a different layout, useDndItems is that engine on its own:
import { useDndItems } from '@jbpark/live-editor/dnd';
const MyItems = ({ binding, onNodeChange }) => {
const { items, selection, actions, canEditStructure } = useDndItems(
binding.rawValue,
{
render: binding.render,
onChange: binding.onChange,
onNodeChange,
minItems: binding.minItems,
maxItems: binding.maxItems,
},
);
return (
<div>
<button disabled={!canEditStructure} onClick={actions.add}>
Add
</button>
{items.map(item => (
<details key={item.id}>
<summary>
#{item.index + 1}
<button
disabled={!canEditStructure}
onClick={() => actions.remove(item.elementIndex)}
>
x
</button>
</summary>
{/* plain properties of an object item */}
{item.properties.map(prop => (
<input
key={prop.label}
defaultValue={prop.rawValue}
onBlur={e => prop.onChange(e.target.value)}
/>
))}
{/* the nested elements `bindings` can't reach */}
{item.nested.map(group =>
group.elements.map(el =>
el.bindings.map(b => (
<Live.Dnd.Field
key={b.label}
binding={b}
onNodeChange={onNodeChange}
/>
)),
),
)}
</details>
))}
</div>
);
};
Everything it returns is a PanelBinding, so it composes with Field —
render your own layout and still hand individual bindings to the built-in
control where that's good enough, as above.
What you don't have to reimplement:
- Re-parsing each item's JSX to find nested data-bound elements, and
resolving the binding
rendermap onto each property. - Translating a visible item position (
index) to its position in the array's elements (elementIndex), which is what every edit addresses. They differ whenever the array mixes objects and primitives. - Keeping the selection pointed at the right items after every edit, so a later bulk action never hits the wrong ones. See Selection after an edit.
| Field | Type | Description |
|---|---|---|
kind | 'object' | 'primitive' | Which kind the array is being edited as. An array holding both is treated as objects; the primitives are left untouched rather than dropped. |
items | DndItemsItem[] | One entry per item. properties holds an object item's plain fields, nested its JSX-valued ones, value a primitive item's own binding. |
selection | multi-select state | selected, toggle, isSelected, clear, replace. Indices are item index values; the actions translate. |
expansion | DndItemsExpansion | Which items show their fields: expandedIds, isExpanded(id), toggle(id), setExpanded(ids). Keyed by item id, and every item starts expanded. See Collapsing and drag sorting. |
actions | DndItemsActions | add, move, remove, plus duplicateSelected / moveSelected / removeSelected. |
canEditStructure | boolean | Uses the same dense-array syntax gate as the mutation helpers. Keep value controls available when false, but disable move, copy, add, and delete and direct the user to the code editor. |
canAddItems / canRemoveItems | (count?: number) => boolean | Whether adding or removing count items (default 1) stays within the minItems and maxItems passed in. The actions refuse an edit past either limit and report it through onEditError. The last item can't be removed even without minItems. |
parseError | boolean | The source didn't parse as an array. items is empty. |
The built-in Items panel is written against exactly this hook, so anything
it can do is reachable here.
Collapsing and drag sorting
The built-in Items panel lets each item collapse to its header, with
"Collapse all" / "Expand all" above the list, and reorders items by dragging
their handle. A mouse drag starts after a few pixels, a touch drag after a
long press, and the keyboard picks an item up with Space or Enter on the
handle. The up/down buttons and bulk actions are still there.
expansion holds the collapsed state for your own markup too. It's keyed by
item id, so an item stays collapsed when it moves or a sibling changes,
and an item added later starts expanded. The hook only holds the state;
what a collapsed item shows is up to you. A one-line summary can come from
the item's own fields:
const { items, expansion } = useDndItems(binding.rawValue, {
onChange: binding.onChange,
});
items.map(item => {
const title = item.properties.find(prop => prop.property === 'title');
return (
<section key={item.id}>
<button
aria-expanded={expansion.isExpanded(item.id)}
onClick={() => expansion.toggle(item.id)}
>
{String(title?.value ?? `Item ${item.index + 1}`)}
</button>
{expansion.isExpanded(item.id) && <ItemFields item={item} />}
</section>
);
});
For drag sorting in your own markup, use @dnd-kit/sortable with item.id
as the sortable id, and commit the drop with
actions.move(from.elementIndex, to.index), the same edit the built-in
panel makes. Give the list its own DndContext, so a drag inside the panel
never reaches the canvas's section sorting.
Array source preservation and limits
Value edits replace only the selected value's source span. Original array
indices are retained: holes and spread entries are omitted from the visible
list, but they remain in the source. For example, changing A in
[, {label:'A'}, {label:'B'}] leaves the leading hole and B untouched.
| Operation | Dense arrays | Arrays with holes or spreads |
|---|---|---|
| Edit a supported literal or object property | Supported | Supported at its original syntax position |
| Move, remove, duplicate, append | Supported | Refused; edit the source code instead |
| Edit a spread entry itself | Not applicable | Refused |
Structural edits preserve raw element text, comments, whitespace and trailing
commas. Gaps between elements stay in their original positions during moves;
deleting an element removes its expression and the necessary separator while
leaving surrounding comments. Copies retain expressions and nested JSX, with
fresh static key and data-id values. Dynamic/ambiguous copy identities,
colliding generated IDs, and parenthesized top-level elements are refused.
The existing last-item guard and empty-array Add limitation remain in place.
A refused operation returns null from the AST helper, leaves source and
selection unchanged, and displays an error through the built-in hook. Public
helper signatures are unchanged. Formatting of returned code now follows the
original source rather than Babel's whole-array formatting.
Your own controls for a children binding: useDndChildren
Pass the structured binding.value to useDndChildren. It sends structural
commands through the existing binding.onChange callback:
import { useDndChildren } from '@jbpark/live-editor/dnd';
const MyChildren = ({ binding }) => {
const { items, selection, actions } = useDndChildren(binding.value, {
onChange: binding.onChange,
});
return (
<div>
<button onClick={actions.add}>Add child</button>
<button onClick={actions.duplicateSelected}>Duplicate selected</button>
<button onClick={actions.removeSelected}>Delete selected</button>
{items.map((item, index) => (
<div key={item.id ?? index}>
<input
type="checkbox"
checked={selection.isSelected(index)}
onChange={() => selection.toggle(index)}
/>
Child {index + 1}
<button
disabled={index === 0}
onClick={() => actions.move(index, index - 1)}
>
Move up
</button>
<button onClick={() => actions.remove(index)}>Delete</button>
</div>
))}
</div>
);
};
items contains the extracted DataAttrNode children. selection exposes
selected, toggle, isSelected, clear, and replace. Actions are add,
move(from, to), remove(index), duplicateSelected, moveSelected('up' | 'down'),
and removeSelected. All indices refer to the current extracted list.
The fields inside each child are ordinary data-bound elements, but the hook
hands you raw nodes, not PanelBindings. Turn them into bindings with the
same two steps useDndPanel().bindings goes through, then render each with
Live.Dnd.Field (or your own control):
import {
Field,
resolvePanelBindings,
withPanelCommit,
} from '@jbpark/live-editor/dnd';
import { findEditableChildren } from '@jbpark/live-editor/utils/ast';
const ChildFields = ({ child, onNodeChange }) =>
findEditableChildren(child).map(node => {
const source = resolvePanelBindings(node);
if (!source) {
return null;
}
return withPanelCommit(source.bindings, onNodeChange).map(binding => (
<label key={`${binding.id}-${binding.property}`}>
{binding.label}
<Field binding={binding} onNodeChange={onNodeChange} />
</label>
));
});
resolvePanelBindings(node)reads one element'sdata-idanddata-bindinginto{ id, tagName, bindings }, or returnsnullwhen the element isn't editable. Its bindings carry everything aPanelBindingdoes exceptonChange.withPanelCommit(bindings, onNodeChange)adds thatonChange, committing each edit by the element's id. Call it during render, not inside a memo:onNodeChangecloses over the current document, and a stale one would write an older source back.
Structural edits preserve each subtree's original source. Text, comments, and
expressions between children stay in their original slots. Copies are appended
before the closing tag, with fresh data-id values on copied JSX elements.
Add copies the first child, or inserts an empty div when the list is empty.
The selection follows the rule in
Selection after an edit.
The AST layer refuses stale commands, invalid indices, unmodeled empty or
expression-only fragments, and copies whose dynamic IDs or trailing spreads
make identity ambiguous. A refused edit returns success: false and keeps the
original code; the built-in panel displays an error. Self-closing parents must
be expanded before adding children.
Existing JSON DataAttrNode[] inputs to update() remain supported for reorder
and removal. Unchanged children reuse their original source. Arbitrary modeled
replacements are accepted only when the old children can be represented without
source loss and the result introduces no duplicate static IDs. Prefer the hook
for structural operations; retain the extracted source metadata for stale-edit
checks. Low-level callers can use ChildrenEdit and getChildrenSignatures from
@jbpark/live-editor/utils/ast.
Selection after an edit
useDndItems and useDndChildren share one selection rule. Selection
indices are positions, so whatever moves items has to move or clear the
selection with them:
| What changed the source | Selection afterwards |
|---|---|
add, duplicateSelected | Unchanged. Both append at the end, so no existing item moves. |
moveSelected | The moved items, at their new positions, so the block can be moved again. |
move, remove, removeSelected | Cleared. Positions shifted under the selection. |
An item value edit (useDndItems) | Unchanged. |
Anything else: another field, undo, an external value | Cleared. The same positions may now hold different items. |
| A refused edit | Unchanged. No new source was produced. |
useDndChildren applies the result when the new source arrives, since the
host's onChange decides whether the edit succeeds. useDndItems applies
it immediately, because its own array edit has already succeeded by then.
PanelBinding
| Field | Type | Description |
|---|---|---|
id | string | data-id of the owning element (stable across edits). |
label | string | Human-readable label from the binding definition. |
property | string | The bound prop/attribute name. |
type | BindingType? | The declared data kind — what the value is (string, number, boolean, ...). undefined means a plain string binding. See the full list below. |
widget | BindingWidget? | The declared presentation — how to render it, as { type, ...settings }. widget.type is an open string, not BindingType: the library ships no widgets, so every value (e.g. 'slider') is a name you make up and handle yourself. Authored as a bare string (widget: 'slider'), it arrives as { type: 'slider' }. The built-in panel ignores it and renders the default control for type. |
options | BindingOption[]? | Present when the binding defines a fixed option set (render a <select>). |
optionsOnly | boolean? | true when options is the only choice. validateBindingValue rejects anything else but empty, and getFieldKind returns 'select' whatever the current value. |
render | BindingRenderMap? | Present on object/array bindings whose nested keys/items declare their own types — walk it to type each nested field instead of treating the value as an opaque string. |
min | number? | Minimum value for a number binding. Compared against the real number value delivers — pass it straight to validateBindingValue. |
max | number? | Maximum value for a number binding. |
pattern | string? | A regex source the value must match. |
required | boolean? | Whether an empty value should fail validation. |
patternMessage | string? | Shown instead of the pattern message when pattern fails. |
minLength / maxLength | number? | Length limits for a string value, in characters. |
step | number? | A number value must be min (or 0) plus a whole number of steps. The built-in number input gets the same step. |
minItems / maxItems | number? | Item count limits for an array value. Pass them to useDndItems, which enforces them. |
minDate / maxDate | string? | The earliest and latest date or datetime value, as YYYY-MM-DD or YYYY-MM-DDTHH:mm. |
protocols | string[]? | The schemes a url value may use. Unset allows any. |
meta | Record<string, unknown>? | Any authored key that isn't one of the fields above (a group name, help text, ...) — see below, and Common meta keys for a shared set of names. Control settings such as a step or unit belong on widget instead. undefined when nothing extra was authored, not an empty object. |
value | unknown | Current value as its real JS type — a number for a number binding, a boolean, an object/array, a string otherwise. Switch on it without re-parsing. |
rawValue | string | The exact source text behind value, for cases that can't round-trip through a JS value (jsx/richtext/function, or an expression attribute you want to edit as text). Use it for an <input> defaultValue and for flattenEditableValue/setEditableValue. |
canEditValue | boolean? | false when reconstructing the modeled value could discard a reference, call, spread, hole, or computed property. Hide or disable the value control and direct the user to the code editor. undefined means the value is editable. |
element | { tagName: string; text: string }? | The element the binding belongs to: its tag name as written and its own text, trimmed ('' when it has none). The built-in panel heads each element's fields with these. Absent for a binding that isn't an element's, such as an array item's property. |
present | boolean? | false when the binding names an attribute the element doesn't carry. onChange(undefined) removes an attribute and onChange(value) adds it back, so this is what an on/off control reads. undefined means the attribute is there, or the binding is content (innerText, innerHTML, children). See Optional attributes. |
onChange | (value: unknown) => void | Commit an edit through the same AST-update pipeline (including the error toast on a bad edit). Pass the value as its real type — it's serialized once, at the AST boundary, where the declared type is known, so no string quoting on your side. |
BindingType is a closed union of 16 data kinds: array, object,
string, number, boolean, color, jsx, richtext, function, date,
time, datetime, url, email, tel, image. A binding with no type on an
attribute that holds a function expression arrives as type: 'function'.
Switching on it alone is enough for the scalar types; for object/array
values, see flattenEditableValue below rather than treating them as plain
text. Data Binding describes how each field is
authored and what the built-in panel does with it.
Choosing a control is the panel's job
The library owns what a value is (type) and what it may be (the
constraints). How it is drawn is yours: widget is
passed through untouched, and the built-in panel never reads it.
There is no list of built-in widgets to pick from. 'slider' below is a
name this example makes up, not a library feature; 'switch', 'radio' or
'icon-picker' would work the same way as long as your panel handles them.
Declare whatever control you want and the config it needs on widget, then
switch on widget.type. A field whose widget you don't handle falls back to
the built-in control for its type:
// data-binding={[{ label: 'Spacing', property: 'size', type: 'number', min: 0, max: 40, widget: { type: 'slider', step: 4, unit: 'px' } }]}
bindings.map(binding =>
binding.widget?.type === 'slider' ? (
<input
type="range"
min={binding.min}
max={binding.max}
step={binding.widget.step ?? 1}
defaultValue={binding.rawValue}
onChange={e => binding.onChange(Number(e.target.value))}
/>
) : (
// ...fall back to the built-in control
<Live.Dnd.Field binding={binding} />
),
);
step and unit are the widget's settings, and the library reads neither.
They're the only two that come typed, as a convenience; any other setting
you put on widget passes through as unknown, so narrow it before use (see
widget). The shipped Custom Palette &
Panel demo's "Content Spacing" field does exactly this; drag it in the
embedded demo above to see it live. To do the same without writing a whole
panel, see renderField.
Any key you author on a binding that the library doesn't define arrives
under binding.meta, typed unknown for the same reason.
Nested fields
A render-map leaf accepts every field a top-level binding does (see
Nested fields). useDndItems hands
each key of an item back as a PanelBinding carrying those fields, so switch
on widget and validate against constraints exactly as for a flat binding.
label and property fall back to the key, and meta.valueType is always
set to the property's actual kind (an authored valueType is overridden).
Constraints declared on a binding aren't enforced automatically — call the
exported validateBindingValue(binding, value) yourself before committing an
edit, the same way the built-in panel does. The exception is minItems and
maxItems: pass them to useDndItems, whose actions enforce them.
Authoring constraints
Two things a data-binding entry has to satisfy for its edits to actually
commit, neither enforced at parse time:
propertymust already exist as an attribute on the element.binding.onChangewrites through the same AST-update pipeline the built-in panel uses, which updates an existing JSX attribute — it doesn't add a new one. A binding whosepropertynames something not already present in the markup (as a prop, or as the element's owninnerText/children/etc.) parses fine and shows up inbindings, but everyonChangecall fails on the built-in panel's side (a "Failed to update" toast, or anonEditErrorcall) or returnssuccess: falseif you're callingupdate()yourself.labelmust be unique per element.labelis a display string, not an identifier, but where a binding doesn't declarepropertyit's still how the built-in AST utilities resolve which binding you mean. Two bindings on the same element sharing a label is an authoring mistakeupdate()refuses to silently guess at — it returnssuccess: falseinstead of writing whichever one happened to match first.
Escaping the binding system entirely
data-binding covers declared, per-property edits. For anything else —
restructuring markup, adding a whole new element, editing something with no
binding declared at all — useDndPanel()'s item.code is the section's full
current source, and the exported extract() walks it into the same
DataAttrNode tree the built-in panel reads (including custom, entirely
undeclared data-* attributes, which extract() passes through intact).
Commit any string back with onChange({ code }):
import { extract } from '@jbpark/live-editor/utils/ast';
const RawEditor = () => {
const { item, onChange, bindingOptions } = useDndPanel();
if (!item) return null;
// With `bindingOptions`, nodes bound by key or by component carry the
// same `bindings` the built-in panel reads.
const nodes = extract(item.code, bindingOptions); // read whatever you need
return (
<button onClick={() => onChange({ code: item.code.replace(/foo/, 'bar') })}>
Edit raw source
</button>
);
};
This is a full escape hatch, not a fallback of last resort — it's the same mechanism Editor mode itself commits through.
Editing object/array values
For an object/array binding, binding.value is already the parsed
object or array, and binding.rawValue is its serialized source text. A
binding's own declared render map (above) is one way to know how to
decompose it, but most content doesn't declare one; e.g. the shipped Hero
item's "Background Style" binding on style has no type or render at
all, since style is just naturally object-shaped.
flattenEditableValue(rawValue) recovers editable structure straight from
the source text, with no declaration required: it parses the string
(the same way parseValue does) and, if the result is an object or array,
recursively walks it, returning one { path, value } entry per primitive
leaf found. path is a list of keys/indices you can hand to
setEditableValue to commit an edit to just that leaf. It returns
rawValue with only that leaf's source text replaced, ready for
binding.onChange, so everything else in the value stays as written:
formatting, comments, JSX, and functions or references the panel never
shows. A nested object/array is walked into further; a string, number, or
boolean is always a leaf — including one that happens to contain JSX. This
is what lets it handle the shipped Stats/FAQ sections' items arrays of
{ key, children }, where children is itself a separately data-bound
JSX element: children comes back as one opaque text leaf rather than
being decomposed further, exactly like parseValue already treats JSX
elsewhere.
A few rules for setEditableValue:
- The new value is written as its own type. A string keeps the quotes the
leaf was written with, so convert an
<input>'s text back to a number or boolean first if the leaf was one. - A JSX leaf stays JSX when the edited text is still JSX, and becomes a string otherwise.
- It never adds a key or grows an array. A path that
flattenEditableValuewouldn't report, such as a missing key, an index past the end, or an entry a later spread could replace, returnsrawValueunchanged.
const entries = flattenEditableValue(binding.rawValue);
// null if the value isn't an object/array, or is empty
entries?.map(({ path, value }) => (
<input
key={path.join('.')}
defaultValue={String(value)}
onBlur={e =>
binding.onChange(setEditableValue(binding.rawValue, path, e.target.value))
}
/>
));
BindingType, BindingOption, BindingRenderMap, validateBindingValue,
flattenEditableValue, and setEditableValue aren't exported from the
package root — import them from the utils/ast subpath instead:
import {
type BindingOption,
type BindingRenderMap,
type BindingType,
flattenEditableValue,
setEditableValue,
validateBindingValue,
} from '@jbpark/live-editor/utils/ast';