---
name: rebase-studio
description: Guide for using and customizing the Rebase Studio developer tools layer. Use this skill when the user needs help with Studio dev tools (SQL/JS/RLS/Storage/Cron/Schema Visualizer/Branches/API Explorer/Logs), admin modes (cms/studio), Studio home page customization, bridge hooks, or Studio configuration. Studio is NOT the CMS — the CMS lives in @rebasepro/cms.
---

# Rebase Studio

Rebase Studio (`@rebasepro/studio`) is the developer tools layer for Rebase. It provides 11 built-in tools — SQL Console, JS Console, RLS Editor, Storage browser, Cron Jobs manager, Schema Visualizer, Branches manager, Backups, API Explorer, Logs Explorer and API Keys — accessible via the "Studio" mode toggle in the sidebar.

## Overview

- **11 built-in dev tools** — all lazy-loaded and code-split so they don't impact initial bundle size
- **StudioHomePage** — customizable landing page with tool cards grouped by section
- **Studio Bridge** — hooks that connect Studio tools to CMS data (collections, navigation, side panels)

## Admin Modes (Bi-State)

> **IMPORTANT FOR AGENTS:** The Studio uses a **bi-state** mode system: `"cms"` | `"studio"`. It is NOT `"developer"` / `"editor"`, and there is no `"settings"` mode — the union carried one briefly, nothing set it and nothing read it, and it is gone. These two are the only valid values.

The admin mode is controlled by `AdminModeController` and persisted in `localStorage` under the key `rebase-admin-mode`. Default mode is `"cms"`. A browser that used the panel before 0.17.0 still holds `"content"`; it is migrated on read.

### Mode Values

| Mode | Description | Navigation Shows |
|------|-------------|------------------|
| `"cms"` | Clean CMS experience for editing data. Default mode. | Collections + admin entries (Users/Roles) |
| `"studio"` | Developer tools and schema management. | Dev tool views + admin entries (Users/Roles) |

### Mode Controller API

```typescript
import { useAdminModeController } from "@rebasepro/app";

interface AdminModeController {
    mode: "cms" | "studio";
    setMode: (mode: "cms" | "studio") => void;
}

// Usage in a component
function MyComponent() {
    const adminModeController = useAdminModeController();

    // Check current mode
    if (adminModeController.mode === "studio") {
        // Show developer UI
    }

    // Switch modes
    adminModeController.setMode("cms");
}
```

### Drawer Mode Switch

When `<RebaseStudio>` is registered, the drawer automatically renders a segmented **CMS / Studio** toggle. Clicking "CMS" sets mode to `"cms"` and navigates to the base path. Clicking "Studio" sets mode to `"studio"` and navigates to `/s`.

## Effective Role Simulation

> **IMPORTANT FOR AGENTS:** The hook is called `useEffectiveRoleController()`, NOT `useEffectiveRole()`.

In Studio mode, developers can select an "effective role" to preview the application as a specific role would see it. The role is persisted in `localStorage` under `rebase-effective-role`.

```typescript
import { useEffectiveRoleController } from "@rebasepro/app";

interface EffectiveRoleController {
    effectiveRole: string | null;
    setEffectiveRole: (role: string | null) => void;
}

// Usage
function RoleSimulator() {
    const { effectiveRole, setEffectiveRole } = useEffectiveRoleController();

    // Set a role to simulate
    setEffectiveRole("editor");

    // Clear simulation (back to actual role)
    setEffectiveRole(null);
}
```

## Studio Dev Tools

The Studio ships 11 built-in dev tools, all **lazy-loaded** (code-split) so they don't impact the initial bundle. Heavy dependencies (Monaco, `@xyflow/react`, `dagre`, `pgsql-ast-parser`) are only loaded when a tool is visited.

### Tool Reference

| Tool Key | Component | Name | Group | Icon | Description |
|----------|-----------|------|-------|------|-------------|
| `"sql"` | `SQLEditor` | SQL Console | Database | `terminal` | Execute raw SQL queries against the database |
| `"js"` | `JSEditor` | JS Console | Compute | `code` | Run JavaScript with the Rebase SDK in a live sandbox |
| `"rls"` | `RLSEditor` | RLS Policies | Database | `ShieldCheck` | Configure Row Level Security for fine-grained data access |
| `"storage"` | `StorageView` | Storage | Storage | `HardDrive` | Browse, upload, and manage files in the storage bucket |
| `"cron"` | `CronJobsView` | Cron Jobs | Compute | `Clock` | Monitor and manage scheduled background tasks |
| `"schema-visualizer"` | `SchemaVisualizer` | Schema Visualizer | Database | `Network` | Interactive ERD showing tables, columns, and relationships |
| `"branches"` | `BranchesView` | Branches | Database | `GitBranch` | Create and manage isolated database copies for development |
| `"backups"` | `BackupsView` | Backups | Database | `Database` | Browse and download database backups |
| `"api"` | `ApiExplorer` | API Explorer | API | `BookOpen` | Interactive API documentation with live request testing |
| `"logs"` | `LogsExplorer` | Logs Explorer | Database | `Activity` | Real-time system, query, and authentication logs |
| `"api-keys"` | `ApiKeysView` | API Keys | Access Control | `KeyRound` | Create and manage scoped service API keys |

> **IMPORTANT FOR AGENTS:** The `"schema"` tool (collection editor) is **NOT** registered by `<RebaseStudio>`. It is auto-injected by `<RebaseShell>` when `collectionEditor` is enabled on `<RebaseCMS>` and `<RebaseStudio>` is mounted with `tools` omitted or containing `"schema"`. Do not try to register it manually — but when you pass a `tools` list, include `"schema"` in it or the collection editor's route is not registered.

### Enabling/Disabling Tools

By default, **all 11 tools** are enabled. Use the `tools` prop on `<RebaseStudio>` to selectively enable a subset:

```tsx
// Enable all tools (default behavior — both are equivalent)
<RebaseStudio />
<RebaseStudio tools={undefined} />

// Enable only specific tools (no collection editor: "schema" is not listed)
<RebaseStudio tools={["sql", "rls", "storage"]} />

// Enable everything except branches ("schema" keeps the collection editor)
<RebaseStudio tools={["sql", "js", "rls", "schema", "storage", "cron", "schema-visualizer", "backups", "api", "logs", "api-keys"]} />
```

The `tools` prop accepts an array of tool key strings:

```typescript
type ToolKey = "sql" | "js" | "rls" | "schema" | "storage" | "cron"
    | "schema-visualizer" | "branches" | "backups" | "api" | "logs" | "api-keys";

// Default when tools is undefined (plus "schema", injected when collectionEditor is on):
const DEFAULT_TOOLS: ToolKey[] = [
    "sql", "js", "rls", "storage", "cron", "schema-visualizer",
    "branches", "backups", "api", "logs", "api-keys"
];
```

### Individual tools are not importable

`@rebasepro/studio` exports **only** `RebaseStudio`, `StudioHomePage` and the
Studio Bridge re-exports (below). The
tools (SQLEditor, JSEditor, RLSEditor,
StorageView, …) are lazy-loaded inside `RebaseStudio.tsx` and deliberately not
re-exported, so that importing the Studio does not pull every tool into the
bundle.

> **WARNING FOR AGENTS:** Do NOT write a deep import such as
> `@rebasepro/studio/components/SQLEditor/SQLEditor`. It resolves inside this
> repository and fails for every installed consumer: the package's `exports`
> map contains `"."` and `"./package.json"` only, and the published `dist/` is a
> single bundle with no per-component file behind such a path. Mount
> `<RebaseStudio>` and let it load the tool.

## Frontend Composition

The Studio is mounted using the declarative composition API. Under the `<Rebase>` provider, `<RebaseAuth>`, `<RebaseCMS>` and `<RebaseStudio>` are purely declarative — they **render nothing** and only register configuration into the registry (`RebaseRegistryController`, read with `useRebaseRegistry()`). `<RebaseShell>` then reads the registry and builds the actual UI.

```tsx
import { useRebaseAuthController, RebaseAuth } from "@rebasepro/app";
import { Rebase } from "@rebasepro/app";
import { RebaseCMS, RebaseShell } from "@rebasepro/cms";
import { useDataEnhancementPlugin } from "@rebasepro/plugin-ai";
import { RebaseStudio } from "@rebasepro/studio";
import React from "react";
import { createRebaseClient } from "@rebasepro/client";
import { tableCustomizations } from "./cms";

// `rebase dev` injects VITE_API_URL with the port it bound (derived from the
// project path, not a fixed 3001); a deployed build serves the API same-origin.
const API_URL = import.meta.env.VITE_API_URL;

// Module scope: inside a component, StrictMode builds a second client in development.
const rebaseClient = createRebaseClient({ baseUrl: API_URL });

export function App() {
    const authController = useRebaseAuthController({ client: rebaseClient });
    const dataEnhancementPlugin = useDataEnhancementPlugin();

    return (
        <Rebase client={rebaseClient} authController={authController} plugins={[dataEnhancementPlugin]}>
            <RebaseAuth/>
            <RebaseCMS tableCustomizations={tableCustomizations} collectionEditor={true}/>
            <RebaseStudio tools={undefined} homePage={undefined} />
            <RebaseShell title="My App"/>
        </Rebase>
    );
}
```

### Props are optional

Every `RebaseStudioConfig` prop is optional, so `<RebaseStudio/>` alone type-checks
and registers every built-in tool; `tools={undefined} homePage={undefined}` is
the same thing spelled out.

### Key Components

| Component | Package | Purpose | Renders UI? |
|-----------|---------|---------|-------------|
| `<Rebase>` | `@rebasepro/app` | Root provider (client, auth, user management, plugins) | Yes (providers) |
| `<RebaseAuth>` | `@rebasepro/app` | Authentication config (custom login view) | No — registers into registry |
| `<RebaseCMS>` | `@rebasepro/cms` | CMS config (collections, views, editor) | No — registers into registry |
| `<RebaseStudio>` | `@rebasepro/studio` | Studio config (tools, home page) | No — registers into registry |
| `<RebaseShell>` | `@rebasepro/cms` | App shell (drawer, navigation, routes, layout) | Yes — the actual UI |

## Global Component Overrides (Swizzling)

Rebase allows you to override default UI components globally by passing a `components` prop to the `<Rebase>` provider. This implements Docusaurus-style component swizzling, supporting both **Eject** and **Wrap** patterns.

```tsx
import { Rebase } from "@rebasepro/app";
import { MyAppBar } from "./MyAppBar";

<Rebase
    client={rebaseClient}
    components={{
        // Eject Mode: Replace the built-in AppBar entirely
        "Shell.AppBar": { Component: MyAppBar },

        // Wrap Mode: Wrap the default LoginView, adding custom branding
        "Auth.LoginView": {
            // `OriginalComponent` is injected at runtime when `wrap: true`; the override
                    // slot's type does not model it, hence the annotation.
                    Component: (({ OriginalComponent, ...props }: {
                        OriginalComponent: React.ComponentType<Record<string, unknown>>
                    }) => (
                <div className="custom-login-wrapper">
                    <div className="branding">Welcome to My Enterprise App</div>
                    <OriginalComponent {...props} />
                </div>
            )) as unknown as React.ComponentType<Record<string, unknown>>,
            wrap: true
        }
    }}
>
    {/* your app */}
    …
</Rebase>
```

**Ejecting by copying the built-in.** To start an eject from the original
rather than from nothing, copy the default component's source and register the
copy: from 0.26 every part except `Collection.View`, `DetailView` and the home
page's drag-and-drop compiles with `@rebasepro/cms` / `@rebasepro/app` imports
only. Which component and file each name maps to, and what to do for the three,
is in the `rebase-customize-admin` skill ("Copying a built-in part").

**Overrides compose across scopes.** A collection's `wrap: true` override (in
its `admin.components`) receives as `OriginalComponent` whatever the app-level
`<Rebase components>` made of that component — the app's override when there is
one, the built-in otherwise. A collection-level eject (no `wrap`) replaces both.
In 0.24 and earlier a collection's `wrap` always received the built-in, and the
app-level override did not render for that collection.

### Overridable Component Scopes

#### App-scoped Components (`AppComponentName`)
These components can only be overridden at the root `<Rebase>` provider, as they represent global shell or utility structures.

- `"Shell.AppBar"` — The header bar at the top of the page.
- `"Shell.Drawer"` — The collapsible main sidebar drawer.
- `"Shell.DrawerNavigationItem"` — Sidebar navigation link.
- `"Shell.DrawerNavigationGroup"` — Sidebar navigation group header.
- `"HomePage"` — The landing dashboard of the CMS (when in content mode).
- `"HomePage.CollectionCard"` — Individual collection link card on the home page.
- `"Auth.LoginView"` — The login screen overlay.

#### Collection-scoped Components (`CollectionComponentName`)
These components can be overridden globally on `<Rebase>` (applied to every collection) or on individual collections inside their definitions — a collection's `wrap: true` override wraps the global one (see above).

- `"Collection.View"` — The container view for the collection.
- `"Collection.Table"` — The default tabular data view.
- `"Collection.Card"` — Individual card wrapper.
- `"Collection.EmptyState"` — View shown when a collection is empty.
- `"Collection.Actions"` — Toolbar actions header.
- `"Collection.FilterField"` — The per-property filter input.
- `"Entity.Form"` — The detail form view.
- `"EditView.FormActions"` — Form action button bar.
- `"DetailView"` — Read-only detail view.
- `"Entity.SidePanel"` — Side panel wrapper.
- `"EntityPreview"` — Reference / relation preview chip.
- `"Entity.MissingReference"` — Placeholder view when a relation references a deleted/non-existent entity.

> **IMPORTANT FOR AGENTS:** three keys break the `Entity.` pattern the rest
> follow — `"EditView.FormActions"`, `"DetailView"` and `"EntityPreview"`.
> `"Entity.FormActions"`, `"Entity.DetailView"` and `"Entity.Preview"` are not in
> the union: they type-error, and in plain JavaScript the override silently never
> applies.

## RebaseCMS Configuration

`<RebaseCMS>` accepts the full `RebaseCMSConfig`:

```typescript
interface RebaseCMSConfig {
    tableCustomizations?: readonly TableCustomization[]; // the customizations from frontend/src/cms, one per table
    externalCollections?: readonly AdminCollection[];    // Firestore collections and other non-Rebase sources
    tables?: readonly TableDescriptor[];                 // embedding and tests: render these instead of the served tables
    uiConfig?: { tables?: { [slug: string]: object } };
    views?: AppView[] | AppViewsBuilder;
    homePage?: ReactNode;
    entityViews?: EntityCustomView[];
    collectionViews?: CollectionCustomView[];  // view modes, opted into by customizeTable's customViews
    entityActions?: EntityAction[];
    navigationGroupMappings?: NavigationGroupMapping[];
    collectionEditor?: boolean | CollectionEditorOptions;
    basePath?: string;                        // URL prefix when not mounted via a router basename
}
```

`plugins` is a prop of `<Rebase>`, not of `<RebaseCMS>`.

### Collection Editor Options

```typescript
interface CollectionEditorOptions {
    /** Auth token for schema-editor API calls. Falls back to authController.getAuthToken. */
    getAuthToken?: () => Promise<string | null>;
    /** Mark the editor as read-only (disable mutations). */
    readOnly?: boolean;
    /** Suggested base paths shown when creating new collections. */
    pathSuggestions?: string[];
}
```

What a save does: schema facts become `TablePatch` edits written into
`backend/schema/<table>.ts`; presentation becomes UI preferences
(`frontend/src/cms/ui-config.json` in development, `rebase.ui_preferences` on a
deployment). The composition order in the panel is: the table as served →
`tableCustomizations` → `uiConfig` (the JSON file) → workspace preferences →
the user's own. `rebase build` ships `ui-config.json` in the bundle
(`entry.uiConfig`), so MCP views and `describe_table` show the same labels,
order and hidden columns. Keep `uiConfig={uiConfig}` on `<RebaseCMS>`
(`rebase verify` warns `cms-ui-config-not-mounted` otherwise).

- **Import an existing table**: a table the database has and `backend/schema`
  does not declare can be adopted from the editor
  (`GET /api/admin/schema-editor/unmapped-tables`). The file is written from
  the database's own description; adoption plans no DDL and never lowers the
  table's RLS posture (RLS off or no policies → `rls: "admin-only"`). A table
  without a primary key cannot be adopted.
- **Firestore collections** are editable in development: a save rewrites the
  `defineFirestoreCollection({...})` call in `frontend/src/cms` in place;
  read-only in production. Deleting one is a code change (file +
  `externalCollections` entry).
- **A file changed on disk** since the editor read it answers 409
  `SCHEMA_EDIT_STALE_FILE` and writes nothing: reload and redo the edit.
- A change to a table's rules is enforced in the same live apply, or reported
  `policies: "deferred" | "failed"` ("Rules saved to source; they take effect
  on the next deploy.").

### Navigation Group Mappings

Control how collections and views are grouped in the sidebar and home page:

```typescript
interface NavigationGroupMapping {
    name: string;           // Group header display name
    entries: string[];      // Collection slugs or view paths
    icon?: string;          // Lucide icon name for the group header
    collapsedByDefault?: boolean | {
        drawer?: boolean;   // Collapse in sidebar
        home?: boolean;     // Collapse on home page
    };
}

// Usage
<RebaseCMS
    tableCustomizations={tableCustomizations}
    navigationGroupMappings={[
        { name: "Content", entries: ["posts", "pages", "media"] },
        { name: "Commerce", entries: ["products", "orders"], collapsedByDefault: { drawer: true } },
    ]}
/>
```

## RebaseStudio Configuration

`<RebaseStudio>` accepts the full `RebaseStudioConfig`:

```typescript
interface RebaseStudioConfig {
    tools?: ("sql" | "js" | "rls" | "schema" | "storage" | "cron"
        | "schema-visualizer" | "branches" | "backups" | "api" | "logs" | "api-keys")[];
    homePage?: ReactNode;
    devViews?: AppView[];  // Your own Studio tools, added beside the built-in ones
}
```

## StudioHomePage Customization

The `StudioHomePage` component is the default landing page for Studio mode. It renders tool cards organized by section. It can be customized through props:

```typescript
interface StudioHomePageProps {
    additionalActions?: React.ReactNode;       // Toolbar actions at the top
    additionalChildrenStart?: React.ReactNode;  // Content before tool sections
    additionalChildrenEnd?: React.ReactNode;    // Content after tool sections
    sections?: HomePageSection[];               // Extra sections after tools
    hiddenGroups?: string[];                    // Tool section labels to hide (e.g. "Compute")
}

interface HomePageSection {
    key: string;             // Unique key
    title: string;           // Section header text
    children: React.ReactNode; // Arbitrary content
}
```

### Built-in Home Page Sections

The default `StudioHomePage` builds its sections from the Studio views actually
registered (each view's `group`), so a card exists only when its route does. With
every tool enabled:

| Section | Tools |
|---------|-------|
| Database | Collections (when the collection editor is on), SQL Console, RLS Policies, Schema Visualizer, Branches, Backups, Logs Explorer |
| Compute | JS Console, Cron Jobs |
| Storage | Storage |
| API | API Explorer |
| Access Control | API Keys |

Sections follow that order; a `devViews` group not in it is appended after, and
a view with no `group` lands in "Tools".

### Custom Home Page Examples

**Add extra sections:**
```tsx
<RebaseStudio
    homePage={
        <StudioHomePage
            sections={[
                {
                    key: "analytics",
                    title: "Analytics",
                    children: <AnalyticsDashboard />,
                },
            ]}
        />
    }
/>
```

**Add action buttons:**
```tsx
<RebaseStudio
    homePage={
        <StudioHomePage
            additionalActions={
                <Button onClick={exportAll}>Export All Data</Button>
            }
        />
    }
/>
```

**Completely replace the home page:**
```tsx
<RebaseStudio
    homePage={<MyCustomStudioHome />}
/>
```

## Custom Login View

Use `<RebaseAuth>` with the `loginView` prop to replace the default login UI:

```tsx
<Rebase client={rebaseClient} authController={authController}>
    <RebaseAuth loginView={<MyCustomLoginPage />} />
    <RebaseCMS tableCustomizations={tableCustomizations} />
    <RebaseStudio />
    <RebaseShell title="My App" />
</Rebase>
```

The `loginView` is registered into the registry via `registerAuth()` and consumed by `<RebaseAuthGate>`.

## Custom Views

Custom React views are described with the `AppView` interface:

```typescript
interface AppView {
    slug: string;                    // URL path segment
    name: string;                    // Display name
    description?: string;            // Optional description (Markdown)
    icon?: string | React.ReactNode; // Lucide icon name or custom element
    hideFromNavigation?: boolean;    // Hide from sidebar (still accessible by URL)
    group?: string;                  // Navigation group name
    pinToBottom?: boolean;           // Sink this view's group to the bottom of the drawer
    view: React.ReactNode | React.ComponentType; // Element, or a component rendered on visit
    nestedRoutes?: boolean;          // Enable nested routing (slug/*)
    roles?: string[];                // Only show to users with at least one matching role
}
```

A view passed to `<RebaseStudio devViews={[…]}>` is a Studio tool, shown in Studio mode. Custom top-level views for the CMS (content mode) are added through the `views` prop on `<RebaseCMS>`. They can also be contributed by plugins via `plugin.views`.

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

// Builder function (role-aware, async-capable)
<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 /> }]
            : []),
    ]}
/>
```

> **IMPORTANT FOR AGENTS:** The `roles` field on `AppView` provides declarative role filtering — the view is excluded entirely (not just hidden from nav) if the user lacks a matching role. Use `roles` for simple access control and the builder function for dynamic/async cases. Both approaches compose.

## CollectionPanel Component

`CollectionPanel` is a high-level wrapper for embedding collection views inside custom pages (dashboards, home pages, entity detail views):

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

type CollectionPanelProps = {
    collection: AdminCollection | string;   // Its name ("tasks") or the collection as a value
    path?: string;                          // A subcollection's full path, where the rows live
    title?: string | false;                 // Title above the collection (false = hide)
    viewMode?: ViewMode;                    // Force view mode (table, card, etc.)
    where?: FilterValues<string>;           // Which rows it holds, as useRows' where
    orderBy?: string | [string, "asc" | "desc"]; // "field:desc" or ["field", "desc"]
    toolbar?: "full" | "compact" | "none" | React.ReactElement;
    rowActions?: (row: Record<string, unknown>, id: string) => React.ReactNode; // Your JSX on every row
    limit?: number;                         // Max entities to display
    updateUrl?: boolean;                    // Sync filter/sort with URL (default: false)
    openEntityMode?: "side_panel" | "full_screen" | "split" | "dialog";
    className?: string;                     // Container CSS class
    collectionOverrides?: Partial<AdminCollection>; // Additional overrides
};
```

### Usage Examples

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

function MyDashboard() {
    return (
        <div>
            {/* Simple usage */}
            <CollectionPanel collection="tasks" title="Pending Tasks" />

            {/* With overrides */}
            <CollectionPanel
                collection="clients"
                viewMode="table"
                limit={10}
                orderBy="createdAt:desc"
                collectionOverrides={{
                    defaultFilter: { status: ["!=", "completed"] }
                }}
            />

            {/* Hide title, custom open mode */}
            <CollectionPanel
                collection="orders"
                title={false}
                openEntityMode="dialog"
            />
        </div>
    );
}
```

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

## Studio Bridge Hooks

The Studio Bridge provides CMS capabilities to Studio components. When CMS is present, real implementations are injected. When CMS is absent, noop defaults ensure Studio works standalone.

### Bridge Interface

```typescript
interface StudioBridge {
    collectionRegistry: CollectionRegistryController;
    schemaEditing: StudioSchemaEditing;   // { available, updateCollection(id, patch) }
    sidePanelController: SidePanelController;
    urlController: UrlController;
    navigationState: NavigationStateController;
    breadcrumbs: BreadcrumbsController;
    capabilities: StudioCapabilities;     // { codebase: boolean }
}
```

### Bridge Hook Reference

| Hook | Return Type | Description |
|------|-------------|-------------|
| `useStudioCollectionRegistry()` | `CollectionRegistryController` | Access registered collections from Studio |
| `useStudioSidePanelController()` | `SidePanelController` | Open/close entity side panels from Studio |
| `useStudioUrlController()` | `UrlController` | Build URLs and navigate from Studio |
| `useStudioNavigationState()` | `NavigationStateController` | Access navigation state from Studio |
| `useStudioBreadcrumbs()` | `BreadcrumbsController` | Set breadcrumbs from Studio tools |

All bridge hooks are exported from `@rebasepro/studio` (re-exported from `@rebasepro/app`):

```typescript
import {
    useStudioCollectionRegistry,
    useStudioSidePanelController,
    useStudioUrlController,
    useStudioNavigationState,
    useStudioBreadcrumbs
} from "@rebasepro/studio";
```

### BreadcrumbsController

```typescript
interface BreadcrumbEntry {
    title: string;
    url: string;
    id?: string;
}

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

### StudioBridgeProvider (Advanced)

For custom wiring, use `StudioBridgeProvider` to inject CMS capabilities:

```tsx
import { StudioBridgeProvider } from "@rebasepro/studio";

<StudioBridgeProvider value={{
    collectionRegistry: useCollectionRegistryController(),
    sidePanelController: useSidePanel(),
    urlController: useUrlController(),
    navigationState: useNavigationStateController(),
    breadcrumbs: useBreadcrumbsController(),
}}>
    <RebaseStudio />
</StudioBridgeProvider>
```

## Core Hooks Reference

These hooks are exported from `@rebasepro/app` and available inside any `<Rebase>` provider tree:

### Primary Hooks

| Hook | Return Type | Description |
|------|-------------|-------------|
| `useRebaseContext()` | `RebaseContext` | Full Rebase context with all controllers |
| `useAuthController()` | `AuthController` | Access current user and auth state |
| `useAdminModeController()` | `AdminModeController` | Read/set admin mode (`cms` / `studio`) |
| `useEffectiveRoleController()` | `EffectiveRoleController` | Simulate a role for previewing |
| `useModeController()` | `ModeController` | Read/set color theme (`light` / `dark`) |
| `useSnackbarController()` | `SnackbarController` | Show toast notifications |
| `useStorageSource()` | `StorageSource` | Access file storage |
| `useRows()` / `useRow()` / `useRowWrites()` | rows / row / writes | Rows as the server sends them, live; writes run hooks and row-level security |
| `useDialogsController()` | `DialogsController` | Programmatic dialog management |
| `useCustomizationController()` | `CustomizationController` | Access plugins, slots, property configs |
| `usePermissions()` | `{ canCreate, canEdit, canDelete, canRead }` | Role-aware permission checks |

### UI & Layout Hooks

| Hook | Return Type | Description |
|------|-------------|-------------|
| `useLargeLayout()` | `boolean` | `true` when viewport ≥ 1025px (lg breakpoint) |
| `useClipboard(options?)` | `useClipboardReturnType` | Copy/cut to clipboard with `ref` or text |
| `useSlot(name, props)` | `ReactNode \| null` | Render plugin slot contributions |
| `useTranslation()` | `{ t }` | Access `t()` for i18n translations |
| `useCollapsedGroups(groups, namespace, defaults)` | `{ isGroupCollapsed, toggleGroupCollapsed }` | Manage collapsible navigation groups |

### Navigation & Data Hooks (from `@rebasepro/cms`)

| Hook | Package | Description |
|------|---------|-------------|
| `useSidePanel()` | `@rebasepro/cms` | Open/close entity side panels |
| `useNavigationStateController()` | `@rebasepro/cms` | Read navigation state (views, top-level entries, loading, refresh) |
| `useUrlController()` | `@rebasepro/cms` | Build URLs and navigate |
| `useBreadcrumbsController()` | `@rebasepro/cms` | Set breadcrumbs |
| `useRebaseRegistry()` | `@rebasepro/app` | Access the full registry (CMS + Studio + Auth configs) |
| `useRebaseClient()` | `@rebasepro/app` | Access the `RebaseClient` instance |

### ModeController (Color Theme)

```typescript
interface ModeController {
    mode: "light" | "dark";
    setMode: (mode: "light" | "dark" | "system") => void;
}

// Usage
const { mode, setMode } = useModeController();
setMode("dark");     // Force dark mode
setMode("system");   // Follow OS preference
```

When the host app owns the theme, hand Rebase its controller with
`<Rebase modeController={…}>` (0.25+): Rebase then reads `mode`, calls
`setMode`, and never touches `<html>`, `prefers-color-scheme` or localStorage.

### useClipboard

```typescript
interface UseClipboardProps {
    onSuccess?: (text: string) => void;
    onError?: (error: string) => void;
    disableClipboardAPI?: boolean;
    copiedDuration?: number;  // ms before isCoppied resets to false
}

const { copy, cut, isCoppied, clipboard, clearClipboard, ref, isSupported } = useClipboard({
    copiedDuration: 2000
});

// Copy text directly
copy("Hello world");

// Copy from a ref
<input ref={ref} />
<button onClick={() => copy()}>Copy</button>
```

### usePermissions

```typescript
const { canCreate, canEdit, canDelete, canRead } = usePermissions();

// Check if current user can create in a collection
if (canCreate(myCollection, "products")) { ... }

// Check if current user can edit a specific row (as useRows / context.data return it)
if (canEdit(myCollection, "products", row)) { ... }
```

### useRebaseContext

Returns the full context object combining all controllers:

```typescript
const context = useRebaseContext();

// Access any controller
context.authController        // Auth state
context.data                  // Flat rows (RebaseSdkData), the same the row hooks read; writes run browserCallbacks
context.storageSource         // File storage
context.snackbarController    // Toast notifications
context.effectiveRoleController // Role simulation
context.databaseAdmin         // Database admin capabilities
context.client                // RebaseClient instance
```

## RebaseShell Configuration

`<RebaseShell>` composes all CMS layers with sensible defaults:

```typescript
interface RebaseShellProps {
    title?: string;              // App title (default: "Rebase")
    appBar?: React.ReactNode;    // Top bar — only rendered when given (or "Shell.AppBar" is overridden)
    drawer?: React.ReactNode;    // Custom drawer
    autoOpenDrawer?: boolean;    // Expand the drawer on hover (default: true)
    defaultDrawerOpen?: boolean; // Start with the drawer expanded (default: false)
    logo?: string;               // Logo path for the drawer and top bar
    children?: React.ReactNode;  // Additional route content
}
```

Internally it composes:
```
<RebaseAuthGate>
  <RebaseNavigation>
    <RebaseRouteDefs layout={<RebaseLayout>}>
      {children}
    </RebaseRouteDefs>
  </RebaseNavigation>
</RebaseAuthGate>
```

## Visual Collection Editor

The collection editor allows non-developers to:
- Add, remove, rename and reorder columns
- Configure column types and validation
- Set up enum values and relations
- Edit a table's row-level security rules

Under the hood every edit is a typed change (`TablePatch`, in
`packages/types/src/schema/table_patch.ts`) sent to `/api/admin/schema-editor`,
which rewrites the `defineTable` files in `backend/schema/` with AST
manipulation (via `ts-morph`) — preserving hooks and hand-written code — and
then compiles the result. Presentation (labels, icons, enum colours, view modes)
is not a schema edit: it lives in `frontend/src/cms/` and in UI preferences.
The server refuses, and the editor shows as read-only "edited in code", what it
cannot rewrite safely: a config built with a spread, a column built by a helper,
rules held in a variable, renaming a table's slug or SQL name (a migration), or
an edit that does not compile.

### Enabling the Collection Editor

```tsx
// Simple — uses authController.getAuthToken automatically
<RebaseCMS tableCustomizations={tableCustomizations} collectionEditor={true} />

// With options
<RebaseCMS
    tableCustomizations={tableCustomizations}
    collectionEditor={{
        getAuthToken: authController.getAuthToken,
        readOnly: false
    }}
/>
```

The backend side is on when it knows where the tables live: `schemaDir`
(`backend/schema`) outside production — which is what `rebase dev` provides.

## Where the panel's collections come from

There is no collections import in the frontend. `<RebaseCMS>` reads the
tables the backend serves from `GET /api/schema/tables` and derives a
collection for each, then layers the `tableCustomizations` over them
(`customizeTable` results from `frontend/src/cms/`) and adds any
`externalCollections` (Firestore, via `defineFirestoreCollection`). See
`rebase-tables`.

## Running the Studio

```bash
# From the project root
pnpm run dev
```

This starts both frontend and backend. The Studio is at the frontend URL `rebase dev` prints — a port derived from the project's path, in 5173–5372, not a fixed 5173.

## Key Packages

| Package | Description |
|---------|-------------|
| `@rebasepro/app` | Core framework, hooks, types, `<Rebase>` provider |
| `@rebasepro/studio` | Studio admin panel (`<RebaseStudio>`, `StudioHomePage`, bridge hooks) |
| `@rebasepro/cms` | CMS frontend (`<RebaseCMS>`, `<RebaseShell>`, `CollectionPanel`, collection editor) |
| `@rebasepro/ui` | Component library (Tailwind v4 + Radix) |
| `@rebasepro/types` | Shared TypeScript types |
| `@rebasepro/plugin-ai` | AI-powered autofill |
| `@rebasepro/inference` | Auto-infer schema from data |

## References

- **Documentation:** [rebase.pro/docs](https://rebase.pro/docs)
- **GitHub:** [github.com/rebasepro/rebase](https://github.com/rebasepro/rebase)
- **Icons:** [rebase.pro/docs/ui/icons](https://rebase.pro/docs/ui/icons) (Lucide-based)
