# Admin UI

Contribute admin menu items, pages, settings, and collection-view overrides from a plugin — and control where they appear in the sidebar.

A plugin can extend the Nextly admin in two complementary ways:

* **`contributes.admin`.** The *declarative* surface: menu entries, custom pages,
  a settings panel, and per-collection view overrides (D19–D23).
* **`admin`** (on the plugin definition) — *placement & appearance*: where the
  plugin's items sit in the sidebar and how they look (D20).

Both are `@public`. Admin **dashboard widgets** are declared with `defineWidget` under
`contributes.dashboard`, and are rendered on the admin dashboard today, but the contract
remains [`@experimental`](https://nextlyhq.com/docs/plugins/stability.md) while its shape settles.

## Component paths

Admin contributions reference React components by **string path**, not by import, so the
declarative surface stays serializable and Node-safe:

```
"<package>/<subpath>#<ExportName>"
// e.g. "@acme/nextly-plugin-reports/admin#ReportsView"
```

Register the components those paths resolve to from your plugin's `/admin` entry, which
runs inside the admin shell:

```ts
// src/admin/index.ts
import { registerComponents } from "@nextlyhq/plugin-sdk/admin";
import { ReportsView } from "./ReportsView";

registerComponents({
  "@acme/nextly-plugin-reports/admin#ReportsView": ReportsView,
});
```

An app loads these through its **component map**, two generated files beside its generated
types (D60):

* `plugin-admin-imports.generated.ts` imports and registers every plugin admin component, and
  the app's admin page imports it.
* `plugin-admin-components.generated.ts` lists the same paths as plain strings, and the admin's
  server layout passes them to `checkAdminComponents` from `nextly/runtime`.

The app commits both. `nextly generate:types` writes them, and `next dev` rewrites them when
they fall behind the config. `NEXTLY_GENERATED_FILES_WRITE=0` turns that off, for a read-only
checkout or a test run, and the server log then names each missing component and the switch.

Check the committed map in CI with `nextly generate:types --check`. It writes nothing, and
exits 2 naming each missing component and each path no longer declared, or 1 when it cannot
load the config:

```bash
npx nextly generate:types --check
```

`--check` and `--dry-run` are refused together: `--check` exits non-zero when the map is out
of date, while `--dry-run` lists the files a real run would write and exits 0.

Production never reads, checks or writes the map. A dashboard widget whose component is missing
from it draws its own card's error state, and every other card and page draws as usual. In
development the error names the widget, its owner and the missing path; in production it says
only that the card could not be drawn. Other components missing from the map draw empty.

After a map change in development, the request that finds the map out of date is already
being served when the map is rewritten, so that one render can still draw the new widget's
card in its error state. The rewritten map is what the next render loads.

**`next dev` keeps the map current once the admin layout calls the check.** New apps do both:
their admin page imports the map and their admin layout calls the check. An app made from an
older template may have neither, so a plugin's components are not registered: its widget cards
draw their error state, and its other components draw empty, until it adds them:

```tsx
// src/app/admin/[[...params]]/page.tsx: with the other imports
import "../../../types/generated/plugin-admin-imports.generated";
```

```tsx
// src/app/admin/[[...params]]/layout.tsx
import { connection } from "next/server";
import { Suspense } from "react";
import { checkAdminComponents } from "nextly/runtime";

import config from "../../../../nextly.config";
import { registeredComponentPaths } from "../../../types/generated/plugin-admin-components.generated";

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <Suspense fallback={null}>
      <ForThisRequest>{children}</ForThisRequest>
    </Suspense>
  );
}

async function ForThisRequest({ children }: { children: React.ReactNode }) {
  await connection();
  await checkAdminComponents({ config, registeredComponentPaths });
  return children;
}
```

Keep anything your layout already renders, such as branding styles, around the `<Suspense>`
element. The check goes in the component beneath the boundary because, under Cache
Components, request work outside one fails the build.

Then run `npx nextly generate:types` once and commit the two generated files. The paths
assume the default types location (`./src/types/generated/`); use the folder your
`typescript.outputFile` names.

## UI building blocks (`@nextlyhq/ui`)

Build your admin components out of the shared **plugin UI kit**, `@nextlyhq/ui` — the
semver-protected surface of React primitives the admin itself is built from (D68/D53).
The host provides it (and React) as a **peer dependency**, so you and the admin share one
version and one theme:

```tsx
// src/admin/ReportsView.tsx
import {
  Button,
  Input,
  Checkbox,
  Select,
  Card,
  Table,
  FormLabelWithTooltip,
} from "@nextlyhq/ui";
```

Which of these primitives are covered by a stability guarantee is recorded in
[`packages/ui/STABILITY.md`](https://github.com/nextlyhq/nextly/blob/main/packages/ui/STABILITY.md):
a component becomes `@public` once a first-party plugin depends on it, and everything
else is `@experimental` and may change in any release.

Register components and reference admin contribution types through
`@nextlyhq/plugin-sdk/admin`; import UI primitives from `@nextlyhq/ui`.

> **Never import from `@nextlyhq/admin`.** It is an application, not a published API —
> reaching into it (e.g. `@nextlyhq/admin/lib/*`) is unsupported and will break. If a
> primitive you need isn't yet exported from `@nextlyhq/ui`, open an issue so it can be
> promoted to the kit rather than copied.

## Styling your admin UI

The admin ships a single, precompiled, isolated stylesheet (every rule scoped under
`.nextly-admin`). Because it is built ahead of time, Tailwind cannot see utilities that
live only in your package — so there are three ways to style a plugin, in order of
preference:

**1. Compose from the kit.** `@nextlyhq/ui` components are already styled by the admin
sheet, so a plugin built from them needs no styling work at all. Reach for the layout
primitives for common structure:

```tsx
import { Card, Stack, Grid, Stat } from "@nextlyhq/plugin-sdk/admin";

<Card>
  <Stack gap={4}>
    <Grid cols={3} gap={4}>
      <Stat label="Submissions" value={1280} />
      <Stat label="This week" value={64} />
      <Stat label="Conversion" value="4.2%" />
    </Grid>
  </Stack>
</Card>;
```

**2. Use safelisted utility classes.** A curated, token-driven set of Tailwind utilities is
always present in the admin sheet, so you can use them directly in your components with no
build step: layout (`flex`, `grid`, `grid-cols-{1..6}`, `gap-{0..8}`, `items-*`,
`justify-*`), spacing (`p-*`, `m-*`, `space-*`), sizing (`w-*`, `max-w-*`, `size-*`),
typography (`text-{xs..2xl}`, `font-*`, `truncate`, `line-clamp-*`), token colors
(`bg-primary`, `text-muted-foreground`, `border-border`, …), and borders/radius/shadow.
These are **token-driven only** — no arbitrary values or raw colors, so your UI themes in
light and dark automatically.

**3. Ship your own CSS (`admin.styles`).** For anything beyond the safelist, compile a
scoped, token-driven stylesheet with the `nextly-build-admin-css` CLI (from
`@nextlyhq/admin-css`, add it as a devDependency) and declare it in your manifest.

Your CSS is compiled in **your** package, not by the host. That is deliberate: the admin
sheet is built when Nextly is released, so it can never scan a plugin that is installed
later, and pointing Tailwind at an installed package with `@source` is not a reliable
substitute — it does not accept package references, and it resolves inconsistently under
pnpm, which is what this repository and many plugin projects use. Compiling ahead of time
means your styles do not depend on the host's build at all.

```css
/* src/admin.css — author against the shared token preset */
@import "tailwindcss";
@import "@nextlyhq/ui/theme.css";
@source "./src";
```

```jsonc
// package.json
{
  "scripts": {
    "build:css": "nextly-build-admin-css src/admin.css dist/admin.css",
  },
}
```

```ts
// your plugin definition
contributes: {
  admin: {
    styles: "@acme/plugin/dist/admin.css";
  }
}
```

Then side-effect-import the built file from your admin entry so the host app's bundler
loads it:

```ts
// src/admin/index.ts
import "../../dist/admin.css";
```

The CLI compiles your Tailwind, **scopes every rule under `.nextly-admin`**, and refuses to
emit if a rule would escape that wrapper or if it finds a hardcoded color — so your styles
can never leak into the host page and always theme correctly. Use `--nx-*` tokens (via
`var()` or the token utilities), never literal colors.

## Declarative contributions

```ts
contributes: {
  admin: {
    // Sidebar entries (D20). One level of children is supported.
    menu: [
      { label: "Reports", to: "/admin/plugins/reports", icon: "BarChart",
        order: 10, requiredPermission: "read-reports" },
    ],
    // Custom pages, namespaced under /admin/plugins/<slug>/<path>, RBAC-gated (D21).
    pages: [
      { path: "summary", component: "@acme/nextly-plugin-reports/admin#ReportsView",
        requiredPermission: "read-reports" },
    ],
    // A settings panel rendered at /admin/plugins/<slug> (D21).
    settings: { component: "@acme/nextly-plugin-reports/admin#ReportsSettings" },
    // Per-collection view overrides + injection points, keyed by slug (D23).
    views: {
      posts: {
        beforeList: "@acme/nextly-plugin-reports/admin#PostsBanner",
        edit: "@acme/nextly-plugin-reports/admin#PostsEditor",
      },
    },
  },
}
```

`menu` and `pages` honour `requiredPermission` for client-side gating (see
[Permissions](https://nextlyhq.com/docs/plugins/permissions.md)). View override slots are `list`, `edit`,
`beforeList`, `afterList`, `beforeEdit`, `afterEdit`.

### Document views

> **Experimental.** `documentViews` and `DocumentViewProps` may change before
> they are marked stable.

A document view is a full-screen screen for one document, at its own address
under the document's:

* `/admin/collections/<slug>/<id>/<path>` for a collection entry;
* `/admin/singles/<slug>/<path>` for a Single.

A view declared under `views[slug]` is for that collection, like every other
slot there. A Single, or any document wherever a field type appears, is reached
by a field-type view (below).

```ts
views: {
  pages: {
    documentViews: [
      { path: "builder", component: "@acme/nextly-plugin-builder/admin#Builder",
        label: "Builder" },
    ],
  },
},
```

A plugin that contributes a field type can instead offer a view on every
collection and Single that has a field of that type. This includes collections
created in the Schema Builder later:

```ts
contributes: {
  fieldTypes: [{ type: "blocks", storage: "json", component: "@acme/x/admin#Blocks" }],
  admin: {
    documentViews: [
      { path: "builder", fieldType: "blocks",
        component: "@acme/x/admin#Builder", label: "Builder" },
    ],
  },
},
```

A view can be scoped only to a field type the same plugin contributes. A field
counts at the top level or inside named groups, at any depth. The address names
it by its path from the document's root (`?field=hero.body`). A field inside an
unnamed group is named as if it were at the top level, because the group only
arranges the form. A field inside a repeater doesn't count: a row is addressed
by its position, and the position names another row once the rows are
reordered. A field-type view's `path` must be unique among every document view
any plugin declares.

The admin keeps the document's own behaviour around your view, so you don't
build any of it yourself:

* It loads the document and holds its form state.
* It holds the document's soft lock, and shows who else is editing (see
  [Editing with others](https://nextlyhq.com/docs/admin/editing-together.md)).
* It saves with the version of the document the form started from. A save
  refused because someone changed the document since opens the admin's conflict dialog (see
  [When your save is refused](https://nextlyhq.com/docs/admin/editing-together.md#when-your-save-is-refused)).
* It offers unsaved work recovered after a crash or a reload. Restoring it
  unmounts your view, replaces the form's values, then mounts your view again.
  A view that keeps its own copy of the document, read when it mounts, starts
  from the restored work, and anything it writes into the form as it unmounts
  is replaced by the restore.
* It asks before the author leaves with unsaved changes.
* It saves on the form's own shortcut, through the same actions as the edit form.

Your component replaces the form's body and receives `DocumentViewProps` from
`@nextlyhq/plugin-sdk/admin`:

| Prop                        | What it is                                                                                                                                                                                                                                                                                                   |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `collectionSlug`, `entryId` | The collection entry being shown.                                                                                                                                                                                                                                                                            |
| `singleSlug`                | The Single being shown, instead of the two above.                                                                                                                                                                                                                                                            |
| `control`                   | The document form's react-hook-form `control`. Write to the fields through it.                                                                                                                                                                                                                               |
| `readOnly`                  | `true` while someone else holds the document. Don't offer edits then.                                                                                                                                                                                                                                        |
| `exit`                      | Goes back to the document's edit form. Commit any state you hold into the form first.                                                                                                                                                                                                                        |
| `field`                     | For a field-type view, the declaration (`FieldConfig`, as a field editor receives it) of the field it edits. When the document has several such fields, it is the one the address names (`?field=<path>`). If the address names none of them, the admin asks the author which one before it draws your view. |
| `fieldPath`                 | For a field-type view, where that field sits in the form, from the document's root: `layout` at the top level, `hero.body` inside a named group. Bind to the field through this, not `field.name`, which names the field within its own group only. Experimental.                                            |

Opening that address requires the same permission as editing the document.
A field-type view also opens only for a field the edit form would let the
author edit. If the field, or any group around it, is read-only,
disabled, hidden, or hidden by its condition, the admin says why and offers the
way back instead of drawing your view.

To open a view from inside the admin, for example from a field editor, call
`navigateTo(path)` from `@nextlyhq/plugin-sdk/admin`. It accepts a path
starting `/admin/`, and refuses anything else by throwing. Moving between a
document's edit form and its own views doesn't prompt about unsaved
changes, because the same form stays mounted.

Startup is refused, naming the plugins involved, when a view's `path`:

* is not one segment of lowercase letters, digits and single dashes;
* is `versions` or `api`, which the document already uses;
* is declared twice on the same collection or Single, or is the path of a
  field-type view and declared anywhere else;
* belongs to a field-type view scoped to a field type the plugin does not
  contribute.

#### The header's controls in your view

> **Experimental.** These may change before they are marked stable.

Your view replaces the header, and the header's save state and Publish with it.
Place `<DocumentSaveIndicator />` and `<DocumentPrimaryAction />`, from
`@nextlyhq/plugin-sdk/admin`, wherever your view draws its toolbar:

* `DocumentSaveIndicator` says whether the work is stored: **Saving…**,
  **Unsaved changes**, **Saved** (when, in its tooltip) or **Not saved** with
  **Retry**. It keeps the width of its longest state, so nothing beside it
  moves, and screen readers hear it as they hear the header's. `className`
  places it.
* `DocumentPrimaryAction` is the action that leads (**Publish**, **Publish
  changes** or **Save**, as in the header). Its arrow holds **Save draft**, the
  other ways to publish, such as **Schedule publish…**, and **Unpublish**. An
  action that can't run right now is disabled, with the reason it is held.

Both are the admin's own controls, run through the same actions as the
header. Outside a document they render nothing.

### Document actions and panel sections

> **Experimental.** `documentActions`, `panelSections` and the props below may
> change before they are marked stable. Collections only: a Single's document
> screen is not changed by them yet.

Two more keys under `views[slug]` change what a collection's document screen
offers, for that collection only. Every other collection keeps the admin's own
screen.

`documentActions` hides or replaces a built-in action in the document's
**More actions** menu. It takes `delete` and `unpublish`, each set to
`"hidden"` or to `{ component, label? }`. For example,
`documentActions: { unpublish: "hidden", delete: { component: "@acme/plugin-layouts/admin#RemoveLayoutDialog", label: "Remove layout…" } }`
takes Unpublish away and routes Delete to the plugin's own dialog.

* A hidden action is not offered at all, from the menu or from
  `useDocumentActions().run`, which refuses it as not offered.
* A replaced action keeps its row: its place, the permission it needs, and
  every reason it can't run right now (a colleague holding the document, a past
  version on screen) still apply. Choosing it mounts your component instead of
  the admin's own confirmation and write, so a dialog renders open. Running it
  with `run("delete")` opens your component too, and answers once it closes.

Until the admin has loaded which plugins are installed, Delete and Unpublish
can't be chosen on any collection's document, because a plugin that hides or
replaces one isn't known yet and the built-in write must not run in the
meantime. Each row says why:

* While the list loads, the row reads "Loading this collection's plugin
  actions…" and clears itself once the list arrives.
* If the list failed to load, the row names its action, for example "Couldn't
  load this collection's plugin actions, so Delete is paused.", with a
  **Retry** row under it. Retry asks for the list again, the row reads as
  loading while it does, and then the plugin's own override applies.

`useDocumentActions().run` refuses the action with the same words. Running a
replaced action that is already open joins it, and both callers get the same
answer when it closes.

Your component receives `DocumentActionReplacementProps` from
`@nextlyhq/plugin-sdk/admin`:

| Prop                         | What it is                                                                                                                                                                                                                                      |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `action`                     | Which action the author chose: `"delete"` or `"unpublish"`.                                                                                                                                                                                     |
| `collectionSlug`, `entryId`  | The document.                                                                                                                                                                                                                                   |
| `documentLock`, `mayWrite()` | What holds the document, kept current while your component is open, and whether it may be written right now. Call `mayWrite()` immediately before your write, after anything you awaited: the document can change hands while a dialog is open. |
| `close(result?)`             | Ends it. `close("deleted")` leaves the document for its collection's list, as the built-in Delete does. `close("changed")` reads the document again. `close()` means the author backed out.                                                     |

Both your replacement and your panel section are drawn inside the document's
editor, so `useDocumentLocale()` names the language being edited (the one a
replaced Unpublish of a translation acts on) and `useDocumentActions()` answers
for the same document.

If your component isn't registered, or throws while drawing, the admin closes
it, tells the author the action couldn't open, and answers a waiting
`run("delete")` as cancelled. When you report `"changed"`, the document is read
again and the author's unsaved edits stay over it, as after their own save.

`panelSections` adds sections to the document panel, after **Details**, in the
order given: `panelSections: [{ title: "Used by", component: "@acme/plugin-layouts/admin#LayoutUsage" }]`.
The admin draws each section's heading, spacing and divider, as it does for its
own sections, so the section reads as part of the panel in light and dark. Your
component draws only what goes under the heading. Nothing is drawn while a
document is being created. It receives `DocumentPanelSectionProps`:

| Prop                        | What it is                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `collectionSlug`, `entryId` | The document.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `documentLock`              | `{ readOnly, actionsDisabled }`, what holds the document right now. `readOnly` follows the fields: a colleague's claim, a past version on screen, a reader's page, or the editor still readying the document. `actionsDisabled` follows the built-in Delete: a colleague's claim, a past version, a collection removed from code, or the editor readying it. A reader's page alone doesn't hold your writes, because your route judges its own permission. Hold your writes while `actionsDisabled`. |
| `mayWrite()`                | Whether the document may be written right now. Call it immediately before a write, after anything you awaited.                                                                                                                                                                                                                                                                                                                                                                                       |
| `documentChanged(result)`   | Tell the editor your section changed the document: `"deleted"` leaves for the collection's list, `"changed"` reads the document again.                                                                                                                                                                                                                                                                                                                                                               |

Startup is refused, naming the plugins involved, when an override names an
action other than `delete` or `unpublish`, when a replacement or a section has
no component (or a section no title), or when two plugins override the same
action on the same collection.

### Who is signed in

`useCurrentUserId()` from `@nextlyhq/plugin-sdk/admin` answers the signed-in user's id, for a
plugin that keeps something per user, such as its own preferences on a browser several
people share. It reads what the admin already knows about the user, so it makes no request.

It answers `null` while that isn't known yet, when no one is signed in, and when the read
failed. Keep nothing then, rather than keeping it for a guess.

```tsx
import { useCurrentUserId } from "@nextlyhq/plugin-sdk/admin";

const userId = useCurrentUserId();
const key = userId === null ? null : `my-plugin.layout:${userId}`;
```

This hook is experimental while its first consumer settles. Its name and its
`string | null` answer are meant to stay.

### Translating your strings

A plugin declares its admin strings in `contributes.translations`, by interface language and
then by key, and its components read them with `usePluginTranslate()` from
`@nextlyhq/plugin-sdk/admin`:

```tsx
// In definePlugin({ ... })
contributes: {
  translations: {
    en: { "acme-shop.cart.title": "Cart", "acme-shop.cart.count": "{count} items" },
    fr: { "acme-shop.cart.title": "Panier" },
  },
}

// In a component
const t = usePluginTranslate();
t("acme-shop.cart.title"); // "Panier" in French, "Cart" in English
t("acme-shop.cart.count", { count: 3 }); // "3 items"
```

Every key begins with your plugin's admin slug and a dot (`@acme/shop` is `acme-shop`). A string
is read in the interface language, then English, then the key itself. Startup refuses a key
outside your namespace, a malformed key or language, a language not spelled as browsers report it
(`pt-BR`, not `pt-br`), a value that isn't text, and a key another plugin declares. A disabled
plugin's strings are still served, since its field editors still show. The admin's own strings begin with `nextly.`, so a plugin slugged `nextly` can
declare none. The strings reach signed-in readers only, so they are not yet on the sign-in
screen.

This surface is experimental while its first consumer settles.

## Dashboard widgets

A plugin adds dashboard widgets under `contributes.dashboard.widgets`, each declared with
`defineWidget` from `@nextlyhq/plugin-sdk` (**experimental**). A declaration says what the
widget is (`id`, `title`, `description`, `size`), who is offered it (`access`), where its data
comes from (`load`, run on the server for each card, as the person viewing it) and how it is
drawn (`view`): one of core's views, or a component of your own. Startup checks every
declaration with the rest of the config.

```ts
import { definePlugin, defineWidget } from "@nextlyhq/plugin-sdk";

export const publishedReports = defineWidget({
  id: "reports/published",
  title: "Reports",
  description: "How many reports there are.",
  size: { default: { w: 3, h: 2 } }, // 12-column grid units: w 1–12, h 2–12
  access: "read-reports", // decided on the server, before the card is offered
  view: "figure",
  load: async ({ services }) => ({
    total: await services.count("reports"),
  }),
});

export const reports = definePlugin({
  name: "@acme/nextly-plugin-reports",
  version: "1.0.0",
  nextly: "*",
  contributes: { dashboard: { widgets: [publishedReports] } },
});
```

`access` is a permission spelled as stored (`"read-reports"`), `{ anyOf }` or `{ allOf }` of
several, `{ collections }` (the reader must be able to read each), or a function of the person.
Without it, everyone who can open the dashboard is offered the widget. `load` reads through the
`services` it is handed, bound to the viewer, so a card only ever counts and lists what that
person may read. Settings, sizes, what a load can read, and testing a widget are on
[Dashboard Widgets](https://nextlyhq.com/docs/widgets.md).

### Let the host draw it

Name one of core's views and ship no UI code. Core draws the card from what `load` returns, and
the answer's shape is checked against the view twice: when the declaration compiles, and when
an answer arrives.

| `view`     | Draws              | `load` returns                                        |
| ---------- | ------------------ | ----------------------------------------------------- |
| `"figure"` | One number         | `{ total }`, with `atLeast: true` for a floor         |
| `"list"`   | One line per row   | `{ items }`, with `fields` and `total` if it has them |
| `"table"`  | A column per field | `{ items }`, with `fields` and `total` if it has them |
| `"bars"`   | A bar per group    | `{ buckets: [{ value, count }] }`                     |
| `"series"` | Counts over time   | `{ points: [{ start, count }], interval }`            |

> A `list` draws one line per row. Its fields are the answer's `fields`, in order, or the first
> row's keys when it names none: the first titles the row, a field of choices (a status) sits
> at its end, and up to three others join the line under the title. On a large card the rows
> become a table with every field.
>
> A `table` draws a column per field, headed by the `label` its entry in `fields` gives, so a
> heading reads "Published at", not `publishedAt`. A load that reads through its `services`
> reads as the viewer, so a field they may not read is absent from their rows, and its column
> with it.
>
> A list or table whose rows carry no field to draw says so on the card rather than guessing.
>
> `total` is how many rows the read matched in all, for the card's "View all (N)" link.

There is no core view for a column of shortcuts, for prose, or for several numbers in one card.
A widget declared with `defineWidget` under `contributes.dashboard` draws one of those with its
own component, below, handed its `load`'s data. `access` gates the whole card: nothing in a
declaration gates one item inside it.

### Where a card sits

Someone who has never arranged their dashboard sees the **default dashboard**, and there is
one: the site's `admin.dashboard.defaultLayout`, or core's own when the site gives none.
Everyone gets the same default, less the cards they may not see: a widget whose permission or
`access` refuses them, or whose `shows` answers no.

Core's own default holds, in order: Set up your project across the row; Needs attention beside
Upcoming releases; Continue where you left off beside Content; then the form builder's new
submissions card, where the form-builder plugin is installed, beside Team activity. While only
one of Needs attention and Upcoming releases is on show, it is drawn across the whole row; its
saved size does not change.

No widget a plugin declares with `defineWidget` is placed on any dashboard on its own: the add
panel offers it, and a reader adds it from there. A site that wants a plugin's widget on its
default names it in `defaultLayout`, as below, marked `optional` where the plugin may be absent.

`contributes.dashboard.suggest` is deprecated: it is still checked at startup (each id must be
one of the plugin's own widgets), and it places nothing. A plugin that used it to put a card on
the default dashboard should say in its README which `defaultLayout` entry a site adds for it.
The site's `admin.dashboard.suggestions` is deprecated for the same reason: it is still checked
(`true` or `false`) and changes nothing, since no card follows the default to turn off.

A site writes its own default as widget ids, or as cards with a size in grid units and
starting settings. An entry marked `optional` is left out where its widget is not installed,
such as a plugin's on a site without that plugin, and takes none of the dashboard's room; any
other entry must name a widget the install has, or startup refuses it. A widget that allows
several cards may be listed more than once: each further card names an `id` of its own, which
no other card and no widget has, and keeps its own settings under it:

```ts
admin: {
  dashboard: {
    defaultLayout: [
      "core/needs-attention",
      { widget: "acme/orders-by-state", w: 6, h: 4, optional: true },
      "core/continue",
      { widget: "core/count", settings: { collection: "posts" } },
      { widget: "core/count", id: "pages-count", settings: { collection: "pages" } },
    ],
  },
}
```

A plugin adds widgets only under `contributes.dashboard.widgets`, each declared with
`defineWidget`. Startup refuses a plugin that still carries `contributes.admin.widgets` or
`contributes.widgetSources`, naming the plugin and the key.

A reader's saved layout, once they have arranged their dashboard, wins over all of this.
Think of the default as where a card starts, not where it stays.

### Hiding, replacing and overriding widgets

The site config can change any widget, built-in or a plugin's, for everyone:

```ts
admin: {
  dashboard: {
    hide: ["core/team"],
    replace: { "core/continue": "acme/recent-orders" },
    overrides: {
      "core/team-activity": {
        title: "Latest changes",
        size: { max: { w: 6, h: 6 } },
        settings: { limit: 5 },
      },
    },
  },
}
```

* **`hide`**: nobody is offered a hidden widget and no card of it is drawn. Cards already saved
  are kept, and come back where they were once the widget is no longer hidden.
* **`replace`**: a plugin offers an alternative to a built-in in `contributes.dashboard.alternatives`,
  and the site puts it in the built-in's place. The default places the alternative where the
  built-in was, at the alternative's own starting size. The built-in is then kept off the
  dashboard like a hidden widget, and an alternative no `replace` names is never offered.
* **`overrides`**: a new title, description, starting settings, or sizes narrowed within the
  widget's own. An override never widens a widget's sizes; startup refuses one that would.

Each holds on every door at once: the add panel, the default, the cards a dashboard draws and
the card data the server answers.

### The card frame and its states

Every card draws in one frame: a header of one fixed height, the body, and at most one footer
link. The header shows the card's subject as its title (a collection card set to Posts reads
"Posts"), with the widget's own name beneath it when the two differ ("Count"), then the card's
quick control and its menu, in the same place on every card. A widget may mark up to three
settings `quick`: the header draws the first, and the card's quick popover, opened from its
title or from Settings in its menu, holds them all with the card's Collection and Size. The
menu lists Settings, Size, Refresh and Remove. A card does not say when its data arrived.

The frame also owns the states, so a card never draws its own: a skeleton while data has never
arrived, the last value marked busy while it refreshes, an empty state, one "Not available to
you" state for a source the reader cannot see (forbidden, missing and hidden all read the same),
and an error that keeps the title and offers Retry for that card only. Figures go through
`formatCount` from `@nextlyhq/ui/format`, so a number reads the same on every card.

A component whose own data says the card is not ready (the answer holds nothing it can show, or
something it cannot read) returns `FrameState` from `@nextlyhq/plugin-sdk/admin` with that state,
and the frame draws it in the body's place: for an empty answer, for example,
`<FrameState state={{ kind: "empty", empty: { title: "No orders yet" } }} />`.

A widget that should leave the dashboard while it has nothing to show, rather than say so,
declares `hidesWhenEmpty: true`. A card that failed, or whose source the reader cannot see, is
never hidden, and customise mode still shows it, marked "Hidden while empty".

Every card is framed: there is no way to decline the frame, and a widget that names `chrome` is
refused at startup.

> [!NOTE]
> `core#` is reserved. Core's own dashboard cards resolve their components under
> that prefix, and the admin refuses to let anything else register or unregister
> one — a plugin claiming the path would replace the body drawn for a card the
> registry still attributes to core.

### Items in Needs your attention

A plugin adds a line to the Needs your attention card, rather than a card of its own, through
`contributes.dashboard.attention` (**experimental**). Each item has an `id` in your plugin's
namespace, a one-line `label`, a `count` taken as the person asking, a `link` inside the admin,
and exactly one of `permission` or `collections` saying who sees it. An optional one-line
`reason` is drawn under the label, saying why the item is waiting; without one, the row has no
reason line. Plugin items rank as warnings, after core's critical items.

```ts
import { defineAttentionItem } from "@nextlyhq/plugin-sdk";

export const unanswered = defineAttentionItem({
  id: "forms/submissions",
  label: "Form submissions",
  reason: "Read and answer them",
  collections: ["form-submissions"],
  count: ({ services, signal }) =>
    services.count("form-submissions", { signal }),
  link: "collections/form-submissions",
});
```

### Draw it yourself

Name a component path as the `view`, and register the component from your plugin's `/admin`
entry, as every admin component is (see [Component paths](#component-paths)). The host still
draws the card's frame: the header, the footer that holds your body's one link, and the loading,
not-available and error states. Your component draws the body:

```ts
import { defineWidget } from "@nextlyhq/plugin-sdk";

export const recentReports = defineWidget({
  id: "reports/recent",
  title: "Recent reports",
  description: "The latest reports, newest first.",
  size: { default: { w: 6, h: 4 } }, // 12-column grid units: w 1–12, h 2–12
  access: "read-reports",
  view: { component: "@acme/nextly-plugin-reports/admin#RecentReports" },
  load: async ({ services }) => {
    const { items } = await services.find("reports", {
      sort: "-createdAt",
      limit: 8,
    });
    return { items };
  },
  // Required for a component of your own: only you can tell when its data is empty.
  isEmpty: data => data.items.length === 0,
});
```

The component is handed `WidgetProps<typeof recentReports>`, typed from the declaration, so its
`data` is what that `load` returns:

```tsx
import type { WidgetProps } from "@nextlyhq/plugin-sdk/widgets";

import type { recentReports } from "./widgets";

export function RecentReports({
  data,
  size,
  refreshing,
}: WidgetProps<typeof recentReports>) {
  const shown = size.tier === "large" ? data.items : data.items.slice(0, 4);
  return (
    <ul aria-busy={refreshing}>
      {shown.map((report: Record<string, unknown>, index: number) => (
        <li key={index}>{String(report.title)}</li>
      ))}
    </ul>
  );
}
```

| Prop          | What it is                                                                                                                                                        |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `widgetId`    | The widget's id.                                                                                                                                                  |
| `placementId` | The **card's** id. One widget may sit on a dashboard twice, and everything belonging to a card, its settings and its answer, is keyed by this, not by `widgetId`. |
| `settings`    | This card's settings, already resolved: the reader's stored values where they are usable, your declared defaults everywhere else, typed from the declaration.     |
| `size`        | The card's `w` and `h` in grid units, and its `tier`: `"small"`, `"medium"` or `"large"`.                                                                         |
| `data`        | The card's answer, always present: the frame draws loading, not available and error itself, and calls your component only once there is data.                     |
| `refreshing`  | Whether a newer answer is on its way; `data` is the last one until it lands.                                                                                      |
| `retry`       | Asks for the card's data again.                                                                                                                                   |

A `load` that throws fails its own card, which shows the frame's error with Retry, while every
other card keeps its answer. The types come from `@nextlyhq/plugin-sdk/widgets`, which carries
no runtime code, so importing them adds nothing to your bundle.

Widgets are drawn on the admin dashboard by `WidgetGrid`, in a 12-column grid that collapses to
one column on small screens, and every card on the page is answered in one batched request. A
widget its reader may not be offered (`access`) is neither drawn nor answered for them.

The contract is still `@experimental` and is expected to grow. Pin your Nextly version while it
settles.

Everything else on this page is `@public` today.

## Placement & appearance

The plugin's own `admin` field controls where its items live (D20):

```ts
import { definePlugin } from "@nextlyhq/plugin-sdk";

definePlugin({
  name: "@acme/nextly-plugin-reports",
  version: "1.0.0",
  nextly: ">=0.0.2-alpha.63",
  // ...
  admin: {
    placement: "collections", // collections | singles | users | settings | plugins | standalone
    order: 10, // lower = higher; default 100
    after: "collections", // anchor for standalone icons
  },
});
```

Placement defaults to `plugins`. `standalone` gives the plugin its own top-level icon,
anchored after the section named by `after`.

The value is written out rather than read from the `AdminPlacement` constant, which ships
from `nextly` and not from `@nextlyhq/plugin-sdk`. The SDK is the only surface a plugin
should depend on, so reaching into core for a constant would tie your plugin to core's
layout for the sake of one string. A host config, which already imports from `nextly`,
can use the constant, and does so below.

## Host overrides (D49)

An integrator can override a plugin's placement without forking it, via
`defineConfig({ admin: { pluginOverrides } })` — keyed by the plugin's admin slug: its
package name lower-cased, with every run of other characters turned into one dash and
leading and trailing dashes dropped (`@acme/nextly-plugin-reports` →
`acme-nextly-plugin-reports`). A key written as the package name is never looked up, and
the override is ignored without an error:

```ts
// nextly.config.ts
import { AdminPlacement, defineConfig } from "nextly";
import { reports } from "@acme/nextly-plugin-reports";

export default defineConfig({
  plugins: [reports()],
  admin: {
    pluginOverrides: {
      "acme-nextly-plugin-reports": {
        placement: AdminPlacement.SETTINGS, // move it
        order: 5,
        after: "users",
        appearance: { label: "Analytics" }, // shallow-merged
      },
    },
  },
});
```

The override wins over the plugin's own `admin` config, so operators stay in control of
their sidebar.

See also: [Permissions](https://nextlyhq.com/docs/plugins/permissions.md) · [Author guide](https://nextlyhq.com/docs/plugins/author-guide.md).
