Skip to main content

Drag & Drop

Live.Dnd lets you build UIs visually. At wider sizes, drag a component from the left palette onto the canvas, then edit its properties from the panel on the right; below Live.Dnd's own responsive breakpoint, the palette and panel move into a drawer instead, and a tap adds the section (there's nothing visible to drag onto once the canvas is stacked behind the drawer). Powered by @dnd-kit.

import { useState } from 'react';

import Live from '@jbpark/live-editor';
import { createDocument } from '@jbpark/live-editor/utils';

export default function DragAndDrop() {
const [value, setValue] = useState(() => createDocument());

return (
<Live>
<Live.Dnd
value={value}
onChange={setValue}
dynamicTailwind
frame={{ mode: 'shadow', syncStyle: true }}
/>
</Live>
);
}
  • value / onChange hold the generated source — drops and property edits are applied through the same AST pipeline, so the code stays canonical. Start from createDocument(), not an empty string: see Document structure.
  • onChange is called once per edit, with { source: 'dnd' } as a second argument. For undo and redo, pass useLiveHistory's value and onChange: see Undo and redo.
  • frame configures the preview surface (see Preview Modes).
  • Use items to customize the palette's available sections. Mark what the panel can edit in each section with data-binding — see Data Binding. Without items, the palette offers a set of sections built from plain elements and Tailwind classes, which need no modules. Like any Tailwind class in preview code, theirs apply through dynamicTailwind or syncStyle (see How Tailwind reaches the preview). The same sections built with @jbpark/ui-kit come from @jbpark/live-editor/ui-kit — see ui-kit sections.
  • A section's name, shown on the canvas and in the panel, comes from its data-name. A <section> without one is named by sectionNameFallback, which gets the section's 0-based position. The default gives Section 1, Section 2, and so on.
  • Use children to replace the built-in UI — a region of it (<Live.Dnd.Layout panel={...} />) or the whole arrangement, driven from the useDndPalette() / useDndPanel() / useDndLayout() hooks — see Custom Palette & Panel.

The embedded demo above runs the real Live.Dnd component, isolated with shadow mode inside a sandboxed iframe (see Preview Modes).

Section toolbar​

A selected section shows four buttons in its top-right corner: move up, move down, duplicate and delete. Move up is disabled on the first section and move down on the last. The move buttons make the same move as the panel's, so a section can be reordered without a drag even when a custom panel leaves move controls out.

In the built-in mobile layout, selecting a section opens the panel in a drawer, which has the same buttons.

Keyboard​

Palette cards and canvas sections can be reached with Tab. A section's content can't: it's inert on the canvas, so Tab goes from one section to the next, and the content's own buttons, links and inputs never take focus or run from the keyboard, as they don't from a click. A screen reader hears the section's name. Its content is edited in the panel, and runs in Live.Preview. While the element picker is on, the content isn't inert, since the picker finds elements under the pointer.

KeyOn a palette cardOn a canvas section
EnterAdds the section to the canvasSelects the section (or clears the selection), like a click
Arrow Up / Arrow Down—Goes to the previous or next section and selects it
Home / End—Goes to the first or last section and selects it
Alt+Arrow Up / Alt+Arrow Down—Moves the section up or down one place, selects it and keeps focus on it. Nothing happens at either end
Cmd+D (macOS) / Ctrl+D—Duplicates the section below itself, and selects and focuses the copy
Delete or Backspace—Deletes the section (through onBeforeDelete) and moves focus to the next one
SpacePicks the card up to drag itPicks the section up to move it
Arrow keys, while picked upMove what's picked upMove the section
Space or Enter, while picked upDrops itDrops it at the new position
Escape, while picked upCancels the dragCancels the move

Screen readers hear the section's name and its new position while it moves. The selected section is scrolled into view whenever it moves out of sight, from the keyboard or from the move buttons on the canvas or in the panel.

Confirming a delete​

Deleting a section is immediate. Pass onBeforeDelete to ask first: it gets the section, and returning false, or a promise of false, keeps it. It runs for the delete button on the canvas, the one in the panel, and a custom panel's onDelete. The library shows no dialog of its own.

<Live.Dnd
value={value}
onChange={setValue}
onBeforeDelete={section => confirm(`Delete ${section.name}?`)}
/>

A promise is waited for, and the section is removed from the document as it is when the answer comes, so edits made while your dialog was open are kept. If onBeforeDelete throws or rejects, the section is kept.

With a modal of your own​

confirm() blocks the page and can't be styled. To use your own dialog, wrap it in a promise that resolves when the user answers. With Modal.confirm from @jbpark/ui-kit:

import type { Section } from '@jbpark/live-editor';
import { Modal } from '@jbpark/ui-kit';

const confirmDelete = (section: Section) =>
new Promise<boolean>(resolve => {
Modal.confirm({
title: 'Delete section?',
content: `"${section.name}" will be removed from the document.`,
okText: 'Delete',
cancelText: 'Cancel',
onOk: () => resolve(true),
onCancel: () => resolve(false),
});
});

<Live.Dnd value={value} onChange={setValue} onBeforeDelete={confirmDelete} />;

Any dialog works the same way, as long as every way of closing it resolves the promise: resolve false on cancel, on Escape and on a click outside, or the section stays undecided and is never removed.

A popover anchored to the delete button, such as ui-kit's Popconfirm, doesn't fit here: onBeforeDelete gets the section, not the control that asked, and the Delete key has no control to anchor to. Use a dialog that doesn't need an anchor.

onBeforeDelete covers sections only. Removing an item in the Items editor or a child in the Children editor doesn't ask.

Picking an element​

The crosshair button at the bottom-left of the canvas turns on the element picker. While it's on, the element under the pointer is outlined, and a click selects that element's section and brings its fields into view in the panel, including fields nested in an Items or Children editor. The picker turns off after a pick, and Escape turns it off without one. Sections can't be dragged while it's on.

onNodePick reports each pick: the element's data-id, which is the id its fields carry in useDndPanel().bindings, and its section's id.

<Live.Dnd
value={value}
onChange={setValue}
onNodePick={({ id, sectionId }) => console.log(id, sectionId)}
/>

A custom layout or panel drives the picker with useDndInspector():

FieldTypeDescription
activebooleanWhether the picker is on.
activate / deactivate / toggle() => voidTurns it on or off.
picked{ id: string; sectionId: string } | nullThe last element picked, until another section is selected. A custom panel can use it to show that element's fields.
highlight(id: string | null) => voidOutlines the element with this data-id in the selected section's preview, the way the picker outlines the element under the pointer. null removes the outline. Call it when a field is hovered or focused so it shows which element it edits.
import { useDndInspector, useDndPanel } from '@jbpark/live-editor/dnd';

const MyPanel = () => {
const { picked, toggle, active } = useDndInspector();
const { bindings } = useDndPanel();
const fields = picked
? bindings.filter(binding => binding.id === picked.id)
: bindings;

return (
<>
<button aria-pressed={active} onClick={toggle}>
Pick an element
</button>
{/* render `fields` */}
</>
);
};

The other direction works too. In the built-in panel, hovering over or focusing a field outlines the element it edits on the canvas. When a section has more than one editable element, the panel heads each element's fields with its tag name and text, such as h2 and "Fast setup", so fields that share a label can be told apart. A custom panel gets the same information from each binding's element and calls highlight itself.

What can be picked:

  • An element is picked by its data-id, so the picker finds the nearest element at or above the pointer that has one. Empty ids are filled for the preview the same way the panel fills them (see Data Binding).
  • A component that doesn't pass data-* attributes through to its DOM can't be picked itself. Clicking it picks the nearest element above it that has a data-id.
  • It works the same in every frame mode: in an iframe, in a shadow root, or rendered in place.
  • Fields inside a collapsed array item aren't shown, so the panel can't bring them into view until the item is expanded.

Previewing at a width​

canvasWidth sets the width sections render at, in CSS pixels. The column is centered in the canvas, which scrolls sideways when it's narrower. Unset, the sections fill the canvas. The control is yours to draw:

const WIDTHS = [
{ label: 'Phone', width: 390 },
{ label: 'Tablet', width: 768 },
{ label: 'Full', width: undefined },
];

const Editor = () => {
const [value, setValue] = useState(initialCode);
const [width, setWidth] = useState<number | undefined>();

return (
<>
{WIDTHS.map(option => (
<button
key={option.label}
aria-pressed={width === option.width}
onClick={() => setWidth(option.width)}
>
{option.label}
</button>
))}
<Live.Dnd
value={value}
onChange={setValue}
frame={{ mode: 'iframe' }}
canvasWidth={width}
/>
</>
);
};

The number is the sections' own width: canvasWidth={390} makes each section, and its iframe, 390px wide. What follows it depends on the frame mode:

frame.modeSection widthMedia queries (sm:, md:)
iframecanvasWidthFollow canvasWidth. Viewport units and auto height follow it too.
shadowcanvasWidthFollow the browser window.
none (in place)canvasWidthFollow the browser window.

So a responsive preview needs frame={{ mode: 'iframe' }}. See Preview Modes for why. A custom layout reads the current value from useDndLayout().canvasWidth, and Live.Dnd.Canvas applies it as the built-in layout does.

Trust​

Each section on the canvas runs the document's code with your page's privileges, as the preview does. Open documents from people you trust, or see Security for showing and editing other people's documents.

Document structure​

Live.Dnd edits one component's source. Its sections are the <section> elements inside a container element, found by its id:

const App = () => {
return (
<main id="app-container">
<section data-name="Hero" data-id="a1b2c3">
{/* ... */}
</section>
<section data-name="Features" data-id="d4e5f6">
{/* ... */}
</section>
</main>
);
};

export default App;
  • The container is the element whose id is app-container. The tag doesn't matter. To use another id, pass it as containerId, both to Live.Dnd and to createDocument({ containerId }).
  • Each <section> inside the container is one section on the canvas, in source order, even when it's wrapped in other elements. A <section> nested inside another belongs to its parent.
  • data-name is the section's name; see sectionNameFallback above for sections without one. data-id identifies the section across edits. Live.Dnd gives every section that lacks one an id the next time it commits an edit, so you don't need to write it by hand.
  • createDocument() from @jbpark/live-editor/utils returns an empty document in this shape. Without a value, Live.Dnd starts from the same document.

A document without the container has no sections, and nothing added from the palette can land in it. Live.Dnd reports this once through onEditError, or a toast by default, with type: 'parse', target: 'document' and reason: 'container-not-found'. The canvas names the missing id too.

A document that doesn't parse is usually one being typed in the code editor. The canvas and panel keep showing the last version that parsed, with a notice that it's out of date, and stay read-only until the source parses again. An edit tried in the meantime isn't applied: it's reported through onEditError with reason: 'parse-error'. If the document has never parsed, the canvas says it has a syntax error.

Sections that fail​

A section that fails to compile, or throws while rendering, shows an error box in its slot on the canvas; the other sections keep working. To show your own placeholder instead, pass renderSectionFallback:

const retired = new Set(['Legacy Banner']);

<Live.Dnd
value={value}
onChange={setValue}
renderSectionFallback={({ section, reason, message }) => (
<div className="rounded border border-dashed p-6 text-center">
{section.name} is unavailable
{reason !== 'forced' && <small>{message}</small>}
</div>
)}
shouldForceSectionFallback={section => retired.has(section.name)}
/>
reasonWhenmessage
'compile'The section's code doesn't compile.The compiler's message.
'runtime'The section threw while rendering.The error's message.
'forced'shouldForceSectionFallback returned true.undefined
  • Return undefined to keep the built-in error box for that case.
  • shouldForceSectionFallback runs before a section is compiled. A section it selects is never compiled, so none of its top-level code runs. Use it for sections you know can't work, such as ones that import a component your modules no longer provide.
  • A runtime fallback renders inside the section's frame, where the section's own content would have been. In iframe mode it only gets the host's styles with frame.syncStyle, so prefer inline styles there. Compile and forced fallbacks render outside the frame.
  • Fixing a section's code recovers it automatically.
  • If your fallback itself throws, that section falls back to the built-in error box. The canvas keeps working.

Keeping edits fast​

Each canvas section re-renders only when its own inputs change, so an edit to one section doesn't redraw the rest. Two props are compared by reference, because the library can't tell whether a new function or object does the same thing as the old one:

  • provider: an inline arrow function is a new function on every render.
  • Objects and functions inside props: props={{ theme: { dark: true } }} creates a new theme object on every render. Strings, numbers and booleans are fine.

Written inline, either one re-renders every section on every edit. In a large document that's slow: at 90 sections it made each edit take over a second. Define them outside the component, or keep them stable with useCallback or useMemo:

// Outside the component: the same function on every render.
const withTheme = (children: React.ReactNode) => (
<ThemeProvider>{children}</ThemeProvider>
);

export default function Page() {
const [value, setValue] = useState(() => createDocument());

return (
<Live>
<Live.Dnd value={value} onChange={setValue} provider={withTheme} />
</Live>
);
}

A provider that depends on state still works; pass it through useCallback with that state as a dependency, and sections re-render when the state changes.

frame and modules are compared by value, so writing them inline is fine. For modules that means its entries, each by reference: an entry that is a new object or function on every render, such as modules={{ theme: { useTheme } }}, compiles every section again on every render, which also resets the document's top-level variables. Define such values outside the component.

A provider that holds its own state gets one copy of it per section, since it's called once per section. See State across sections.

Passing a set of props together​

Live.Dnd's props are flat, one per option. To set several in one place, such as the ones that shape the panel, build one object and spread it:

import { metaPanelLayout } from '@jbpark/live-editor/dnd';
import { uiKitFields } from '@jbpark/live-editor/ui-kit';

// Outside the component, so `bindings` and `bindingKeys` keep their identity.
const PANEL_OPTIONS = {
renderField: uiKitFields,
panelLayout: metaPanelLayout,
bindings,
bindingKeys,
onUpload: uploadImage,
};

<Live.Dnd value={value} onChange={setValue} {...PANEL_OPTIONS} />;

The object needs no stable identity itself; each prop is compared as above. Keep it outside the component anyway when it holds bindings or bindingKeys, which re-read every section when they change.