---
name: rebase-admin
description: Guide for navigating the Rebase admin panel, opening entities in side drawers, building URLs, embedding collection panels, using the collection registry, and programmatic navigation. Use this skill when an agent or user needs to navigate to a collection view, open an entity in the side panel/drawer, build admin URLs, embed a collection inside a custom page, use the entity selection dialog, or access admin-specific controllers.
---

# Rebase Admin (`@rebasepro/cms`)

The `@rebasepro/cms` package provides the admin-panel layer for Rebase. It handles collection views, entity editing, navigation, side panels (drawers), URL routing, breadcrumbs, and the full admin context. This skill covers the **programmatic APIs** for navigating and interacting with the admin.

> **IMPORTANT FOR AGENTS:** All hooks in this skill must be called **inside** the `<RebaseShell>` component tree. They rely on React contexts provided by `<RebaseNavigation>`, `<SidePanelProvider>`, and `<RebaseRouteDefs>`. In a page of your own app with no shell, a `CollectionsProvider` provides the collection, URL, side-panel and side-dialog controllers instead (0.25+, see §4).

> **Customizing the admin** — a settings page, a dashboard, a bulk action, an approval queue, a master-detail page, a new view mode, a replaced screen? Read the **`rebase-customize-admin`** skill first. It is one short page — building blocks, hooks, places — and points at tested recipes shipped in `node_modules/@rebasepro/cms/recipes`.

> **Building the view itself?** This skill covers navigation and admin plumbing. For what the view should *look* like, read the **`rebase-design-language`** skill first — custom views render inside the admin shell and must match it. It ships whole-view skeletons and points at the UI reference (`UIReferenceView`, from `@rebasepro/app/debug`).

## Quick Reference — Common Tasks

| Task | Hook / Component | Package |
|------|-----------------|---------|
| Open entity in side drawer | `useSidePanel()` | `@rebasepro/cms` |
| Navigate to a collection view | `useUrlController()` | `@rebasepro/cms` |
| Look up a collection by slug | `useCollectionRegistryController()` | `@rebasepro/cms` |
| Embed a collection in a custom page | `<CollectionPanel>` | `@rebasepro/cms` |
| One record's form in your own page | `<RecordForm>` | `@rebasepro/cms` |
| One record, read-only, in your own page | `<RecordDetail>` | `@rebasepro/cms` |
| One value of a row, drawn as the admin draws it | `<FieldValue>` | `@rebasepro/cms` |
| Add custom top-level views | `<RebaseCMS views={[...]}>` | `@rebasepro/cms` |
| Replace how one field is edited or shown | `fields: { <key>: { Field, Preview } }` in `customizeTable` | see §12 |
| Open an entity selection dialog | `useSelectionDialog()` | `@rebasepro/cms` |
| Open a custom side dialog | `useSideDialogsController()` | `@rebasepro/cms` |
| Set breadcrumbs | `useBreadcrumbsController()` | `@rebasepro/cms` |
| Access full admin context | `useAdminContext()` | `@rebasepro/cms` |
| Access navigation state & views | `useNavigationStateController()` | `@rebasepro/cms` |

---

## 1. Opening Entities in the Side Drawer

Use `useSidePanel()` to open, replace, or close entity side panels (the sliding drawer that shows entity forms).

```typescript
import { useSidePanel } from "@rebasepro/cms";
```

### SidePanelController Interface

```tsx
interface SidePanelController {
    /** Close the last (topmost) panel */
    close: () => void;

    /** Open a new entity side panel */
    open: <M extends Record<string, unknown>>(props: SidePanelBindingProps<M>) => void;

    /** Replace the last open panel with a new one */
    replace: <M extends Record<string, unknown>>(props: SidePanelBindingProps<M>) => void;
}
```

### SidePanelBindingProps

```typescript
interface SidePanelBindingProps<M extends Record<string, unknown> = Record<string, unknown>> {
    /** Absolute path of the entity's collection (e.g. "products") */
    path: string;

    /** Id of the record to open. Omit it to open the form for a new record. */
    id?: string | number;

    /** Set to true to create a copy of an existing entity */
    copy?: boolean;

    /** Open with a specific sub-collection tab selected */
    selectedTab?: string;

    /** Override the width of the form panel (e.g. "600px") */
    width?: number | string;

    /** Explicit collection config (auto-resolved from navigation if omitted) */
    collection?: AdminCollection<M>;

    /** Whether to update the browser URL when opening (default: true) */
    updateUrl?: boolean;

    /** Called after a save, with the saved record as the server sends the row */
    onSaved?: (params: { row: Record<string, unknown>; id: string | number }) => void;

    /** Callback when the panel is closed */
    onClose?: () => void;

    /** Close the panel automatically after saving */
    closeOnSave?: boolean;

    /** Override form properties */
    formProps?: Record<string, unknown>;

    /** Show a full-screen toggle button */
    allowFullScreen?: boolean;

    /** Pre-populate form values when creating a new entity (only when id is not set) */
    defaultValues?: Partial<M>;
}
```

### Examples

**Open an existing entity for editing:**
```tsx
const sidePanel = useSidePanel();

// Open the product with ID "abc123" in the side drawer
sidePanel.open({
    path: "products",
    id: "abc123"
});
```

**Create a new entity with pre-filled values:**
```tsx
sidePanel.open({
    path: "products",
    defaultValues: {
        name: "New Product",
        status: "draft"
    }
});
```

**Open with a callback on save:**
```tsx
sidePanel.open({
    path: "orders",
    id: orderId,
    closeOnSave: true,
    onSaved: ({ row, id }) => {
        console.log("Saved:", id, row);
    }
});
```

**Replace the current panel (instead of stacking):**
```tsx
sidePanel.replace({
    path: "clients",
    id: "xyz789"
});
```

---

## 2. Navigating to Collection Views

Use `useUrlController()` to build URLs and navigate programmatically within the admin.

```typescript
import { useUrlController } from "@rebasepro/cms";
```

### UrlController Interface

```typescript
type UrlController = {
    /** Base path for the admin (default: "/") */
    basePath: string;

    /** Base path for collection routes (default: "/c") */
    baseCollectionPath: string;

    /** Convert a URL path to a data path: "/c/products" → "products" */
    urlPathToDataPath: (cmsPath: string) => string;

    /** Base URL for the home screen */
    homeUrl: string;

    /** Check if a URL path belongs to a collection */
    isUrlCollectionPath: (urlPath: string) => boolean;

    /** Build a URL for a collection: "products" → "/c/products" */
    buildUrlCollectionPath: (path: string) => string;

    /** Build a URL for a custom view or app path */
    buildAppUrlPath: (path: string) => string;

    /** Resolve collection IDs in a path to database paths */
    resolveDatabasePathsFrom: (path: string) => string;

    /** Navigate to a route (wraps react-router's navigate) */
    navigate: (to: string, options?: NavigateOptions) => void;

    /** `false` under a `CollectionsProvider` (no CMS routes): records open over the page. Absent = routes mounted */
    routesMounted?: boolean;
};
```

### Examples

**Navigate to a collection view:**
```tsx
const urlController = useUrlController();

// Navigate to the "products" collection
const url = urlController.buildUrlCollectionPath("products");
urlController.navigate(url);
// This navigates to "/c/products"
```

**Navigate to a specific entity within a collection:**
```tsx
const url = urlController.buildUrlCollectionPath("products/abc123");
urlController.navigate(url);
// This navigates to "/c/products/abc123"
```

**Navigate to a custom view:**
```tsx
const url = urlController.buildAppUrlPath("my-dashboard");
urlController.navigate(url);
```

**Navigate and replace history (no back button):**
```tsx
urlController.navigate(
    urlController.buildUrlCollectionPath("orders"),
    { replace: true }
);
```

**Navigate to home:**
```tsx
urlController.navigate(urlController.homeUrl);
```

> **IMPORTANT FOR AGENTS:** The URL structure is `basePath + baseCollectionPath + "/" + slug`. By default this produces `/c/products`. Use `buildUrlCollectionPath()` instead of manually constructing URLs.

---

## 3. Collection Registry

Use `useCollectionRegistryController()` to look up registered collections by slug.

```typescript
import { useCollectionRegistryController } from "@rebasepro/cms";
```

### CollectionRegistryController Interface

```tsx
type CollectionRegistryController<
    DB = Record<string, unknown>,
    EC extends CollectionConfig = CollectionConfig
> = {
    /** All registered collections */
    collections?: EC[];

    /** Whether the registry is ready */
    initialised: boolean;

    /** Get a collection by slug or path */
    getCollection: <K extends keyof DB>(slugOrPath: Extract<K, string>, includeUserOverride?: boolean) => EC | undefined;

    /** Get the raw (un-normalized) collection config — for the Visual Editor only */
    getRawCollection: (slugOrPath: string) => EC | undefined;

    /** The path a collection's rows are stored under, for the path the admin addresses it by */
    resolveDataPath: (path: string) => string;

    /** The inverse of resolveDataPath: the admin path for a stored path */
    resolveCollectionPath: (path: string, preferredDriver?: string) => string;

    /** Get all parent entity references for a path */
    getParentReferencesFromPath: (path: string) => EntityReference[];

    /** Get parent collection slugs for a path */
    getParentCollectionSlugs: (path: string) => string[];

    /** Get parent entity IDs for a path */
    getParentEntityIds: (path: string) => string[];

    /** Resolve IDs to paths */
    convertIdsToPaths: (ids: string[]) => string[];
};
```

### Example

```tsx
const registry = useCollectionRegistryController();

// Check if a collection exists
const products = registry.getCollection("products");
if (products) {
    console.log("Collection name:", products.name);
    console.log("Fields:", Object.keys(products.properties));
}

// List all collections
registry.collections?.forEach(c => {
    console.log(c.slug, c.name);
});
```

---

## 4. Embedding Collections with CollectionPanel

`CollectionPanel` is a high-level wrapper for embedding collection views inside custom pages (dashboards, home pages, entity detail views). Name the collection by `path` (registered with `<RebaseCMS>`), or hand it over as a value with `collection` (0.25+) — then it works in a page of your own app too, with no CMS around it (see *Outside the CMS* below).

```typescript
import { CollectionPanel } from "@rebasepro/cms";
```

### CollectionPanelProps

```typescript
type CollectionPanelProps = {
    /** The collection: its name ("tasks"), registered with RebaseCMS or a
     *  CollectionsProvider, or the collection as a value */
    collection: AdminCollection | string;

    /** Where the rows live, where that is not the collection's name: a
     *  subcollection's full path ("posts/p1/comments") */
    path?: string;

    /** Title above the collection. `false` to hide. Defaults to collection name. */
    title?: string | false;

    /** The view mode it opens in, over the URL's and the one the person saved; they can still switch */
    viewMode?: ViewMode;

    /** The order the rows open in: "field:desc" or ["field", "desc"] */
    orderBy?: `${string}:asc` | `${string}:desc` | [string, "asc" | "desc"];

    /** Which rows it holds, as useRows' where; follows the prop */
    where?: FilterValues<string>;

    /** Max entities to display */
    limit?: number;

    /** Sync filter/sort with URL params (default: false) */
    updateUrl?: boolean;

    /** Entity open mode when clicking */
    openEntityMode?: "side_panel" | "full_screen" | "split" | "dialog";

    /** Container CSS class */
    className?: string;

    /** Additional collection-level overrides */
    collectionOverrides?: Partial<AdminCollection>;

    /** The ids of the rows drawn as selected; `[]` for none. Default: the row last opened */
    highlightedIds?: (string | number)[];

    /** Only these fields, in this order: the table's columns, and what list rows,
     *  cards and kanban cards are filled from. Wins over the customization's
     *  fieldOrder, the saved order and listFields for this panel */
    fields?: string[];

    /** The toolbar: "full" (default), "compact" (search, view switch, New),
     *  "none", or composed of CollectionToolbar (start/end), CollectionSearchBar,
     *  CollectionFiltersButton, CollectionViewModeToggle and CollectionAddButton */
    toolbar?: "full" | "compact" | "none" | React.ReactElement;

    /** Your JSX on every row, card and kanban card (the table's last column),
     *  handed the row and its id; a click on it does not open the record */
    rowActions?: (row: Record<string, unknown>, id: string) => React.ReactNode;

    /** Called with the clicked row instead of opening it (rows, cards, kanban, Edit).
     *  The row as the server sends it, as useRows reads it: ISO date strings,
     *  a belongsTo as its foreign key (customerId) */
    onRowClick?: (row: Record<string, unknown>, id: string) => void;
};
```

### Examples

```tsx
// Simple embedded collection
<CollectionPanel collection="tasks" title="Pending Tasks" />

// Table with an order and a limit
<CollectionPanel
    collection="clients"
    viewMode="table"
    limit={10}
    orderBy="createdAt:desc"
/>

// With a default filter
<CollectionPanel
    collection="orders"
    title={false}
    openEntityMode="dialog"
    collectionOverrides={{
        defaultFilter: { status: ["!=", "completed"] }
    }}
/>

// Three columns of the pending orders, the compact toolbar, a Ship button on
// every row, and the click handled by the page
<CollectionPanel
    collection="orders"
    viewMode="table"
    fields={["number", "status", "total"]}
    where={{ status: ["==", "pending"] }}
    toolbar="compact"
    rowActions={(order, id) => <Button size="small" onClick={() => update("orders", id, { status: "shipped" })}>Ship</Button>}
    onRowClick={(order, id) => setSelectedId(id)}
    className="max-h-[480px]"
/>
```

A panel sizes to its rows: with no height from its parent, or only a
`max-height`, it draws its toolbar and rows and scrolls past that. It lays
itself out by its own width, not the window's. The collection's
`entityActions` draw on rows, cards and kanban cards alike.

> **IMPORTANT FOR AGENTS:** `CollectionPanel` defaults `updateUrl` to `false` so embedded panels don't hijack the browser URL. Only set `updateUrl={true}` if you explicitly need URL sync.

### Outside the CMS: your own page, any router (0.25+)

A collection's table, or one record's form, can live in a page of your own app
with no `<RebaseCMS>`, `<RebaseNavigation>` or `<RebaseShell>`. They need
`<Rebase>` above them and a React Router router — any router (`<BrowserRouter>`
works; a data router is not required), at any path. A router is required:
there is no router-less mode.

```tsx
import { Rebase } from "@rebasepro/app";
import { CollectionPanel, RecordForm } from "@rebasepro/cms";

<Rebase client={client} authController={authController}>
    <BrowserRouter>
        {/* A collection's table, the collection passed as a value */}
        <CollectionPanel collection={postsCollection}/>

        {/* One record's form — loaded by id, saved through <Rebase>'s data layer.
            Leave out id to create a record. */}
        <RecordForm collection={postsCollection} id="123"
            onSaved={({ id }) => console.log("saved", id)}
            onClose={() => navigate("/posts")}/>
    </BrowserRouter>
</Rebase>
```

- `RecordForm` props (0.29+): `fields?: string[]` shows only those fields,
  in that order; its children replace the generated fields with your JSX,
  where `<FormField name="title"/>` (`@rebasepro/cms`) draws one field;
  `compact?: boolean` is the dense form (no rail, no record metadata, medium
  controls); `collectionOverrides?: Partial<AdminCollection>` applies over the
  registered collection, as on `CollectionPanel`. With `fields` or children the
  form validates only what it shows, and a create that leaves out a required
  field with no default shows an error naming it and will not save.
- Two forms on one page do not share DOM ids. In tests, find a field by
  `[data-form-field="title"]` inside the form's `[data-form-path="posts"]`.
- `RecordDetail` (0.29+) is the read-only twin: `collection`, `id`,
  `path?`, `fields?`, `collectionOverrides?`, `className?`. It draws the record
  as the admin's record page does, and leaves out a field a `conditions.hidden`
  rule hides for that record or one the user may not read.
- `<FieldValue collection="orders" field="status" value={order.status} size?/>`
  (0.29+) draws one value as the server sends it (`useRows`, `client.data`)
  through `PropertyPreview`. A belongsTo's foreign key
  (`field="customer" value={order.customerId}`) is shown as the target's title. It needs the collection
  registered above it (`<RebaseCMS>` or `CollectionsProvider` — every table the server serves is); an unknown
  collection or field throws.

- No CMS route serves the page, so a record clicked in the table opens in a
  side panel or dialog **over** the page — never by URL (`full_screen` and
  `split` become `side_panel`).
- Given a `collection`, each panel brings its own `CollectionsProvider` when
  none is above it. Mount one yourself to share a scope between several panels,
  or to use the lower-level pieces (`CollectionViewBinding`, `useSidePanel`)
  under it:

```tsx
import { CollectionPanel, CollectionsProvider } from "@rebasepro/cms";

<CollectionsProvider tableCustomizations={[postsCms, authorsCms]}>
    <CollectionPanel collection="posts"/>
    <CollectionPanel collection="authors"/>
</CollectionsProvider>
```

- Unsaved-changes guards work under any router: a data router
  (`createBrowserRouter`) blocks in-app navigation too; under `<BrowserRouter>`
  they fall back to the browser's leave-page prompt. In 0.24 and earlier the
  record views threw outside a data router.
- **Theme:** `<Rebase>` puts a `dark` class on `<html>` and follows
  `prefers-color-scheme` unless the host app owns the theme. To own it, pass your
  controller — `<Rebase modeController={{ mode, setMode }}>` (0.25+, a
  `ModeController`: `mode: "light" | "dark"`, `setMode("light" | "dark" | "system")`)
  — and Rebase never touches `<html>`, the media query or localStorage.

---

## 5. Entity Selection Dialog

Use `useSelectionDialog()` to open a side dialog for picking rows (same mechanism used by reference fields). The rows come back as the server sends them, with their ids beside them.

```typescript
import { useSelectionDialog } from "@rebasepro/cms";
```

### Usage

```tsx
function MyComponent() {
    const { open, close } = useSelectionDialog<Product>({
        path: "products",
        onSingleRowSelected: (row, id) => {
            console.log("Selected:", id, row?.name);
            close();
        }
    });

    return <Button onClick={open}>Select Product</Button>;
}
```

The hook accepts `SelectionProps` with `path` made optional (`string | false`), plus an `onClose` callback. With `multiselect: true`, `onMultipleRowsSelected(rows, ids)` reports every tick and `onSelectionDone(rows, ids)` the final selection once; `selectedIds` pre-selects rows. `open()` throws when no `path` is set, or when no `collection` is passed and none is registered at that path.

---

## 6. Side Dialogs (Generic)

Use `useSideDialogsController()` to open arbitrary side panels with custom React content. This is the lower-level mechanism behind entity side panels.

```typescript
import { useSideDialogsController } from "@rebasepro/cms";
```

### SideDialogsController Interface

```typescript
interface SideDialogsController {
    /** Close the last panel */
    close: () => void;

    /** Currently open panels */
    sidePanels: SideDialogPanelProps[];

    /** Override all panels */
    setSidePanels: (panels: SideDialogPanelProps[]) => void;

    /** Open one or multiple side panels */
    open: (panelProps: SideDialogPanelProps | SideDialogPanelProps[]) => void;

    /** Replace the last panel */
    replace: (panelProps: SideDialogPanelProps | SideDialogPanelProps[]) => void;
}
```

### SideDialogPanelProps

```typescript
interface SideDialogPanelProps {
    /** Unique key identifying this panel */
    key: string;

    /** React component to render inside the panel */
    component: React.ReactNode;

    /** Optional panel width (e.g. "90vw", "600px") */
    width?: string;

    /** When open, update the browser URL to this path */
    urlPath?: string;

    /** URL to navigate to when the panel is closed and there's no history */
    parentUrlPath?: string;

    /** Callback when the panel is closed */
    onClose?: () => void;

    /** Store additional data on the panel */
    additional?: unknown;
}
```

### Example

```tsx
const sideDialogs = useSideDialogsController();

sideDialogs.open({
    key: "my-custom-panel",
    component: <MyCustomView data={someData} />,
    width: "600px",
    onClose: () => console.log("Panel closed")
});
```

---

## 7. Breadcrumbs

Use `useBreadcrumbsController()` to read or set the breadcrumb trail.

```typescript
import { useBreadcrumbsController } from "@rebasepro/cms";
```

### BreadcrumbsController Interface

```typescript
interface BreadcrumbsController {
    breadcrumbs: BreadcrumbEntry[];
    set: (props: { breadcrumbs: BreadcrumbEntry[] }) => void;
}

interface BreadcrumbEntry {
    title: string;
    url: string;
    // Stable identifier (e.g. the collection path). Lets the provider tell a
    // rebuilt-but-unchanged trail from a real navigation.
    id?: string;
}
```

### Example

```tsx
const breadcrumbs = useBreadcrumbsController();

breadcrumbs.set({
    breadcrumbs: [
        { title: "Dashboard", url: "/" },
        { title: "Products", url: "/c/products", id: "products" },
    ]
});
```

---

## 8. Navigation State

Use `useNavigationStateController()` to access registered views, loading state, and trigger navigation refresh.

```typescript
import { useNavigationStateController } from "@rebasepro/cms";
```

### NavigationStateController Interface

```typescript
type NavigationStateController = {
    /** Custom views added to the main navigation */
    views?: AppView[];

    /** Custom views added to admin navigation */
    adminViews?: AppView[];

    /** Top-level navigation entries and groups */
    topLevelNavigation?: NavigationResult;

    /** Whether navigation is still loading */
    loading: boolean;

    /** Error during navigation loading */
    navigationLoadingError?: Error;

    /** Force a navigation recalculation */
    refreshNavigation: () => void;
};
```

---

## 9. Admin Context (All-in-One)

Use `useAdminContext()` to get the full admin context combining the core `RebaseContext` with all admin-specific controllers.

```typescript
import { useAdminContext } from "@rebasepro/cms";
```

### AdminContext Type

```typescript
type AdminContext = RebaseContext & {
    sidePanelController: SidePanelController;
    sideDialogsController: SideDialogsController;
    urlController: UrlController;
    navigationStateController: NavigationStateController;
    collectionRegistryController: CollectionRegistryController;
};
```

### Example

```tsx
const context = useAdminContext();

// Access any controller
context.sidePanelController.open({ path: "products", id: "abc" });
context.urlController.navigate(context.urlController.buildUrlCollectionPath("orders"));
context.collectionRegistryController.getCollection("products");
context.authController; // from RebaseContext
context.data;           // flat rows from RebaseContext, as useRows and client.data return them
```

> **TIP:** Use `useAdminContext()` instead of `useRebaseContext()` when you need admin controllers (side panels, navigation, URL). Use `useRebaseContext()` from `@rebasepro/app` when you only need core context (auth, data, storage).

---

## 10. Common Patterns

### Navigate to a collection and open an entity

```tsx
import { useUrlController, useSidePanel } from "@rebasepro/cms";

function navigateAndOpen() {
    const urlController = useUrlController();
    const sidePanel = useSidePanel();

    // First navigate to the collection
    urlController.navigate(urlController.buildUrlCollectionPath("products"));

    // Then open the entity in the side drawer
    sidePanel.open({
        path: "products",
        id: "abc123"
    });
}
```

### Open entity from a custom view without navigating

```tsx
import { useSidePanel } from "@rebasepro/cms";

function MyCustomView() {
    const sidePanel = useSidePanel();

    return (
        <button onClick={() => sidePanel.open({
            path: "products",
            id: "abc123",
            updateUrl: false  // don't change the URL
        })}>
            View Product
        </button>
    );
}
```

### Programmatic entity creation from a custom view

```tsx
import { useSidePanel } from "@rebasepro/cms";

function CreateButton() {
    const sideEntity = useSidePanel();

    return (
        <button onClick={() => sideEntity.open({
            path: "orders",
            defaultValues: {
                status: "pending",
                createdAt: new Date()
            },
            closeOnSave: true,
            onSaved: ({ id }) => {
                console.log("Created order:", id);
            }
        })}>
            New Order
        </button>
    );
}
```

---

## 10. Custom Top-Level Views

Add custom pages to the main admin navigation using the `views` prop on `<RebaseCMS>`. Views appear alongside collections in the sidebar and home page.

### AppView Interface

```typescript
interface AppView {
    slug: string;                    // URL path segment (e.g. "dashboard")
    name: string;                    // Display name in navigation
    view: React.ReactNode | React.ComponentType; // Element, or a component (rendered lazily on visit)
    icon?: string | React.ReactNode; // Lucide icon key or custom element
    group?: string;                  // Navigation group (default: "Views")
    pinToBottom?: boolean;           // Sink this view's group to the bottom of the drawer
    description?: string;            // Optional description (Markdown)
    hideFromNavigation?: boolean;    // Hidden from sidebar but still routable
    nestedRoutes?: boolean;          // Register slug/* wildcard route
    roles?: string[];                // Only show to users with at least one matching role
}
```

### Static Views

```tsx
<RebaseCMS
    tableCustomizations={tableCustomizations}
    views={[
        { slug: "dashboard", name: "Dashboard", icon: "LayoutDashboard", view: <Dashboard /> },
        { slug: "reports",   name: "Reports",   icon: "FileText",        view: <Reports />, group: "Analytics" },
        { slug: "audit-log", name: "Audit Log",  icon: "ScrollText",     view: <AuditLog />, roles: ["admin"] },
    ]}
/>
```

### Builder Function (Role-Aware)

Pass a function instead of an array to dynamically resolve views based on the current user:

```tsx
<RebaseCMS
    tableCustomizations={tableCustomizations}
    views={({ user, authController, data }) => [
        { slug: "dashboard", name: "Dashboard", icon: "LayoutDashboard", view: <Dashboard /> },
        ...(user?.roles?.includes("analyst")
            ? [{ slug: "reports", name: "Reports", icon: "FileText", view: <Reports /> }]
            : []),
    ]}
/>
```

The builder receives `{ user, authController, data }` — `data` reads rows as the server sends them, like `context.data` — and can return a `Promise<AppView[]>` for async resolution.

### Plugin-Contributed Views

Plugins can also contribute views via the `views` property on `RebasePlugin`:

```tsx
const myPlugin: RebasePlugin = {
    key: "analytics",
    views: [
        { slug: "analytics", name: "Analytics", icon: "BarChart3", view: <Analytics /> }
    ]
};

// `plugins` is a prop of <Rebase>, NOT of <RebaseCMS>.
<Rebase plugins={[myPlugin]} client={client} authController={authController}>
    {() => <RebaseCMS tableCustomizations={tableCustomizations} />}
</Rebase>
```

All views (admin, builder, plugin) are merged in order: **admin views → Studio dev views → Plugin views**.

### Plugins: what composes, and two hooks that never ran

- **Field wrappers compose** (0.25+). Every plugin's `fieldBuilder.wrap` receives
  the field as the plugins before it left it (`params.Field`), and every wrapper
  renders — the first plugin's innermost, the last plugin's outermost. In 0.24
  and earlier only the last plugin that returned a wrapper rendered.
- **`hooks.modifyCollectionAsync` and `lifecycle.onCollectionChange` are
  deprecated: nothing ever invoked them.** They still compile, and `<Rebase>`
  warns once per plugin that sets one. For a change that needs data, fetch the
  data before rendering `<Rebase>`, then build the plugin from the result, so its
  `hooks.modifyCollection` is synchronous over data it already has — a plugin's
  `loading: true` does not hold back `<Rebase>`'s plain children, and
  `modifyCollection` is not re-applied when data arrives later. To react to
  changes, subscribe with `context.data.table(slug).listen(...)` from
  `lifecycle.onMount`, unsubscribing in `onUnmount`. (The `onCollectionChange`
  an entity action's `onClick` receives is a different, working API.)

### Role Filtering

The `roles` field provides declarative access control. When set, the view is excluded entirely (not just hidden from nav) if the user doesn't have at least one matching role:

```tsx
// Only visible to admin users
{ slug: "admin-panel", name: "Admin", view: <AdminPanel />, roles: ["admin"] }

// Visible to admin OR editor
{ slug: "editor", name: "Editor", view: <Editor />, roles: ["admin", "editor"] }

// Visible to everyone (roles omitted)
{ slug: "dashboard", name: "Dashboard", view: <Dashboard /> }
```

> **IMPORTANT FOR AGENTS:** The `roles` filter applies to ALL views — admin views, builder-returned views, and plugin views. Use `roles` for simple role gates and the builder function for dynamic/async conditions. Both compose.

### Navigation Grouping

Views participate in the same navigation group system as collections. Use the `group` property on the view, or control grouping centrally via `navigationGroupMappings`:

```tsx
<RebaseCMS
    tableCustomizations={tableCustomizations}
    views={[
        { slug: "dashboard", name: "Dashboard", view: <Dashboard />, group: "Analytics" },
        { slug: "reports",   name: "Reports",   view: <Reports />,   group: "Analytics" },
    ]}
    navigationGroupMappings={[
        { name: "Content",   entries: ["posts", "pages"] },
        { name: "Analytics", entries: ["dashboard", "reports"] },
    ]}
/>
```

---

## 11. Where the Admin Lives — Mounting Under a URL Prefix

In the default scaffold the frontend **is** the admin panel: `App.tsx` renders `<RebaseAuth>` + `<RebaseCMS>` + `<RebaseShell>` at the root, so the deployed URL shows the admin directly. There is no separate admin URL — in production one server serves both the API (`/api/*`) and this SPA.

When a project ships its **own product app** as the frontend, the admin is mounted under a prefix (commonly `/admin`) instead. Split the Vite entry by URL so each app is lazy-loaded and product visitors never download the admin bundle:

```tsx
// frontend/src/main.tsx
const isAdmin = window.location.pathname.startsWith("/admin");
const ProductApp = lazy(() => import("./App"));
const AdminApp = lazy(() => import("./AdminApp"));

// A data router lets the admin's unsaved-changes guards block in-app
// navigation too (any router works; others fall back to a leave-page prompt).
const router = isAdmin
    ? createBrowserRouter([{ path: "/*", element: <AdminApp/> }], { basename: "/admin" })
    : createBrowserRouter([{ path: "/*", element: <ProductApp/> }]);

root.render(<RouterProvider router={router}/>);
```

When the admin is the whole frontend, do not hand-write the prefix at all: set
`apps.<name>.path` in `rebase.json` and `rebase build` passes it to Vite as
`base`, which the scaffold's `main.tsx` already reads back out of
`import.meta.env.BASE_URL` and gives to the router as `basename`.

The alternative, when the admin is nested inside a route of a larger app with
no `basename`, is to tell the CMS about the prefix instead:

```tsx
// frontend/src/AdminApp.tsx — tell the admin about the prefix
<RebaseCMS tableCustomizations={tableCustomizations} basePath="/admin" />
```

> **IMPORTANT FOR AGENTS:** Choose **either** a router `basename="/admin"` **or** `<RebaseCMS basePath="/admin">` — never both, or the prefix is applied twice. Without either, collection views hang on a spinner because URL⇄collection resolution never matches. `<RebaseCMS>` works under any React Router router (0.25+; in 0.24 and earlier it required a **data router**, `createBrowserRouter`, because of `useBlocker`). Prefer a data router anyway: under it, unsaved-changes guards also block in-app navigation, where under `<BrowserRouter>` they can only prompt when leaving the app.

---

## 12. Custom Field and Preview Components

To replace how a single field is edited or displayed, give the column a component under `fields` in the table's `customizeTable` (in `frontend/src/cms/`). `Field` is the form editor; `Preview` is the read-only rendering in tables, cards and references. Both are imported **by value** — the customization is frontend code, so there is no string path and no lazy thunk (`customizeTable` throws on either):

```tsx
// frontend/src/cms/exercises.tsx
import { customizeTable } from "@rebasepro/cms";
import type { exercises } from "../../../backend/schema/exercises";
import BodyPartsField from "../BodyPartsField";
import BodyPartsPreview from "../BodyPartsPreview";

export const exercisesCms = customizeTable<typeof exercises>("exercises", {
    fields: {
        body_parts: { name: "Affected body parts", Field: BodyPartsField, Preview: BodyPartsPreview }
    }
});
```

The table in `backend/schema/exercises.ts` declares the column
(`body_parts: col.text({ enum: [...] }).array()`); the frontend imports it as
a type only, so no server code reaches the browser.

The component itself is ordinary React, in `frontend/`:

```tsx
// frontend/src/BodyPartsField.tsx
import type { FieldProps } from "@rebasepro/cms";
import type { ArrayProperty } from "@rebasepro/cms-types";

export default function BodyPartsField({ value, setValue, property, error, disabled }: FieldProps<ArrayProperty>) {
    return null; // …your editor
}
```

```tsx
// frontend/src/BodyPartsPreview.tsx
import type { FieldPreviewProps } from "@rebasepro/cms-types";

export default function BodyPartsPreview({ value, property, size }: FieldPreviewProps) {
    return null; // …your read-only rendering
}
```

Read the enum values, labels and limits off the `property` argument rather than restating them, so the component cannot drift from the table.


---

## Exported Components

The admin package exports the following components (from `@rebasepro/cms`):

| Component | Description |
|-----------|-------------|
| `RebaseCMS` | Declarative admin config (`tableCustomizations`, `externalCollections`, views, editor) — renders nothing |
| `RebaseShell` | App shell (drawer, nav, routes, layout) — renders the actual UI |
| `CollectionPanel` | Embed a collection view inside custom pages — `collection` by name or as a value; `where`, `orderBy`, `fields`, `toolbar`, `rowActions`, `onRowClick` (0.29+) |
| `RecordForm` | One record's form in a page of your own app (0.25+); `fields`, `FormField` children, `compact`, `collectionOverrides` (0.29+) |
| `FormField` | One field of the record form it is rendered in, by property name (0.29+) |
| `RecordDetail` | One record, read-only, in a page of your own app; `fields`, `collectionOverrides` (0.29+) |
| `FieldValue` | One value of a flat row, drawn as the admin draws it (0.29+) |
| `CollectionsProvider` | The minimal scope for collection views and record forms outside the CMS (0.25+) |
| `CollectionViewBinding` | The collection view, bound to Rebase data |
| `CollectionTableBinding` | The table rendering of a collection |
| `CollectionCardViewBinding` | The card/grid rendering of a collection |
| `EntityViewBinding` | Entity detail/edit view |
| `EditViewBinding` / `DetailViewBinding` | The record's edit view, and its read-only view — the two `Entity.SidePanel` switches between (0.26+) |
| `EntityPreviewBinding` | Reference/relation preview chip |
| `EntityCardBinding` | Card representation of an entity |
| `SelectionTableBinding` / `SelectableTable` | Table for selecting entities |
| `SideDialogs` | Side dialog container |
| `SidePanelProvider` | Context provider for the side panel controller |
| `Scaffold` | Layout scaffold component |
| `AppBar` | Top app bar |
| `Drawer` / `DefaultDrawer` | Sidebar drawer |
| `RebaseAuthGate` | Auth-gated wrapper |
| `RebaseNavigation` | Navigation provider |
| `RebaseLayout` | Layout wrapper |
| `RebaseRouteDefs` | Route definitions |

> **IMPORTANT FOR AGENTS: a component-override *slot name* is not an export.**
> `"DetailView"`, `"EntityPreview"`, `"Collection.View"`, `"Collection.Table"`,
> `"Collection.Card"`, `"Entity.Form"`, `"Entity.SidePanel"` and
> `"Entity.MissingReference"` are string keys in the `OverridableComponentName`
> union — what you pass to `components={{ … }}` to *replace* a component. There
> is no `import { EntityPreview } from "@rebasepro/cms"`; the component that
> ships is `EntityPreviewBinding`. Importing a slot name gets you `undefined`.
> Each name's default component, and the file to copy it from, is the table in
> the `rebase-customize-admin` skill ("Copying a built-in part").

## Exported Hooks

| Hook | Description |
|------|-------------|
| `useSidePanel()` | Open/close entity side panels |
| `useSideDialogsController()` | Open/close generic side dialogs |
| `useUrlController()` | Build URLs and navigate |
| `useNavigationStateController()` | Access navigation state |
| `useCollectionRegistryController()` | Look up collections by slug |
| `useBreadcrumbsController()` | Read/set breadcrumbs |
| `useAdminContext()` | Full admin context (core + admin controllers) |
| `useSelectionDialog()` | Open a dialog that picks rows |
| `useSelectionController(collection)` | A selection of rows you hold, for `admin.selectionController`: `selection` (`{ type: "rows", ids, rows }` or a query), `isSelected(id)`, `toggleSelection(row)` |
| `useHistory()` | Entity version history |
| `useApp()` | App-level utilities |

## Exported Utilities

| Utility | Description |
|---------|-------------|
| `addInitialSlash(path)` | Ensure path starts with `/` |
| `removeInitialSlash(path)` | Strip leading `/` |
| `removeTrailingSlash(path)` | Strip trailing `/` |
| `removeInitialAndTrailingSlashes(path)` | Strip both |
| `getLastSegment(path)` | Get last path segment |
| `getCollectionBySlugWithin(collections, slug)` | Find collection in array |
| `mergeEntityActions(...)` | Merge entity action arrays |
| `resolveEntityAction(...)` | Resolve an entity action |
| `resolveEntityView(...)` | Resolve an entity view |
| `isReferenceProperty(prop)` | Check if property is a reference |
| `isRelationProperty(prop)` | Check if property is a relation |
| `getIconForProperty(prop)` | Get icon for a property type |

## Built-in Entity Actions

```typescript
import {
    editEntityAction,
    copyEntityAction,
    deleteEntityAction,
    unlinkEntityAction, // 0.26+: removes a row from a junction-backed tab, deleting nothing
    resetPasswordAction
} from "@rebasepro/cms";
```

These are pre-built `EntityAction` objects that can be added to a collection's `entityActions` array.
