Skip to main content

Utilities

@jbpark/live-editor/utils holds helpers for working with a document outside the editor: reading and replacing its sections, checking it before you save or load it, and managing the caches the editor keeps. The AST helpers a custom panel uses (extract, update, validateBindingValue, ...) are in @jbpark/live-editor/utils/ast, and Custom Palette & Panel describes them.

Documents​

A document is the code Live.Dnd edits: a component that renders a container element holding the sections, as Document structure describes.

import {
checkDocument,
createDocument,
extractSections,
replaceSections,
} from '@jbpark/live-editor/utils';

const code = createDocument();
const sections = extractSections(code); // [{ id, name, code }, ...]
const next = replaceSections(code, [
...sections.map(section => section.code),
'<section data-name="Contact"><p>Write to us</p></section>',
]);
FunctionReturnsWhat it does
createDocument(options?)stringAn empty document with the container and no imports. Start a controlled Live.Dnd from it. See Document structure.
extractSections(code, options?)Section[]The container's sections, each { id, name, code }. [] when the code doesn't parse or has no container.
replaceSections(code, codes, options?)stringThe document with its sections replaced by codes, in order. Everything outside the container is kept as written.
checkDocument(code, options?)DocumentCheckWhether Live.Dnd can edit the document. See below.

replaceSections keeps the markup between sections, such as wrappers and comments, where it is. When the sections have data-ids, a reorder moves only the sections whose order changed, and each one lands next to the section before it in the new list. When two neighbors swap, the later one is the one that moves.

Every function takes { containerId } when your container isn't the default id="app-container". Pass the same id you give Live.Dnd.

Checking a document​

checkDocument tells you why Live.Dnd couldn't edit a document, before you save it or after you load it. These are the same reasons Live.Dnd reports through onEditError:

type DocumentCheck =
| { ok: true }
| { ok: false; reason: 'parse-error'; error: unknown }
| { ok: false; reason: 'container-not-found'; containerId: string };
const check = checkDocument(code, { containerId: 'root' });

if (!check.ok && check.reason === 'container-not-found') {
// The document has no element with id="root".
}

Serving a saved document​

Live.Preview compiles a document in the browser, which puts Babel on the page: compile from @jbpark/live-editor/utils adds about 2.3 MB (560 KB gzip) to a bundle. A page that only shows saved documents can skip it by transpiling once, when the document is saved, and running the result:

StepFunctionNeeds Babel
Turn the source into plain JavaScripttranspile(code) from @jbpark/live-editor/utilsYes
Run that JavaScript and get the componentrunModule(js, modules) from @jbpark/live-editor/runtimeNo (0.3 KB gzip)

compile(code, modules) is the two in one. For the default palette document (9 sections, 31.6 KB), transpiling takes about 50 ms in Chromium and running the result well under 1 ms.

// On save, on your server or in a build step
import { transpile } from '@jbpark/live-editor/utils';

const { code: js, error } = transpile(document);

if (error) {
throw new Error(error); // Babel's message, with the line and column
}

await db.pages.save({ source: document, js });
// The page that shows it
import { runModule } from '@jbpark/live-editor/runtime';

// The same `modules` the editor gave the document, defined once.
const MODULES = { ...uiKitModules, actions };

const SavedPage = ({ js }: { js: string }) => {
const { exports, error } = useMemo(() => runModule(js, MODULES), [js]);
const Page = exports.default;

return error || !Page ? <p>This page couldn't be shown.</p> : <Page />;
};
  • Store the source too: the editor edits the source, and you transpile again after each save.
  • runModule works on the server as well, so the page can be rendered with renderToString and hydrated with the same js.
  • The transpiled code runs with the page's privileges, as anything compile() runs does. Serve one author's documents to other people from a separate site; see Showing documents to visitors.
  • Styles aren't part of the module. If the document uses Tailwind classes, build their CSS on save as well, or serve the page with your own Tailwind build.

Caches​

The editor caches compiled modules, fetched scripts and parsed documents for the whole page. Live clears them when its last instance unmounts, so most apps never call these.

FunctionWhat it clears
clearEditorCaches()Every page-wide cache: compiled modules, script blobs (their blob URLs are revoked), parsed documents and extracted bindings.
clearCompilationCache()Compiled modules only. Clearing doesn't re-render anything: a component compiles again the next time it renders.

Scripts​

preloadScripts(urls) starts fetching scripts you'll pass as frame.scripts, so the first preview doesn't wait for them. It doesn't throw: a failed fetch is retried, and reported, when a preview loads the script.

Class names​

cn(...classes) joins class names and merges conflicting Tailwind classes (clsx with tailwind-merge), the way the editor's own components do.

Removed in 5.0​

These internal helpers were exported from ./utils and ./utils/ast until 4.x, deprecated since 4.5.0. 5.0 removed them. If your code imports one, use the replacement below.

NamesUse instead
appendArrayItem, duplicateArrayItems, moveArrayItem, moveArrayItems, removeArrayItems, updateArrayItemProperty, updateArrayItemValue, parseItems, parseArrayExpression, arrayExpressionToCode, canStructurallyEditArray, ArrayItem, ItemKinduseDndItems from ./dnd
extractNodeValue, extractObjectProperties, getCurrentValue, getStructuredValue, createNodeFromValue, canLosslesslyEvaluateSource, ExtractedNodeValue, NodeValueType, EditableNodeValueTypeextract, update, and PanelBinding's value, onChange and canEditValue
parseBinding, parseBindingExpression, readNodeBindings, resolveBindings, getKeyBindings, getRegistryBindings, isComponentTagNameextract(source, { bindings, bindingKeys }) or useDndPanel().bindings
parseDocument, getSections, replaceDocumentSections, inspectDocument, DocumentInspectionextractSections, replaceSections, checkDocument
generateDocumentCode, fillSectionIds, generateSectionPreview(s), createSectionPreviewCache, SectionPreviewCache, DocumentTree, generateSection(s)Nothing. Live.Dnd does this itself.
fillIds, replaceIds, clone, generateCodeNothing
clearExtractCache, clearDocumentParseCache, clearScriptCacheclearEditorCaches
transformCode, detectTypeScriptcompile
bulkUpdateupdateAll, which applies every entry or none
registerEditorSession, getCachedScriptBlobNothing. Live registers its session; use preloadScripts.

5.0 also removed the earlier names of the ./dnd hooks and types: useItemsEditor and useChildrenEditor are useDndItems and useDndChildren, and the ItemsEditor* and ChildrenEditor* types are DndItems* and DndChildren*.