You're reading docs for Nextly Alpha. APIs may change between releases.

Dashboard Widgets

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:

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.

Its test draws the card from its preview case, so you see it before it has data. Run the test with npx vitest run.

Availability

Built inThe widget system, core's widgets and admin rendering all ship
Plugin-contributed widgetsExperimental. They render, but defineWidget and its shape are still settling — see the stability ladder
PermissionA 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.

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.

viewDrawsload 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 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: w is from 1 to 12 columns and h from 2 to 12. 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 h. On the dashboard, cards sit in one ordered list, filling rows left to right and wrapping, each spanning its w columns, and a reader can change a card's width from its menu within the widget's bounds. A card is as tall as its content, and the cards that share a row are drawn as tall as the tallest of them; nothing inside a card is cut off or scrolls. h no longer sets a card's height: it is kept in the declaration and in saved layouts. A list's length is its reader's "Number of entries" setting rather than its size (below). 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 a card of 3 columns (25%) or fewer is drawn at half the width, so two share a row, and every other card at the full 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: a dashed outline the size of the card shows where it will land, and the other cards move aside. From the keyboard, a card's ⋯ menu moves it with Move earlier and Move later. 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 lists each once, and a card added starts on the first collection the reader may read that no card of that widget uses yet. Offered, never placed — nobody's dashboard gains a card because a collection was created — and a new collection needs no new widget.

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:

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. A card is as tall as its content, so how many rows a list reads is not a question of its size: it is the reader's "Number of entries", a setting the widget declares.

import {
  defineWidget,
  listEntries,
  MAX_WIDGET_ROWS,
  setting,
} from "@nextlyhq/plugin-sdk";

export const recentOrders = defineWidget({
  id: "acme/recent-orders",
  title: "Recent orders",
  description: "The newest orders, and how many there are in all.",
  size: { default: { w: 6, h: 4 }, max: { w: 12, h: 8 } },
  view: "list",
  settings: {
    limit: setting.number({
      label: "Number of entries",
      defaultValue: 5,
      min: 1,
      max: MAX_WIDGET_ROWS,
    }),
  },
  load: async ({ settings, services }) => {
    // The reader's "Number of entries": five unless chosen, never more than twenty.
    const { items, total } = await services.find("orders", {
      sort: "-createdAt",
      limit: listEntries(settings.limit),
      total: true,
    });
    return total === undefined ? { items } : { items, total };
  },
});

listEntries(limit) is the rule core's own list cards read their "Number of entries" by: five where the setting is missing, at most MAX_WIDGET_ROWS (twenty). With total, the card's footer reads "View all (N)" when there are more than it shows.

rowsThatFit(size, { density }) still answers the list rows a card of that h held when cards were drawn at fixed heights, at most ten, for the loads that call it.

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.

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:

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.
  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: "figure", "list", "bars", "series" or "table". Without it, the card loads in the frame's generic shape. The add panel lists a widget by its icon (a Lucide icon's name), its title and its description, which reads best as one line.

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.

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" } }),
  }),
});
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.

Statuses in your own component

Core's cards draw every status the same way, in light and dark, and a widget drawn by its own component reads best beside them when it does too. The admin has four statuses, success, warning, danger and info, each with four tokens: --nx-<status>-surface, -border, -text and -solid.

  • A status label (Published, Draft, Failed) is a quiet chip: the card's surface, ordinary text, and a small dot in the status's colour before the word. Draw it with the kit's status chip, Badge from @nextlyhq/ui, with variant="success", "warning", "destructive" or "info"; a status that marks nothing to act on, such as a draft, takes the plain variant="outline". The word carries the status, so colour is never the only signal.
  • A dot, an icon, a progress bar or a chart mark is drawn in the status's -solid colour, which keeps 3:1 against the page in both themes. The kit's Widget.BarChart already draws a chart of statuses this way.
  • A warning or a failure that needs reading sits on the status's -surface with its -border, and its icon in -text.
import { Badge } from "@nextlyhq/ui";

export function ReportStatus({ failed }: { failed: boolean }) {
  return failed ? (
    <Badge variant="destructive">Failed</Badge>
  ) : (
    <Badge variant="success">Sent</Badge>
  );
}

Use the tokens through var() or the token utilities in your plugin's own stylesheet (see Styling your admin UI). Avoid the numbered status shades (bg-success-100, text-warning-700) and opacity mixes (bg-destructive/10): they are pale tints that read differently in each theme, and they are deprecated. Core leaves a widget's own markup as it is, so this is a recommendation, not a check.

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:

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:

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 settings drawer, opened from Settings… in its menu, shows a preview of the card, then its settings in sections, none folded: Content, what the card reads; Display, how it shows it (every card's title is there too); and Size, the card's width. Name a setting's section with section, "data" for Content or "display":

density: setting.select({
  label: "Row spacing",
  options: [
    { label: "Comfortable", value: "default" },
    { label: "Compact", value: "compact" },
  ],
  defaultValue: "default",
  section: "display",
}),

Without one, a Collection, Filter, Sort, Group by or Field setting and a setting.dateRange are drawn under Content, and every other setting under Display. "advanced" is still accepted, from when the drawer folded settings away, and is drawn under Display. Startup refuses a section other than "data", "display" or "advanced".

A list's "Number of entries", a number setting keyed limit, is drawn as a choice of 5, 10 or 20 within its bounds; a number stored before that is none of them is shown and kept until the reader picks another.