Embed Mica in a host application
A host is any React application that renders a Mica document for real
people. The host keeps everything Mica deliberately does not own: routing,
sign-in, its own state, its services and its styling. This guide builds a host
step by step; every snippet follows examples/mock-host, the complete reference
consumer in the Mica repository.
Add the dependency
Section titled “Add the dependency”Mica is not published to the npm registry — the package called mica there is
unrelated. You need a checkout of the Mica repository; depend on it by path, the
way the reference host does:
{ "dependencies": { "mica": "file:../path/to/mica", "react": "^19.1.1", "react-dom": "^19.1.1" }}Import only the two public entry points:
import { JSONUIProvider, Renderer /* … */ } from "mica/runtime";import "mica/runtime.css";mica/runtime resolves to the TypeScript source under a bundler’s
development condition (so vite dev and vitest need no build step) and to
dist-lib/runtime.js otherwise. Run npm run build:lib in the Mica repository
before a production build or a tsc typecheck of the host. React, json-render,
Zod and lucide-react stay external to that build, so the host’s own copies run.
Load the document
Section titled “Load the document”Validate any document you did not write yourself with parseDocument. It runs
every check the designer’s import runs and tells you which pack to render with:
import { parseDocument, type MicaDocument, type MicaPack } from "mica/runtime";
const result = parseDocument(jsonFromYourStorage);if (!result.ok) throw new Error(result.error);const document: MicaDocument = result.spec;const pack: MicaPack = result.pack;The reference host’s document is written in TypeScript and declares
hostActions.createLead, so it passes parseDocument. A document authored in
the designer always does too.
parseDocument stops at the first problem. To show or log every problem at
once — for a document a tool generated, say — call listDocumentIssues with the
same JSON; its first entry is the error parseDocument returns. See
using the functions.
Render it
Section titled “Render it”A host composes four pieces around the document:
import { useRef, useState } from "react";import { JSONUIProvider, PackSurface, PageProvider, Renderer, createListHandlers, createValidateHandler, createStateStore, goToPageHandler, micaDirectives, preflightLocalActions,} from "mica/runtime";
export function MicroApp({ document, pack }: { document: MicaDocument; pack: MicaPack }) { const [store] = useState(() => createStateStore(structuredClone(document.state ?? {}))); const [page, setPage] = useState<string | undefined>(undefined); const pageRef = useRef(page); pageRef.current = page; const [handlers] = useState(() => ({ ...createListHandlers({ document, store }), ...createValidateHandler({ document, store, activePageKey: () => pageRef.current }), goToPage: goToPageHandler(document, setPage), })); const local = preflightLocalActions(document, handlers); if (!local.ok) { return <p role="alert">{local.issues.map((issue) => issue.message).join(" ")}</p>; }
return ( <PageProvider spec={document} activePageKey={page}> <JSONUIProvider registry={pack.runtimeRegistry} store={store} handlers={handlers} directives={micaDirectives}> <PackSurface pack={pack}> <Renderer spec={document} registry={pack.runtimeRegistry} /> </PackSurface> </JSONUIProvider> </PageProvider> );}createStateStoreholds the session’s state. Seed it with the document’s state and anything the host wants the document to read.PageProviderchooses the page by key. With no key it shows the first page; an unknown key renders an in-place message listing the valid keys. It also tells a$labelread which Choice it names, so keep it around a single-page document that uses one.createValidateHandler’sactivePageKeygetter must return that same key (a host that never navigates passes() => undefined).JSONUIProvidersupplies the store, the action handlers and the directives.setStateis built in;goToPage, the list actionsaddRowandremoveRow(createListHandlers),validate(createValidateHandler) and the object verbs come from the host.micaDirectivesadds$format, which shows a raw value as money, a date or a count,$calc, a display-only calculation such as an order total, and$exprfor a number or text formula in those same props (arithmetic, orifchoosing between values; comparisons only insideif’s condition; a boolean$expris refused in a display slot); without it a formula renders as raw JSON. A$calcor$exprresult never reaches your handlers, so recompute anything that counts from the raw inputs your verbs receive. ImportRendererfrommica/runtime(as above). It rewrites boolean$exprinvisibleand$condso Mica evaluates them. With json-render’s ownRenderer, the pack registry still hides avisibleformula, but a$condformula on Required, Disabled or Busy would always hold.PackSurfaceapplies the pack’s default theme, or thethemeyou pass it (see apply a theme);mica/runtime.cssstyles everything inside it, and nothing outside it.
Apply a theme
Section titled “Apply a theme”A theme gives a document your brand without changing the document. Mica builds it; your host stores it and chooses which one to use. A document never names a theme.
Build a theme from what someone chose, and store its JSON wherever you keep documents:
import { createTheme } from "mica/runtime";
const theme = createTheme({ name: "Northwind", brand: "#3159b8", mode: "light", fonts: { body: "Inter" }, radius: "large",});await saveTheme(workspaceId, JSON.stringify(theme)); // your storageThe designer’s Export theme writes the same JSON, so a theme someone made
in the Theme panel can be
stored as it is. examples/mock-host keeps its chosen theme this way and
reads it back through parseTheme.
createTheme throws an Error naming the first value it refuses, so a theme
editor can show it beside the field. It is fast enough to run on every
keystroke. The JSON is { micaTheme: 1, id, source, tokens }. source holds
what was chosen, and tokens holds every value derived from it. id comes from
source, written one way with defaults left out, so the same choices always
give the same id.
Load a stored theme with parseTheme and pass it to PackSurface:
import { PackSurface, parseTheme, type MicaTheme } from "mica/runtime";
const result = parseTheme(await loadTheme(workspaceId));const theme: MicaTheme | undefined = result.ok ? result.theme : undefined;
<PackSurface pack={pack} theme={theme}> <Renderer spec={document} registry={pack.runtimeRegistry} /></PackSurface>- Leave
themeout to render the pack’s default theme. parseThemechecks stored JSON as strictly asparseDocumentchecks a document. It refuses unknown keys, a missing or unknown token, a value that isn’t a colour, font, length or shadow of the expected form, anidthat doesn’t match itssource, a token that misses a contrast floor and JSON over 32,000 characters. It returns{ ok: false, error }with the reason. Each theme keeps the tokens it was stored with, so an upgrade to Mica’s generator never changes how a saved theme looks.- Any pack, any theme. A theme only sets the look, so the same theme works with Signal and Nocturne documents.
PackSurface sets data-mica-theme="<key>" on its element and adds that key’s
rules to a stylesheet it shares across every surface on the page. The key is
the theme’s id followed by a hash of its tokens, so a stored theme and one
regenerated from the same source with different tokens never share rules. It
writes each rule through the CSSOM (a constructable stylesheet the document
adopts, or insertRule on one empty <style> element in browsers without
constructable stylesheets), never as <style> text, and removes them when the
last surface using that theme unmounts. Overlays, such as a combobox’s list and
a date picker’s popover, open inside the surface and take the scheme in effect
at the control that opened them.
A theme names font families; it never loads them. Load the families your
themes may use, by self-hosting the files with @font-face, for example. Any
family the page doesn’t have falls back to the role’s stack. Offer people
only the families you load.
Content Security Policy
Section titled “Content Security Policy”A theme needs no extra CSP source. Its rule is written through the CSSOM, and
no theme value can include a URL, so a theme never fetches anything. The
pack’s default theme is still an inline style attribute on the surface. If
your policy refuses inline styles, pass a theme: that is enough, since CSP does
not govern a constructable stylesheet. Browsers without them (before Safari
16.4 and Firefox 101) fall back to a <style> element, which such a policy
blocks; PackSurface then writes no rule, so to reach those browsers also
serve the rule as a file.
If you want the rule as a file, for those browsers or to preload it,
themeCss(theme) returns those rules as text: the token rule, then a rule for
each scheme an opaque container restores. Serve the whole string. A stylesheet
insert takes one rule, so split on each top-level block the way PackSurface
does. themeKey(theme) returns the key the rules match. The file only adds to
what PackSurface does; still pass it the theme, since it sets that key as the
surface’s data-mica-theme, and without a theme it writes the pack’s defaults
inline, which win over a served file.
Choose the locale
Section titled “Choose the locale”micaDirectives formats in the browser’s locale. To format in the locale your
app has chosen, create the directives once with createMicaDirectives:
import { createMicaDirectives } from "mica/runtime";
// Once, at module scope or in useState — JSONUIProvider rebuilds its// directive registry whenever the array changes.const directives = createMicaDirectives({ locale: "de-DE" });locale is a BCP 47 tag, or a list of them with the preferred one first.
createMicaDirectives throws on a malformed tag, so a typo fails at setup
rather than on every formatted value. The reference host passes "en-US".
Route pages
Section titled “Route pages”Mica never touches the URL. The host maps its own routing state to a page key and turns navigation intents back into route changes. The reference host uses the URL hash:
function pageKeyFromHash(): string | undefined { const route = window.location.hash.replace(/^#\/?/, ""); return route ? decodeURIComponent(route) : undefined;}
const [activePageKey, setActivePageKey] = useState(pageKeyFromHash);const navigate = useCallback((pageKey: string) => { window.location.hash = `/${encodeURIComponent(pageKey)}`;}, []);
useEffect(() => { const followHash = () => setActivePageKey(pageKeyFromHash()); window.addEventListener("hashchange", followHash); return () => window.removeEventListener("hashchange", followHash);}, []);
// …goToPage: goToPageHandler(document, navigate)goToPageHandler(document, onNavigate) checks the target against the
document’s pages and throws for an unknown one; for a valid one it calls
onNavigate(pageKey). A single-page document needs no routing wiring at all.
Give the document host data
Section titled “Give the document host data”Anything the host puts in the store is readable with $state, even paths the
document never declared. The reference host seeds a /host namespace:
createStateStore({ ...document.state, host: { greeting: "Welcome back, Northwind Robotics", account: { plan: "growth" } },});and its document shows { "$state": "/host/greeting" } in a Heading. Keep host
values out of /mica, which is reserved, and out of /objects and /meta once
the document declares business objects.
Add your own actions
Section titled “Add your own actions”Declare the verb on the document, then implement the handler. The reference
host declares hostActions.createLead and registers a function of the
action’s params:
createLead(params) { const id = `lead_${String(params.name).trim().toLowerCase().replace(/[^a-z0-9]+/g, "-")}`; store.set("/host/lastCreatedLeadId", id); return { ...params, id };}Call preflightHostActions(document, handlers) so a missing handler fails
before render, and preflightLocalActions(document, handlers) when the
document dispatches validate so a missing check cannot fail open. A host
action may not be named validate: that is a Mica verb, refused at import.
Prefer the business-object verbs when
the thing is a record; use a host action when the host owns a named verb that
is not fetch, create, update or delete of a declared type.
In the designer, Load host action catalog on the Objects view, then
Declare an entry, puts that verb on a Button’s Events action list.
Each declared parameter has a structured editor: Value, State path, or
inside a template Row field. An enum parameter is a dropdown; a required
one that is not yet set starts on a disabled Choose…. Optional true/false
and enum parameters offer Not supplied; leave an optional text or number
box empty to omit it. $expr is refused in host-action params.
Log what happens
Section titled “Log what happens”registerActionObserver reports every dispatch and settle. Pair it with
objectRejectionReason to say why an object action stopped:
useEffect(() => registerActionObserver({ onSettle: (event) => { const reason = objectRejectionReason(event.error); // "busy" | "cancelled" | "failed" | "stale" | "superseded" | null console.log(event.name, event.ok ? "ok" : reason ?? "failed"); },}), []);The observer is global to the page, not to one provider.
Implement business objects in a host adds the declared-object half: binding, preflight, seeding, startup and the write confirmation.