React pages
A page, a slot or a cell can be a React component that renders inside the panel: on its React, its React Query client, its UI kit, theme, language and router. This is the extension host API v2. Use it for interactive tools (dashboards of a service, editors, multi-step flows) that a server template cannot draw. Plain scripts (Customizing the panel, v1) keep working.
A RustCMS demo application: the React demo page.
Quick start
rustcms make:page StatsPage --react
cd resources/admin && npm install && npm run build # Node ^20.19.0 or >=22.12.0
rustcms permission:syncmake:page StatsPage --react (--react and --script exclude each other) writes, for an application whose package is blog:
src/admin/pages/stats_page.rs, aPanelPagewithPageView::Script("blog/stats")and the permissionstats.view;resources/admin/src/blog/stats.tsxandstats.css(your sources);placeholders for the built
resources/admin/js/blog/stats.jsandcss/blog/stats.css, so the application compiles before the first build;in the admin provider:
rust.extension_script_v2("stats", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/admin/js/blog/stats.js")), rustcms::admin::Requires { react: "19.3", react_query: "5.104", ui: 6 }) .extension_style("stats", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/resources/admin/css/blog/stats.css")))the first time only:
resources/admin/package.json,tsconfig.json,.gitignoreand the SDK inresources/admin/sdk. Existing files are never overwritten.
The vendor (blog) is your package name with _ replaced by -. The generated component:
// resources/admin/src/blog/stats.tsx
import { type PageProps, registerPage, useAdminQuery } from "@rustcms/admin-sdk";
import { Card, CardContent } from "@rustcms/admin-sdk/ui";
import "./stats.css";
type Data = { user: string };
function StatsPage(props: PageProps<Data>) {
// Your `AdminRoutes` under `{admin}/api/x` (e.g. `.get("/stats", …)`):
// const items = useAdminQuery<Item[]>(props, "/stats");
void useAdminQuery;
return (
<Card>
<CardContent className="stats-body">
<p>
{props.t("Signed in as user")} {props.data.user}
</p>
{props.path && <p>{props.path}</p>}
</CardContent>
</Card>
);
}
registerPage("blog/stats", StatsPage);Until it is built, the page shows "unavailable"; the application still compiles.
Commit the build
Commit the built js/ and css/ files, package-lock.json and .rustcms-build.json. The Rust build reads the built files with include_str!, so cargo build and deployments need no Node.
npm run build (the SDK's rustcms-build) builds every src/<vendor>/<name>.tsx into js/<vendor>/<name>.js and css/<vendor>/<name>.css. An entry without styles gets an empty CSS file, so include_str! always finds one. .rustcms-build.json lists what the build wrote, so the outputs of a removed entry are deleted at the next build (never hand-written scripts beside them). A second page is a second file. The build uses the SDK's Vite preset, rustcmsExtension({ entry, root }) from @rustcms/admin-sdk/vite.
Full example
The demo's React page reads a sub-path in data:
pub struct ReactPage;
#[async_trait]
impl PanelPage for ReactPage {
const SLUG: &'static str = "react-demo";
fn meta() -> PanelPageMeta {
PanelPageMeta::new("React demo").icon("layers").group("Content").permission("demo.live")
}
fn view() -> PageView {
PageView::Script("demo/react")
}
async fn data(ctx: &Ctx) -> AppResult<Value> {
// The sub-path (`items/2`) is canonical; this page's permission covers it.
Ok(json!({
"path": ctx.page_path(),
"items": [{ "id": 1, "name": "First" }, { "id": 2, "name": "Second" }],
}))
}
}and registers the built script:
// The React demo page and the categories' swatch entry (v2, built by
// `npm run build` in resources/admin).
.extension_script_v2(
"demo-react",
include_str!("../../resources/admin/js/demo/react.js"),
Requires { react: "19.3", react_query: "5.104", ui: 6 },
)
.extension_style("demo-react", include_str!("../../resources/admin/css/demo/react.css"))Its tag list reads and writes the tags resource with the panel's rules (policy, validation, audit), and shows toasts:
/** Tags through the resource API: the panel's policy, validation and audit apply. */
function Tags(props: PageProps<Data>) {
const tags = useResource<Tag>(props, "tags", { query: { per_page: "100" } });
const create = useResourceMutation(props, "tags", "create", {
onSuccess: () => {
setName("");
props.toast.success(props.t("Tag created"));
},
});
const remove = useResourceMutation(props, "tags", "delete", {
onSuccess: () => props.toast.success(props.t("Tag deleted")),
});
const [name, setName] = useState("");
const errors = fieldErrors(create.error);
return (
<div className="demo-react-tags">
<form
className="demo-react-row"
onSubmit={(e) => {
e.preventDefault();
// As the panel's forms: an empty text is no value (`required` refuses it).
create.mutate({ data: { name: name.trim() === "" ? null : name } });
}}
>
<Input aria-label={props.t("Tag name")} value={name} onChange={(e) => setName(e.target.value)} />
<Button type="submit">{props.t("Add tag")}</Button>
<Tooltip content={props.t("Read the tags again")}>
<Button type="button" variant="ghost" onClick={() => void tags.refetch()}>
{props.t("Refresh")}
</Button>
</Tooltip>
</form>
{errors.name && <p role="alert" className="demo-react-error">{errors.name.join(" ")}</p>}
<ul className="demo-react-list">
{tags.data?.data.map((tag) => (
<li key={tag.key} className="demo-react-row">
<span>{tag.data.name}</span>
<DropdownMenu trigger={props.t("Actions")} aria-label={`${props.t("Actions")} ${tag.data.name}`} variant="ghost">
<DropdownMenuItem onSelect={() => props.navigate(`/r/tags/records/${tag.key}`)}>{props.t("Open")}</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem destructive onSelect={() => remove.mutate({ key: tag.key })}>
{props.t("Delete")}
</DropdownMenuItem>
</DropdownMenu>
</li>
))}
</ul>
</div>
);
}A live counter from an event stream:
useEvents(props, "/demo/ticks", {
onEvent(name, data) {
if (name === "tick") setCount((data as { count: number }).count);
},
});The component
Register with registerPage, registerSlot, registerCell, (from ui 3) registerEntry or (from ui 6) registerField and the name of the Rust side (PageView::Script("…") of a page or slot, .cell("…") of a column, CustomEntry::make(field, "…") of an infolist, the WIDGET of a virtual field). registerRichTextNode (ui 4) draws application elements. Within each kind (page, slot, cell or entry) a name is taken once, by v1 or v2.
Never call createRoot: the panel renders your component.
The panel's own modules are reached only through the imports the SDK's preset maps. @rustcms/admin-sdk itself (hooks and registration code) is bundled into your script, and so are other installed dependencies and your local modules. Other React, React DOM and React Query subpaths (react-dom/client, react/jsx-dev-runtime) and every dynamic import() fail the build.
| Import | What |
|---|---|
react, react/jsx-runtime | the panel's React |
react-dom | createPortal |
@tanstack/react-query | useQuery, useMutation, useQueryClient, useInfiniteQuery |
@rustcms/admin-sdk | registerPage/Slot/Cell/Entry, registerRichTextNode (ui 4), registerField (ui 6), the hooks below, the prop types, RichDocument and MediaItem |
@rustcms/admin-sdk/ui | Alert, Badge, Button, buttonVariants, Card, CardContent, CardHeader, CardTitle, Checkbox, Switch, Dialog, Input, Label, NativeSelect, Textarea, Page, PageHeader, Loading, ErrorState, cn; and from ui 2: Tabs*, DropdownMenu*, Tooltip, Table*, Skeleton, Separator, CodeBlock; and from ui 3: Infolist (below); and from ui 5: RichEditor, RichTextView, MediaField, MediaPicker, MediaThumb, useImageViewer, useMediaAccess, useMediaUpload, FormField, FieldError, RepeaterRow, IconButton (form widgets) |
@rustcms/admin-sdk/host | ApiError (status, code, fieldErrors, formErrors, maybeApplied), versions ({api, react, reactQuery, ui}) |
Props
| Page | Slot | Cell | |
|---|---|---|---|
data (frozen copy of data()) | ✓ | ✓ | value |
record | ✓ | ✓ | |
slug, path, search | ✓ | ||
slot, resource, recordKey | ✓ | ||
props (the cell's) | ✓ | ||
locale, t, scope, can | ✓ | ✓ | ✓ |
navigate, reload, api, realtime | ✓ | ✓ | |
resources, toast (ui 2) | ✓ | ✓ | |
title (ui 2) | ✓ |
t(text)translates with the catalogs ofregisterTranslations(Languages).can(permission)is true when the user holds that admin permission. It only hides buttons: the server checks every request.navigate("/p/stats/items/2")opens a panel path.- Cells are drawn once per row of a list: they get no API client, streams or navigation, only the value, the record and their props. Fetch what a whole list needs in a page.
Calling your routes
props.api.get/delete(path, { query }?) and props.api.post/put/patch(path, body?, { query }?) call your admin routes under {admin}/api/x, with the session and CSRF token. Paths start with one / (/blog/posts); .., //, ?, #, encoded slashes and double encoding are refused before anything is sent. Errors are ApiError (status, code).
Hooks wrap them with React Query:
useAdminQuery(props, path, { query, ...options }): cached per view, user and language.useAdminMutation(props, path, method): on success, refetches the view's queries. Writes are never retried automatically: if the outcome of a write is unknown (the connection dropped), the panel's "paused" banner asks the user, and the view's next writes wait.useEvents(props, path, handlers)anduseSocket(props, path, handlers, { reconnect })open a stream or socket while mounted.useSocketreturns{ send }.useColorScheme()returns"light"or"dark"and re-renders when the user or the system changes it, e.g. to redraw a canvas chart. CSS needs nothing: the theme's variables follow it. It reads the panel'sdata-scheme, so it works on any 0.6 panel.
When the session changes (sign-in, sign-out, another tab), the view is mounted again for the new session; calls and callbacks of the old one do nothing (a call rejects with ApiError code session_changed). A refused CSRF token also ends the session state, so that call rejects the same way. A read (api.get, resources.list/get) answered after its view was mounted again in the same session (a sub-path navigation) is delivered: its query cache entry, shared with the new view, gets the data instead of an error. Writes answered late still reject.
Records of your resources
With ui: 2 in Requires, props.resources reads and writes the records of your resources through the panel's own routes, so their policy, scope(), field rules, validation, audit log and encrypted fields apply. The demo's Tags component above uses it.
| Hook / method | |
|---|---|
useResource(props, slug, { query, ...options }) | a page of records: { data: [Envelope], meta: { page, perPage, total, lastPage } } |
useRecord(props, slug, key, options?) | one record |
useResourceMutation(props, slug, op, options?) | op: create {data}, update {key, data}, delete, restore, forceDelete {key}, action {name, keys, data?} |
fieldErrors(error) | the field errors of a refused write (422): { field: [messages] } |
props.resources.list/get/create/update/delete/restore/forceDelete/action | the same without React Query |
props.resources.track(slug) | marks a resource as used by the view (its paused-write banner shows there; the hooks do it) |
An Envelope is { key, title?, abilities, data, trashed?, labels? }.
- Values use the panel's wire format: 64-bit integers and decimals as strings.
props.resourcessends values unchanged: sendnullto clear a field (or to leave arequiredone empty, which it refuses); an empty string stays an empty string. - Updates send the changed fields, and the last write wins. Encrypted maps answer
409 secret_stalewhen they changed meanwhile. On a 409 or 422, keep the user's draft. - Lost answers: a write whose answer was lost pauses that resource's writes, in your view and in the resource's own pages. Both show the banner; creates and actions can be retried safely there. Writes are never retried automatically.
- Refreshing: after any write to a resource, every view reading it refetches, the built-in lists included.
- Validation: slugs, action names and keys a URL could change (
.,..) are refused before anything is sent.
Lower-level helpers, for your own React Query calls: adminKey(props, path, query) and resourceKey(props, slug, …) (the query keys the hooks use), queryPairs(query) and SDK_UI (the ui level the SDK is built for, 6).
Toasts
props.toast.success(text) and props.toast.error(text) (ui 2) show a message in the panel's corner:
- a success for 5 s, an error for 8 s; at most 5 at a time (the oldest goes first); text is cut at 500 characters;
- announced to screen readers;
- kept when the user leaves the page, dropped when the session changes.
Page titles
props.title(text) (ui 2, pages) names the current sub-path in the panel's heading and breadcrumb; props.title(null) hides the heading (it stays for screen readers) when the page draws its own:
// The sub-path names itself in the panel's heading and breadcrumb.
useEffect(() => {
if (props.path === "tags") props.title(props.t("React demo: tags"));
}, [props.path, props.title, props.t]);A title holds for the sub-path it was set on: on another one the page's own title shows again until it is set there too. It ends with the view and with the session.
Components
ui 2 adds:
Tabs(controlled): with sub-paths,<Tabs value={props.path || "overview"} onValueChange={(v) => props.navigate("/p/x/" + v)}>, thenTabsList aria-label=…,TabsTrigger value=…andTabsContent value=….DropdownMenu trigger="Actions"withDropdownMenuItem onSelect destructive disabled,DropdownMenuSeparatorandDropdownMenuLabel. The keyboard works, and Escape returns to the button.Tooltip content="…"around one element.Table,TableHeader,TableBody,TableRow,TableHeadandTableCell, styled like the panel's lists.Skeleton,Separator, andCodeBlock code="…"(with a copy button).
ui 3 adds Infolist schema={…} data={…}: entries drawn as a record's view page draws them (Infolists), for example from a panel page's PageView::Infolist schema.
Menus and tooltips work inside a Dialog. Every Dialog has a close button (×, "Close") in its top right corner, after your content, so opening still focuses your first field; closeButton={false} leaves it out, and closeDisabled disables it and Escape (for example while saving). Since ui 5, footer={…} puts buttons at the bottom that stay in view while the content above them scrolls, and size sets the width (sm, md (the default), lg or xl).
Form widgets
ui 5 gives extensions the widgets of the panel's forms, so an editor of your own (a dialog, a page) looks and behaves like a form and follows the panel when it changes. They are controlled (value and onChange) and only edit: save through your own route, where the server checks what it receives (AppNodes::parse_for for rich text, the media rules for files).
/**
* The forms' widgets (ui 5) in an extension's own editor: the posts'
* content editor (its elements, formulas and image library), a media field,
* field frames and repeater rows. Nothing here is saved: an extension saves
* through its own route, where the server checks what it receives.
*/
function Widgets(props: PageProps<Data>) {
const [doc, setDoc] = useState<RichDocument | null>(null);
const [image, setImage] = useState<string | string[] | null>(null);
const [options, setOptions] = useState(["", ""]);
const [preview, setPreview] = useState(false);
const move = (from: number, to: number) => {
const next = [...options];
next.splice(to, 0, next.splice(from, 1)[0]!);
setOptions(next);
};
return (
<Card>
<CardContent className="demo-widgets">
<FormField id="demo-body" label={props.t("Content")} help={props.t("The editor of a post's content: its elements and formulas.")}>
{(aria) => (
<RichEditor id="demo-body" label={props.t("Content")} value={doc} onChange={setDoc} toolbar="compact"
field={{ resource: "posts", name: "content" }} describedBy={aria["aria-describedby"]} />
)}
</FormField>
<FormField id="demo-image" label={props.t("Image")} required error={image ? undefined : props.t("Choose an image.")}>
{(aria) => (
<MediaField id="demo-image" label={props.t("Image")} value={image} onChange={setImage}
rules={{ accept: ["image/*"], collection: "post-content" }} invalid={!!aria["aria-invalid"]} describedBy={aria["aria-describedby"]} />
)}
</FormField>
<ol className="demo-options">
{options.map((option, index) => (
<li key={index}>
<RepeaterRow title={`${props.t("Option")} ${index + 1}`}
onMoveUp={index > 0 ? () => move(index, index - 1) : null}
onMoveDown={index < options.length - 1 ? () => move(index, index + 1) : null}
onRemove={options.length > 1 ? () => setOptions(options.filter((_, i) => i !== index)) : undefined}>
<FormField id={`demo-option-${index}`} label={props.t("Text")}>
<Input id={`demo-option-${index}`} value={option}
onChange={(e) => setOptions(options.map((o, i) => (i === index ? e.target.value : o)))} />
</FormField>
</RepeaterRow>
</li>
))}
</ol>
<div>
<Button variant="outline" onClick={() => setOptions([...options, ""])}>{props.t("Add an option")}</Button>{" "}
<Button onClick={() => setPreview(true)}>{props.t("Preview")}</Button>
</div>
<Dialog open={preview} onClose={() => setPreview(false)} title={props.t("Preview")} size="lg"
footer={<Button onClick={() => setPreview(false)}>{props.t("Close")}</Button>}>
{doc ? <RichTextView doc={doc} field={{ resource: "posts", name: "content" }} /> : <p>{props.t("Nothing written yet.")}</p>}
</Dialog>
</CardContent>
</Card>
);
}
RichEditor: the forms' rich text editor, with its toolbar (toolbar="compact"as in repeater rows), formulas, image library, uploads and paste rules.valueis a document ornull(none; erasing everything givesnull); documents are written in the lowest version they need.field=borrows that field's application elements and media collection, read from the resource's schema as its forms read it (the create form, else the view page); without it the editor takes no application element.collectionoverrides the field's.onBusyreports uploads in progress: do not save meanwhile.RichTextView doc={…} field={…}: a document as view pages show it.MediaField: the forms' media input (thumbnails, upload, the media library, remove, reorder, the image viewer).valueis an id ornull, or a list of ids withrules.multiple.rules:multiple,max(default 1, or 20 withmultiple),accept(["image/*"]),maxSize,preview,collection.MediaPicker(the library dialog alone),MediaThumb,useImageViewer(images)({ open(index), viewer }) anduseMediaAccess()({ library, upload }: hide what the user may not use).useMediaUpload()returnsupload(file, { collection, key })(key: your own idempotency key, default a new UUID), which uploads as the forms do: the session's CSRF token, one idempotency key for every attempt, at most two at a time among extensions' uploads (each form keeps its own count), a 429 sent again afterRetry-After, and never in another session than the one it was asked in (a sign-out and another sign-in while it waits rejects it withsession_changed). It resolves to the storedMediaItemand rejects with the server's error.FormField: a field's label (*withrequired), help and error, tied to the control with{id}-helpand{id}-error; give a function to receive the control'saria-invalidandaria-describedby.FieldErroris the error line alone.RepeaterRow: a row of a list edited in place, as repeaters draw it: title,actions, then move up, move down and remove. A move given asnullshows disabled (the first or last row); left out, it is not shown.IconButtonis its small named icon button.
The types RichDocument and MediaItem come from @rustcms/admin-sdk.
ui 6 adds registerField(name, { edit, view? }): the component of a virtual field, a field of a record's form without a column, saved by the application with the record.
Sub-pages
/admin/p/<slug>/<sub/path> opens the same page: props.path is "sub/path" ("" without one), and PanelPage::data reads ctx.page_path(). The page's permissions cover every sub-path; check more in data when some need it. A sub-path is up to 16 non-empty segments of A-Z a-z 0-9 . _ ~ - (. and .. are refused), at most 512 bytes as sent (one trailing slash is dropped). Anything else is "not found" in the panel and a 422 validation error on path from the API, after the permission checks.
Styles
The panel's stylesheet holds only the classes the panel uses. Put yours in the page's CSS file (imported by the TSX), with the theme's CSS variables so they follow light and dark mode: --background, --foreground, --card, --muted, --muted-foreground, --primary, --primary-foreground, --secondary, --border, --ring, --success, --warning, --destructive, --radius.
.stats-body { padding-top: 1.25rem; color: var(--muted-foreground); }The ui components carry their own styles. Styles are never injected at run time, so the panel's Content Security Policy stays strict.
Errors and compatibility
- A component that throws while rendering shows "unavailable" with Retry; other views are unaffected (a cell shows its plain value).
Requiresstates the React, React Query anduiversions the bundle was built against. A panel with another major, an older minor or a loweruidoes not load the script at all, and the console says why: rebuild with the SDK of that RustCMS version. Aui: 1bundle keeps working on newer panels.- A bundle built with the
ui3 SDK refuses to register on a panel belowui3, and a bundle whoseRequiresstill says an olderuiis refused at registration, with a message: update the provider. AdminProvider::extension_timeout(Duration)(1–60 s, default 10) bounds how long the panel waits for scripts to register.
Testing
npm run typecheck checks the sources against the SDK's types. Test the Rust side like any page (app.get("/admin/api/pages/stats/items/2")); end-to-end tests drive the built page in a browser.
Upgrading the SDK
rustcms upgrade warns when the version of resources/admin/sdk differs from the one the command carries (older or newer). Run rustcms make:sdk: it replaces the files you did not edit and lists the ones it kept, and the extension_script_v2 registrations whose Requires declare an older ui: set ui: 6 there. Then update package.json to the versions in Requires, run npm install && npm run build, and commit.
Security notes
- Every request goes through the server's checks:
can()only hides buttons, andprops.resourcesuses the panel's routes, soscope(), the policy and field rules apply (Authorization). - Extensions run with the user's session; ship only code you review. The panel's CSP is not loosened for them.
Related pages
- Customizing the panel: pages, slots, cells, v1 scripts
- Admin routes: the JSON endpoints your page calls
- Realtime:
useEvents,useSocket - Theming and branding