# Dashboard Widgets

Put the numbers your team actually checks on the admin dashboard.

The admin dashboard is built from widgets. Each one is a single declaration, written with
`defineWidget`: what it is, who is offered it, how its data is loaded on the server as the
person looking, and how it is drawn. Core's own widgets are declared the same way.

## Quick start

From your app's root, or your plugin's:

```bash
npx nextly generate:widget open-orders
```

It writes a working widget and its test, and lists the widget where yours are listed: a site's
in `admin.dashboard.widgets`, a plugin's in its `contributes.dashboard.widgets`. Choose how it
shows its data with `--view figure` (the default), `list`, `table`, `bars`, `series` or
`component`, which writes a component of your own. `--collection` makes it read from a
collection the reader chooses. On a terminal it asks for anything you leave out.

* A site's widgets are named `site/<name>`, and a plugin's are named under the plugin's own name.
* It never writes over a file that exists, unless you pass `--force`. Generating a widget again
  with `--force` leaves it listed once. It will not switch a widget between a component of its
  own and a core view: it names the files to remove first.
* The test imports `@nextlyhq/plugin-sdk` and boots on `@nextlyhq/adapter-sqlite`, so a project
  without them gets them added to its `devDependencies`, at your `nextly` version; run your
  package manager's install afterwards.
* With `nextly -c <path> generate:widget`, it lists the widget in the config that path names.
* `--dry-run` shows the files and the config edit without writing them.
* When it cannot edit your config safely, it leaves the file as it was and prints the line to add.

Then open `/admin/dev/widget-previews` on your dev server to see the card before it has data,
and run its test with `npx vitest run`.

## Availability

|                            |                                                                                                                                                                 |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Built in                   | The widget system, core's widgets and admin rendering all ship                                                                                                  |
| Plugin-contributed widgets | **Experimental.** They render, but `defineWidget` and its shape are still settling — see the [stability ladder](https://nextlyhq.com/docs/plugins/stability.md) |
| Permission                 | A widget's `load` reads as the viewer, so two people can see the same dashboard and different numbers                                                           |

## Declaring a widget

A plugin declares its widgets under `contributes.dashboard.widgets`, with `defineWidget` from
`@nextlyhq/plugin-sdk`, the only surface a plugin imports from. A site declares its own under its
config's `admin.dashboard.widgets`, and there `defineWidget` may also come from `nextly`. Startup
checks every declaration with the rest of the config, and names every fault it finds in one
message.

```ts
contributes: {
  dashboard: { widgets: [ordersThisMonth, recentOrders] },
}
```

A widget is drawn one of two ways. It can 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 }`            |

Or it can name a component of its own, `view: { component: "<package>/admin#Name" }`, which the
admin draws inside the card's frame; such a widget also says, with `isEmpty`, when its data is
empty, since core cannot tell that for a component it does not draw. The frame draws every
state but ready either way: loading, empty, not available and error. See
[Plugin admin UI](https://nextlyhq.com/docs/plugins/admin-ui.md#dashboard-widgets) for both, and for the props a
component is handed.

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

A widget's size is `{ w, h }` on a grid 12 columns wide, with rows of one fixed height: `w` is
from 1 to 12 columns and `h` from 2 to 12 rows. It declares the size a card starts at and, if it
likes, the smallest and largest a reader may resize it to:
`size: { default: { w: 6, h: 3 }, min: { w: 4, h: 2 }, max: { w: 12, h: 6 } }`. The minimum
defaults to the default, and the maximum to the full width at the default's height. On the
dashboard, cards sit in one ordered list, filling rows left to right and wrapping, each spanning
its `w` columns and `h` rows, and a reader can change a card's width and height from its menu
within the widget's bounds. Columns follow the dashboard's own width rather than the window's:
from 640 to 1,023 pixels a card of 6 columns or fewer is drawn at 6 and a wider one at 12, and
below 640 pixels every card is drawn at the full width. A card keeps its height at every width. A reader can arrange the dashboard at every width.
Where it shows more than one column, a card is dragged by its handle, with the pointer or the
keyboard, and a line shows where it will land; below 640 pixels, where every card is full width,
cards are moved, resized and removed from their menu instead. The arrangement applies at every
width.

## Loaded as the viewer

A widget does not reach the database itself. Its `load` runs on the server for each card, and
reads through the `services` it is handed, already bound to the person viewing the card: they
take no user and no option to read past access, so a card only ever counts and lists what that
person could have read directly. That is what makes permission scoping reliable rather than
something each widget author has to remember.

Core's Count, Breakdown, Over time and Recent entries are declared this way too, each with a
Collection setting: the add panel offers each once per collection the reader may read, set to
that collection. Offered, never placed — nobody's dashboard gains a card because a collection
was created — and a new collection needs no new widget.

> [!WARNING]
> Contributing a widget from a plugin works today, but `defineWidget` is marked
> `@experimental` and its shape may change before it settles. Building on it is
> reasonable; depending on it in something you cannot easily update is not.

## A site's own widgets

A site declares widgets of its own in its config, with `defineWidget` as a plugin does. They are
checked, registered and offered in the add panel like a plugin's, and `defaultLayout` may place
them. A widget drawn by its own component names it relative to the config file, and says when
its data is empty, since core cannot tell that for a component it does not draw:

```ts
import { defineWidget } from "nextly";
import { defineConfig } from "nextly/config";

const notes = defineWidget({
  id: "site/notes",
  title: "Notes",
  description: "The team's notes for this week.",
  size: { default: { w: 6, h: 3 } },
  load: async () => ({ notes: ["Ship the release notes"] }),
  view: { component: "./dashboard/notes#NotesCard" },
  isEmpty: data => data.notes.length === 0,
});

export default defineConfig({ admin: { dashboard: { widgets: [notes] } } });
```

The generated component map imports `./dashboard/notes` from beside the config file, so the same
spelling works in `next dev`, in `nextly generate:types` and in its `--check` in CI, whatever path
aliases the app defines. A package name works as it does for a plugin. A path alias such as
`@/dashboard/notes` is refused at startup, with the relative spelling to write instead, because
nothing that writes or checks the map resolves it.

## Size-aware loads

A widget declared with `defineWidget` can compute its own data in a `load` function. `load`
runs on the server for each card, as the person viewing it. It is handed the card's `size`: its
`w` and `h` in grid units, kept within the widget's size bounds, and its `tier`, which is
`"small"`, `"medium"` or `"large"`. The tier depends on how wide the card is drawn on that
reader's screen. Use the size to read only what the card can show:

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

export const recentOrders = defineWidget({
  id: "acme/recent-orders",
  title: "Recent orders",
  description: "The newest orders, and how many there are on a large card.",
  size: { default: { w: 6, h: 4 }, max: { w: 12, h: 8 } },
  view: "list",
  load: async ({ size, services }) => {
    // As many rows as this card's body draws: never more than ten.
    const limit = rowsThatFit(size, { density: "default" });
    const { items } = await services.find("orders", {
      sort: "-createdAt",
      limit,
    });
    if (size.tier !== "large") return { items };
    // Only a large card shows the total, so only a large card counts the orders.
    return { items, total: await services.count("orders") };
  },
});
```

`rowsThatFit(size, { density })` counts the list rows that fit in a card of that height. It
uses the same formula as core's own list cards, so a load reads exactly the rows the card
draws. `density` is `"default"` or `"compact"`, the values a list card's Density setting takes.
Compact rows are shorter, so the same card holds more of them.

The size is part of the question a load answers. When a reader resizes a card, or a card
crosses into another tier, that card's `load` runs again on its own. The other cards keep their
answers. A widget's `shows` function gets the same `size`.

> [!NOTE]
> A card is not always asked with a tier. For example, when the server decides
> which cards of a default dashboard a reader sees, no screen is involved. Then
> `load` and `shows` are handed the card's stored size, or the widget's default
> size for a card not yet saved, with the tier `"medium"`.

### What a load can read

The `services` a `load` is handed read as the person viewing the card, with the same access
checks as every other read of their content. Beside `count`, `find`, `groupBy` and `timeseries`, they answer:

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

export const ordersThisMonth = defineWidget({
  id: "acme/orders-this-month",
  title: "Orders this month",
  description: "How many orders came in over the last 30 days.",
  size: { default: { w: 3, h: 2 } },
  view: "figure",
  // Drawn as a number while it loads, and in the add panel.
  skeleton: "figure",
  load: async ({ services }) => ({
    total: await services.count("orders", { window: { range: "30d" } }),
  }),
});
```

* **`count(collection, { window })`** counts the entries whose `dateField` (their `createdAt`
  unless you name another) falls in a range's window: `{ range: "30d" }` is the same window a
  series over `"30d"` is drawn across. Add `previous: true` for the window just as long that
  ends where that one starts, so the last 30 days and the 30 before them never share an entry.
* **`find(collection, { total: true })`** also answers `total`, how many entries the same read
  matched in all, for a "View all (N)" link; `atLeast: true` beside it means the number is a
  floor. A `limit` of `0` answers no rows, which is what `rowsThatFit` gives for a card too
  short to hold one.
* **`groupBy`** answers `truncated: true` when it left groups out, and `atLeast: true` when its
  counts are floors.
* **`describe(collection)`** answers the collection as your reads may use it: its `title` field,
  whether it has a draft and published `status` (as `defineCollection({ status: true })` gives
  it), and its `fields`, each with its `name`, its `label`, `type`, and `choices` for a field of
  choices. A field the collection gives no label of its own is labelled from its name, as the
  admin names it: `createdAt` is "Created At". Only fields the viewer may read are listed. Use
  it to name a grouping's values or to choose a list's columns.

A `dateField`, for `count`'s window or for `timeseries`, must be a date field of the collection
that everyone who can read the collection can read. Any other field is refused, whoever asks.

`skeleton` says what a card looks like while its data is on the way, and how its row is
sketched in the add panel: `"figure"`, `"list"`, `"bars"`, `"series"` or `"table"`. Without it,
the card loads in the frame's generic shape.

All of these are experimental.

## A setting's own editor

A setting is drawn in the card's settings panel by the field its builder names: a number input
for `setting.number`, a picker for `setting.collection`. Where none of those fits, a setting can
name a component of your own with `editor` (**experimental**), drawn in the sheet in its place.
The component is handed `SettingEditorProps` of the setting's value: the value, an `onChange`, the
card's other settings as the sheet holds them now, and whether the sheet is saving. A setting with
no value is handed `undefined`, and an editor clears a setting by calling `onChange(undefined)`:
the setting is saved unset, so the card reads its default, or no value where it has none. A change
is held to the setting's own rules (its type, `min` and `max`, its options, and for a Field
setting the fields its collection offers the reader) and saved with the rest of the settings when
the reader saves; a value that breaks them is named under the editor, and the server refuses it
too.

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

export const salesGoal = defineWidget({
  id: "acme/sales-goal",
  title: "Sales goal",
  description:
    "Orders over the last 30 days, against the goal the reader sets.",
  size: { default: { w: 3, h: 2 } },
  view: "figure",
  settings: {
    goal: setting.number({
      label: "Goal",
      defaultValue: 1000,
      editor: { component: "@acme/nextly-plugin-shop/admin#GoalEditor" },
    }),
  },
  load: async ({ services }) => ({
    total: await services.count("orders", { window: { range: "30d" } }),
  }),
});
```

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

export function GoalEditor({
  label,
  value,
  onChange,
  disabled,
}: SettingEditorProps<number>) {
  // ...draw the value, and call onChange with a number, or with undefined to clear it
}
```

The editor is registered like the widget's own component, from your admin entry, and the
component map holds it to the setting's value: an editor written for another setting's value
fails to compile. Startup refuses an `editor` that names no component, and one component used both
as a widget's view and as a setting's editor.

## Testing a widget

`@nextlyhq/plugin-sdk/testing` runs a widget's `load` for a given person against a test instance,
through the dashboard's own route, so that person's access applies exactly as it does on the
dashboard:

```ts
import { createTestNextly, runWidgetLoad } from "@nextlyhq/plugin-sdk/testing";
import { expect, it } from "vitest";

import { openOrders, shop } from "./shop";

it("counts the open orders for the instance's administrator", async () => {
  const t = await createTestNextly({ plugins: [shop] });
  // The first user an instance stores is its super administrator.
  const admin = await t.nextly.users.create({
    email: "admin@example.com",
    password: "Password123!",
    data: { name: "Admin", isActive: true },
  });
  await t.nextly.create({ collection: "orders", data: { state: "open" } });
  const answer = await runWidgetLoad(t, openOrders, {
    as: { id: admin.item.id },
  });
  expect(answer).toEqual({ state: "ready", data: { total: 1 } });
  await t.destroy();
});
```

It answers in the card's own states: `ready` and `empty` with the data, `needs-setting`,
`unavailable`, `not-shown`, or `error`. `as: null` answers as the dashboard answers nobody signed
in.

`@nextlyhq/plugin-sdk/testing/admin` draws the card in the admin's own frame, for a state you name
or for what a load answered:

```tsx
import { renderWidgetCard } from "@nextlyhq/plugin-sdk/testing/admin";
import { render, screen } from "@testing-library/react";
import { expect, it } from "vitest";

import { openOrders } from "./shop";

it("draws the count in the dark scheme", () => {
  render(
    renderWidgetCard(openOrders, {
      state: "ready",
      data: { total: 3 },
      theme: "dark",
    })
  );
  const card = screen.getByRole("region", { name: "Open orders" });
  expect(card.textContent).toContain("3");
});
```

Both helpers are for tests and stay out of a production build. They are experimental, and their
shape may change.

## Where a setting is drawn

A card's More settings panel draws its settings in three sections: **Data**, what the card reads;
**Display**, how it shows it (every card's title is there too); and **Advanced**, folded until a
reader opens it. Name a setting's section with `section`:

```ts
density: setting.select({
  label: "Density",
  options: [
    { label: "Default", value: "default" },
    { label: "Compact", value: "compact" },
  ],
  defaultValue: "default",
  section: "advanced",
}),
```

Without one, a Collection, Filter, Sort, Group by or Field setting and a `setting.dateRange` are
drawn under Data, and every other setting under Display. A setting is folded under Advanced only
when it says so. Startup refuses a `section` other than `"data"`, `"display"` or `"advanced"`.

## Related

* [Plugin admin UI](https://nextlyhq.com/docs/plugins/admin-ui.md) — contributing admin surfaces, and drawing a widget with your own component
* [Plugin stability](https://nextlyhq.com/docs/plugins/stability.md) — what is settled and what is not
