@dashspec/renderer 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,606 @@
1
+ # Widgets
2
+
3
+ Every box on a dashboard is a **node** in `spec.panels`: a `kind` (which widget) and a
4
+ `spec` (that widget's props). The renderer ships 30 built-in widgets, and you can add
5
+ your own.
6
+
7
+ ```json
8
+ "ordersKpi": {
9
+ "kind": "Kpi",
10
+ "spec": { "title": "Orders", "data": { "source": "summary", "path": "orders" }, "target": 300 }
11
+ }
12
+ ```
13
+
14
+ - [Props every widget shares](#props-every-widget-shares)
15
+ - [Built-in widgets](#built-in-widgets)
16
+ - [Nesting widgets with slots](#nesting-widgets-with-slots)
17
+ - [Write your own widget](#write-your-own-widget)
18
+
19
+ ## Props every widget shares
20
+
21
+ Besides its own props, every built-in widget except the atoms (Text, Value, Progress,
22
+ Icon, Divider) accepts these in `spec`:
23
+
24
+ | Prop | Type | What it does |
25
+ |---|---|---|
26
+ | `title` | string | Card title (templates allowed: `"Orders in ${filters.region}"`) |
27
+ | `subtitle` | string | Smaller text under the title |
28
+ | `info` | string | Help text behind an ⓘ next to the title |
29
+ | `meta` | string | Short text on the right of the header, e.g. `"Total: ${datasources.summary.data.total}"` |
30
+ | `live` | boolean | Shows "● Live, updated just now" from the datasource's last update |
31
+ | `data` | binding | Where the data comes from (below) |
32
+ | `options` | object | Passed to the underlying library (charts: ECharts options), merged last |
33
+ | `highlight` | string | Hover group: widgets with the same group highlight together |
34
+
35
+ The atoms accept only `data` and `options` besides their own props.
36
+
37
+ **Data bindings.** `spec.data` is one of:
38
+
39
+ | Binding | Data the widget gets |
40
+ |---|---|
41
+ | `{ "source": "sales", "path": "rows" }` | Datasource `sales`, then `path` inside it (optional) |
42
+ | `{ "panel": "salesTable", "path": "selection" }` | Another panel's state (default path `selection`) |
43
+ | `{ "state": "selectedOrder" }` | A value in the [state tree](state-and-events.md#the-state-tree) |
44
+ | `{ "value": 42 }` | A fixed value |
45
+
46
+ A node without `data` inside another node uses its parent's data. While a datasource
47
+ loads the panel shows a skeleton, and with no rows it shows "No data" (change the text
48
+ with the node's `messages: { "empty": "…", "error": "…" }`).
49
+
50
+ Props can use `${…}` templates anywhere (see [Data](data.md#templates)). A prop that
51
+ fails the widget's schema is dropped and reported by validation; the widget keeps its
52
+ other props.
53
+
54
+ ## Built-in widgets
55
+
56
+ Each widget lists the events it emits. Wire them in the node's `on` map; see
57
+ [State and events](state-and-events.md#events).
58
+
59
+ Field props such as `x`, `label` or `value` name a field of each data row; dot paths
60
+ (`"totals.orders"`) work.
61
+
62
+ `format` takes `number`, `compact`, `percent`, `duration` (seconds), `date`, `datetime`,
63
+ `time` or `text`. Tones are `good`, `warn`, `bad`, `neutral`, `info`.
64
+
65
+ ### Numbers
66
+
67
+ | Kind | What it shows | Main props | Events |
68
+ |---|---|---|---|
69
+ | `Kpi` | A metric card: label, big value, target and an "On track / Action needed" chip | `unit`, `format`, `decimals`, `target`, `targetLabel`, `goodWhen` (`up` / `down` / `none`), `badge`, `statusLabels`, `compare`, `band`, `progress`, `note`, `emptyText`, `sublabel`, `size` (`normal` / `hero`), `tone` | `click`, `hover` (part `value`) |
70
+ | `Tiles` | One tile per row: label, big number, caption | `label`, `value` (required), `caption`, `status`, `statusMap`, `valueTone`, `count`, `format`, `unit`, `columns`, `minTileWidth`, `wrap`, `selectable`, `selected` | `click`, `hover`, `select` (part `tile`) |
71
+ | `Gauge` | A value on an arc or circle with coloured bands | `min` (0), `max` (100), `bands: [{ to, tone }]`, `shape` (`arc` / `circle`), `unit`, `format`, `decimals` | `click` |
72
+ | `Status` | A status badge from a state field, or fixed text | `state` (field, default `"state"`), `stateMap`, `labels`, `label`, `text`, `tone` | `click` |
73
+
74
+ ```json
75
+ "panels": {
76
+ "orders": {
77
+ "kind": "Kpi",
78
+ "spec": {
79
+ "title": "Orders today",
80
+ "data": { "source": "summary", "path": "orders" },
81
+ "target": 300,
82
+ "goodWhen": "up",
83
+ "compare": { "path": "ordersYesterday", "label": "vs yesterday" }
84
+ }
85
+ },
86
+ "byStore": {
87
+ "kind": "Tiles",
88
+ "spec": { "title": "Orders by store", "data": { "source": "stores" }, "label": "store", "value": "orders", "caption": "orders" }
89
+ },
90
+ "uptime": {
91
+ "kind": "Gauge",
92
+ "spec": {
93
+ "title": "Uptime",
94
+ "data": { "source": "summary", "path": "uptime" },
95
+ "unit": "%",
96
+ "bands": [{ "to": 90, "tone": "bad" }, { "to": 97, "tone": "warn" }, { "to": 100, "tone": "good" }]
97
+ }
98
+ },
99
+ "apiStatus": {
100
+ "kind": "Status",
101
+ "spec": { "data": { "source": "summary" }, "state": "apiState", "stateMap": { "up": "good", "down": "bad" } }
102
+ }
103
+ }
104
+ ```
105
+
106
+ ### Charts
107
+
108
+ | Kind | What it shows | Main props | Events |
109
+ |---|---|---|---|
110
+ | `BarChart` | Bars, grouped, stacked or horizontal | `x` (required), `y` (field or list), `seriesBy`, `labels`, `stacked`, `normalized`, `horizontal`, `range: { low, high }`, `pageSize`, `colorBy` (`average` / `none`), `partial`, `valueLabels`, `averageLine`, `legendLabels`, `target`, `targetLabel`, `unit`, `format` | `click`, `doubleClick`, `hover`, `hoverEnd`, `legendClick`, `brush`, `datazoom` (parts `bar`, `legend`, `axis`) |
111
+ | `LineChart` | Lines or areas over `x` | `x` (required), `y`, `seriesBy`, `area`, `gradient`, `smooth`, plus the bar chart's `labels`, `target`, `unit`, `format` | same as BarChart (parts `point`, `legend`, `axis`) |
112
+ | `PieChart` | A pie or donut | `label`, `value` (required), `donut`, `unit`, `format`, `decimals` | `click`, `hover`, `hoverEnd`, `legendClick` (parts `slice`, `legend`) |
113
+ | `Scatter` | Points by two numbers | `x`, `y` (required), `size`, `series`, `xLabel`, `yLabel` | `click`, `hover`, `hoverEnd`, `brush`, `legendClick` |
114
+ | `MatrixChart` | A heatmap of rows × columns | `rows`, `cols`, `value` (required), `unit`, `format` | `click`, `cellClick`, `hover` (part `cell`) |
115
+ | `Breakdown` | Parts of a whole as meters, a segmented bar or a donut | `label`, `value` (required), `mode` (`meters` / `segmented` / `donut`), `remainder: { label, total }`, `showPercent`, `limit`, `unit`, `format` | `click`, `hover` (part `item`) |
116
+ | `Sparkline` | A tiny line, no axes | `y` (required), `x`, `area` (default `true`) | `hover` |
117
+
118
+ ```json
119
+ "panels": {
120
+ "trend": {
121
+ "kind": "LineChart",
122
+ "spec": { "title": "Orders per day", "data": { "source": "daily" }, "x": "date", "y": ["orders", "returns"], "area": true }
123
+ },
124
+ "byRegion": {
125
+ "kind": "BarChart",
126
+ "spec": {
127
+ "title": "Orders by region",
128
+ "data": { "source": "sales" },
129
+ "x": "region",
130
+ "y": "orders",
131
+ "seriesBy": "channel",
132
+ "stacked": true,
133
+ "options": { "legend": { "bottom": 0 } }
134
+ }
135
+ },
136
+ "mix": {
137
+ "kind": "Breakdown",
138
+ "spec": { "title": "Channel mix", "data": { "source": "channels" }, "label": "channel", "value": "orders", "mode": "segmented" }
139
+ }
140
+ }
141
+ ```
142
+
143
+ Charts take their colours from the theme's `chart.series` tokens (see
144
+ [Theming](theming.md#charts)).
145
+
146
+ ### Lists
147
+
148
+ | Kind | What it shows | Main props | Events |
149
+ |---|---|---|---|
150
+ | `Table` | Rows and columns with sorting, search, filters, paging, totals and pivots | `columns` (below), `columnsFrom`, `totals`, `pivot`, `pagination`, `search`, `sorting`, `filtering`, `sticky`, `rowKey`, `rowMutedWhen`, `virtual`, `density` | `rowClick`, `cellClick`, `hover` (parts `row`, `cell`) |
151
+ | `CardGrid` | One card per row with fields, a status and a progress bar | `cardTitle` (required), `fields: [{ key, label, format, unit }]`, `status`, `statusMap`, `progress: { value, max, label }`, `badge`, `minCardWidth`, `selectable`, `selected`, `rowKey` | `click`, `select` (part `card`) |
152
+
153
+ A table column is `{ key, label?, type?, … }`. `type` is `text`, `number`, `badge`,
154
+ `link`, `image`, `progress`, `sparkline`, `list` or `template`; other column fields are
155
+ `format`, `decimals`, `prefix`, `suffix`, `align`, `empty`, `template`
156
+ (`"${row.first} ${row.last}"`), `list`, `map` (badge value → tone), `tone` (an
157
+ expression over `row`), `href` (link template), `max` (progress), `width`, `sortable`,
158
+ `filter` (`text` / `select` / `min`) and `filterOptions`.
159
+
160
+ ```json
161
+ "orders": {
162
+ "kind": "Table",
163
+ "spec": {
164
+ "title": "Latest orders",
165
+ "data": { "source": "orders", "path": "results" },
166
+ "columns": [
167
+ { "key": "id", "label": "Order", "type": "link", "href": "/orders/${row.id}" },
168
+ { "key": "customer", "label": "Customer", "filter": "text" },
169
+ { "key": "status", "label": "Status", "type": "badge", "map": { "paid": "good", "late": "bad" } },
170
+ { "key": "total", "label": "Total", "type": "number", "format": "number", "decimals": 2, "align": "right" }
171
+ ],
172
+ "search": true,
173
+ "pagination": { "pageSize": 20 },
174
+ "sorting": { "default": { "key": "total", "order": "desc" } },
175
+ "totals": { "columns": { "total": "sum" } }
176
+ },
177
+ "on": { "rowClick": [{ "do": "setSelection" }] }
178
+ }
179
+ ```
180
+
181
+ `pagination`, `search`, `sorting` and `filtering` each take `mode: "client"` (the table
182
+ works on the rows it has) or `"server"` (the table writes `page`, `pageSize`, `search`,
183
+ `sortKey`, `sortOrder`, `ordering` or `filters` to `panels.<id>.ui`, and your datasource
184
+ sends them; see [Data](data.md#server-side-paging)).
185
+
186
+ ### Status and timelines
187
+
188
+ | Kind | What it shows | Main props | Events |
189
+ |---|---|---|---|
190
+ | `StageTracker` | Steps of a process with the current one marked | `stages` (required list of names), `current` (field, default `"stage"`) | `click` (part `stage`) |
191
+ | `StateTimeline` | Coloured segments of states over time, one lane per item | `time` (default `"ts"`), `value` (default `"value"`), `stateMap`, `tones`, `window` (e.g. `"8h"`), `rows`, `endLabel` | `click`, `hover` (part `segment`) |
192
+
193
+ ```json
194
+ "shipment": {
195
+ "kind": "StageTracker",
196
+ "spec": { "data": { "source": "shipment" }, "stages": ["Ordered", "Packed", "Shipped", "Delivered"], "current": "stage" }
197
+ },
198
+ "machines": {
199
+ "kind": "StateTimeline",
200
+ "spec": {
201
+ "title": "Machine states, last 8 hours",
202
+ "data": { "source": "machineEvents" },
203
+ "time": "at",
204
+ "value": "state",
205
+ "rows": "machine",
206
+ "window": "8h",
207
+ "tones": { "running": "good", "idle": "warn", "down": "bad" }
208
+ }
209
+ }
210
+ ```
211
+
212
+ ### Content
213
+
214
+ | Kind | What it shows | Main props | Events |
215
+ |---|---|---|---|
216
+ | `Content` | Markdown text: paragraphs, headings, lists, **bold**, *italic*, `code`, links, and `action:<name>` links that run a named action | `markdown`, `align` | `click` |
217
+ | `Image` | An image from a URL or a data field | `src`, `srcField`, `alt`, `fit` (`contain` / `cover` / `fill`) | `click` |
218
+ | `ImageMap` | An image with markers at x/y percentages | `src` (required), `alt`, `markers` (a list of `{ x, y, label, value, status }`, or field names to read them from data rows), `statusMap`, `format`, `unit` | `click`, `hover` (part `marker`) |
219
+
220
+ ```json
221
+ "intro": {
222
+ "kind": "Content",
223
+ "spec": { "markdown": "## Week ${filters.week}\n\nNumbers update every minute. [Export orders](action:exportOrders)" }
224
+ },
225
+ "floor": {
226
+ "kind": "ImageMap",
227
+ "spec": {
228
+ "src": "https://cdn.example.com/floor-plan.png",
229
+ "alt": "Warehouse floor",
230
+ "data": { "source": "zones" },
231
+ "markers": { "x": "posX", "y": "posY", "label": "name", "status": "state" },
232
+ "statusMap": { "ok": "good", "full": "bad" }
233
+ }
234
+ }
235
+ ```
236
+
237
+ Values filled into `markdown` by `${…}` are escaped: data can't add links or headings.
238
+ Links and image sources are checked (see [Security](security.md)).
239
+
240
+ ### Layout
241
+
242
+ These hold other nodes in [slots](#nesting-widgets-with-slots).
243
+
244
+ | Kind | What it does | Slot | Main props | Events |
245
+ |---|---|---|---|---|
246
+ | `Container` | Flex box for its children | `items` | `direction` (`row` / `column`), `wrap`, `gap`, `justify`, `align`, `equal`, `childMinWidth`, `scroll` | none |
247
+ | `Row` | A Container that lays items side by side | `items` | same as Container | none |
248
+ | `Column` | A Container that stacks items | `items` | same as Container | none |
249
+ | `Card` | A card with a title and a body you compose | `body` | `direction`, `gap`, `align` | `click` |
250
+ | `Tabs` | Tabs, one slot per tab key | one per tab `key` | `tabs: [{ key, label }]`, `initial` | `change` (part `tab`, `value` = tab key) |
251
+ | `Repeater` | Draws its `item` slot once per data row | `item` | `layout` (`grid` / `list`), `minItemWidth`, `gap`, `limit`, `emptyText` | none |
252
+
253
+ ### Filters
254
+
255
+ | Kind | What it does | Main props |
256
+ |---|---|---|
257
+ | `Filter` | Places one of the dashboard's filters (`spec.variables`) on the canvas instead of the filter bar | `variable` (the filter's `name`), `fill` |
258
+
259
+ ```json
260
+ "regionPicker": { "kind": "Filter", "spec": { "variable": "region" } }
261
+ ```
262
+
263
+ ### Atoms
264
+
265
+ Small pieces for building your own cards inside `Card`, `Row` or a header slot.
266
+
267
+ | Kind | What it shows | Main props | Events |
268
+ |---|---|---|---|
269
+ | `Text` | A line of text; `{value}` is replaced by the bound value | `text`, `field`, `size` (`xs`…`xl`), `weight`, `color`, `align`, `emptyText` | `click` |
270
+ | `Value` | A formatted number | `field`, `format`, `decimals`, `unit`, `prefix`, `size`, `color` (`default` / `primary` / `byTarget` / `good` / `warn` / `bad`), `target`, `goodWhen`, `countUp` | `click` |
271
+ | `Progress` | A progress bar | `field`, `max`, `color`, `goodFrom`, `showPercent`, `thickness` | none |
272
+ | `Icon` | An icon: `bolt`, `fire`, `factory`, `clock`, `check`, `alert`, `up`, `down`, `gauge`, `box`, `user`, `money` | `icon`, `size`, `color`, `background` | `click` |
273
+ | `Divider` | A line | `direction`, `dashed` | none |
274
+
275
+ ```json
276
+ "revenueCard": {
277
+ "kind": "Card",
278
+ "spec": { "title": "Revenue", "data": { "source": "summary" } },
279
+ "slots": { "body": ["revenueValue", "revenueBar", "revenueNote"] }
280
+ },
281
+ "revenueValue": { "kind": "Value", "spec": { "field": "revenue", "format": "compact", "prefix": "$", "target": 50000, "color": "byTarget" } },
282
+ "revenueBar": { "kind": "Progress", "spec": { "field": "revenue", "max": 50000, "showPercent": true } },
283
+ "revenueNote": { "kind": "Text", "spec": { "text": "Goal: $50k", "size": "xs" } }
284
+ ```
285
+
286
+ ## Nesting widgets with slots
287
+
288
+ A node holds other nodes in **slots**: named lists of node ids in `slots`. Only
289
+ top-level nodes go in `layouts`; nested ones live only in their parent's slot.
290
+
291
+ ```json
292
+ "panels": {
293
+ "summaryRow": {
294
+ "kind": "Row",
295
+ "spec": { "gap": 12 },
296
+ "slots": { "items": ["ordersKpi", "revenueKpi"] }
297
+ },
298
+ "ordersKpi": { "kind": "Kpi", "spec": { "title": "Orders", "data": { "source": "summary", "path": "orders" } } },
299
+ "revenueKpi": {
300
+ "kind": "Kpi",
301
+ "spec": { "title": "Revenue", "data": { "source": "summary", "path": "revenue" } },
302
+ "style": { "flex": "2 1 0" },
303
+ "slots": { "header": ["revenueLive"] }
304
+ },
305
+ "revenueLive": { "kind": "Status", "spec": { "text": "Live", "tone": "info" } }
306
+ },
307
+ "layouts": [{ "items": [{ "panel": "summaryRow", "x": 0, "y": 0, "w": 12, "h": 5 }] }]
308
+ ```
309
+
310
+ The rules:
311
+
312
+ - **Every node** has a `header` slot (next to the title) and a `footer` slot (under the
313
+ body). The header takes only small widgets: atoms, `Status`, `Content`, `Filter`.
314
+ - Layout widgets add their own: `items` (Container, Row, Column), `body` (Card), one
315
+ slot per tab `key` (Tabs), `item` (Repeater).
316
+ - A node sits in **one place**: on the grid or in one slot.
317
+ - As a child of a container, a node's `style` may set `flex`, `minWidth`, `maxWidth`
318
+ and `align`.
319
+ - A child without its own `data` uses its parent's and can also read the parent's data
320
+ as `${parent.*}`.
321
+
322
+ **Tabs** get one slot per tab key:
323
+
324
+ ```json
325
+ "views": {
326
+ "kind": "Tabs",
327
+ "spec": { "tabs": [{ "key": "trend", "label": "Trend" }, { "key": "table", "label": "Table" }] },
328
+ "slots": { "trend": ["trend"], "table": ["orders"] }
329
+ }
330
+ ```
331
+
332
+ **Repeater** draws its `item` slot once per row. Children read the row as `${item.*}`
333
+ and its position as `${index}`, and get the row as their data:
334
+
335
+ ```json
336
+ "storeCards": {
337
+ "kind": "Repeater",
338
+ "spec": { "data": { "source": "stores" }, "minItemWidth": 240 },
339
+ "slots": { "item": ["storeCard"] }
340
+ },
341
+ "storeCard": {
342
+ "kind": "Card",
343
+ "spec": { "title": "${item.name}" },
344
+ "slots": { "body": ["storeOrders"] }
345
+ },
346
+ "storeOrders": { "kind": "Value", "spec": { "field": "orders", "unit": "orders" } }
347
+ ```
348
+
349
+ ## Write your own widget
350
+
351
+ Your widgets use the same contract as the built-ins. Their kind must be namespaced
352
+ (`acme.Gauge`, `mui.DataGrid`) so it can never clash with a built-in. Register them with
353
+ the `widgets` prop, a [design system](design-systems.md), or a `DashSpecProvider`:
354
+
355
+ ```tsx
356
+ <DashSpecProvider widgets={[AcmeTable, AcmeMap]}>
357
+ <App />
358
+ </DashSpecProvider>
359
+ ```
360
+
361
+ The JSON then uses them by kind:
362
+
363
+ ```json
364
+ "orders": { "kind": "acme.Table", "spec": { "title": "Orders", "data": { "source": "orders" } } }
365
+ ```
366
+
367
+ There are two ways to write one: wrap an existing component, or write a widget component.
368
+
369
+ ### `wrapComponent`: wrap an existing component
370
+
371
+ `wrapComponent` turns any React component (from MUI, Ant, Chakra, your own library)
372
+ into a widget without writing a new component. You describe how JSON props, events,
373
+ state and slots map to the component's props.
374
+
375
+ ```tsx
376
+ import { z } from "zod";
377
+ import { wrapComponent } from "@dashspec/renderer";
378
+ import { DataGrid } from "@acme/ui";
379
+
380
+ export const AcmeTable = wrapComponent(DataGrid, {
381
+ kind: "acme.Table",
382
+ meta: { label: "Acme table", category: "Acme" },
383
+ // The JSON props. Include `title` if the panel should show one.
384
+ schema: z.object({
385
+ title: z.string().optional(),
386
+ columns: z.array(z.object({ key: z.string(), label: z.string() })),
387
+ dense: z.boolean().default(false),
388
+ }),
389
+ defaults: { columns: [] },
390
+ implements: "table",
391
+ // JSON + data → the component's props. Default: the spec's props plus `data`.
392
+ mapProps: ({ spec, data }) => ({
393
+ columns: spec.columns,
394
+ rows: Array.isArray(data) ? data : [],
395
+ size: spec.dense ? "small" : "medium",
396
+ }),
397
+ // Component callback → DashSpec event. The first argument becomes `event.value`.
398
+ events: { onRowClick: "rowClick" },
399
+ // Component callback → your own state path (read as ${state.selectedOrderIds}).
400
+ writes: { onSelectionChange: "selectedOrderIds" },
401
+ // Component props that take React elements → slots the JSON can fill.
402
+ slots: { toolbar: "toolbar" },
403
+ });
404
+ ```
405
+
406
+ ```json
407
+ "orders": {
408
+ "kind": "acme.Table",
409
+ "spec": {
410
+ "title": "Orders",
411
+ "data": { "source": "orders" },
412
+ "columns": [{ "key": "id", "label": "Order" }, { "key": "total", "label": "Total" }]
413
+ },
414
+ "slots": { "toolbar": ["exportButton"] },
415
+ "on": { "rowClick": [{ "do": "openModal", "modal": "order", "args": { "id": "${event.value.id}" } }] }
416
+ }
417
+ ```
418
+
419
+ `WrapOptions`:
420
+
421
+ | Option | What it does |
422
+ |---|---|
423
+ | `kind` | Namespaced kind (required) |
424
+ | `meta` | `{ label, icon?, category?, description?, preview?, size? }` for palettes (required) |
425
+ | `schema` | zod schema of the JSON props. Default: any object |
426
+ | `defaults` | Starting props when an editor adds the widget |
427
+ | `version` | Props version, default `1` (see [versions](#versions-and-migrations)) |
428
+ | `mapProps(props)` | Builds the component's props from [`WidgetProps`](#widgetprops) |
429
+ | `events` | `{ componentCallback: "eventName" }`; the event carries `value` (first argument) and `args` (all arguments) |
430
+ | `writes` | `{ componentCallback: "state.path" }`; writes the first argument to your own state. Runtime-owned roots (`filters`, `panels`, `view`, `modal`, `highlight`, `datasources`, `context`) are refused |
431
+ | `slots` | `{ componentProp: "slotName" }`; the prop receives the slot's rendered children |
432
+ | `implements`, `exposes` | Role and published state ([below](#roles-and-aliases)) |
433
+ | `frame` | `"card"` (default) or `"plain"` (no card around it) |
434
+ | `small` | `true` lets it sit in header slots |
435
+
436
+ ### `defineWidget`: write a widget component
437
+
438
+ For full control, write a component that receives `WidgetProps`:
439
+
440
+ ```tsx
441
+ import { z } from "zod";
442
+ import { defineWidget, type WidgetProps } from "@dashspec/renderer";
443
+
444
+ const schema = z.object({
445
+ title: z.string().optional(),
446
+ field: z.string().default("value"),
447
+ max: z.number().default(100),
448
+ });
449
+
450
+ function Battery({ spec, data, emit, helpers, status }: WidgetProps<z.output<typeof schema>>) {
451
+ const row = (Array.isArray(data) ? data[0] : data) as Record<string, unknown> | undefined;
452
+ const value = Number(row?.[spec.field] ?? 0);
453
+ const pct = Math.min(100, (value / spec.max) * 100);
454
+ return (
455
+ <button
456
+ type="button"
457
+ aria-busy={status === "loading"}
458
+ onClick={() => emit("click", "level", { value, datum: row })}
459
+ style={{ width: "100%", background: "var(--ds-color-surface-sunken)", border: 0, padding: 0 }}
460
+ >
461
+ <div style={{ width: `${pct}%`, height: 24, background: "var(--ds-good)" }} />
462
+ <span>{helpers.fmt.percent(pct)}</span>
463
+ </button>
464
+ );
465
+ }
466
+
467
+ export const BatteryWidget = defineWidget({
468
+ kind: "acme.Battery",
469
+ version: 1,
470
+ meta: { label: "Battery", icon: "gauge", category: "Acme", size: { w: 3, h: 3 } },
471
+ schema,
472
+ defaults: { field: "value", max: 100 },
473
+ events: ["click"],
474
+ parts: ["level"],
475
+ component: Battery,
476
+ });
477
+ ```
478
+
479
+ Style widgets with the `--ds-*` CSS variables so they follow the dashboard's theme and
480
+ dark mode (see [Theming](theming.md#css-variables)).
481
+
482
+ #### `WidgetProps`
483
+
484
+ | Prop | Type | What it is |
485
+ |---|---|---|
486
+ | `spec` | your schema's output | The node's props, parsed with your schema, `${…}` filled, `{ "fn": … }` props turned into functions |
487
+ | `data` | `unknown` | The bound data, after `data.path` |
488
+ | `source` | `unknown` | The whole datasource result, before `data.path` |
489
+ | `status` | `"idle" \| "loading" \| "success" \| "error"` | The datasource's status, to show a busy state while keeping rows |
490
+ | `emit(type, part?, detail?)` | `Emit` | Sends an event (`"click"`, `"rowClick"`…) that the node's `on` map handles. `detail` may carry `datum`, `value`, `series`, `index`, `x`, `y` and anything else |
491
+ | `run(action, detail?)` | function | Runs a named action or an action object as if from this panel |
492
+ | `store` | `WidgetStore` | The dashboard's state (below) |
493
+ | `state` | `PanelState` | This panel's runtime state: `selection`, `hover`, `drill`, `controls`, `hiddenSeries`, `ui` |
494
+ | `setUi(patch)` | function | Merges into `panels.<id>.ui`: widget-owned state (page, sort, open tab). Datasources can read it |
495
+ | `renderSlot(name, options?)` | function | Draws the children in one of the node's slots, anywhere in your markup |
496
+ | `helpers` | `Helpers` | Formatting and date helpers with the dashboard's locale and time zone (`helpers.fmt.number(…)`) |
497
+ | `highlight` | `unknown` | The hovered value of the panel's highlight group |
498
+ | `size` | `{ width, height }` | Pixel size of the panel body |
499
+ | `mode` | `"view" \| "preview" \| "tv" \| "edit"` | How the dashboard is shown |
500
+ | `panelId` | `string` | This node's id |
501
+
502
+ `WidgetStore` paths are dot paths into the [state tree](state-and-events.md#the-state-tree):
503
+
504
+ | Method | What it does |
505
+ |---|---|
506
+ | `get(path)` | The value now, e.g. `store.get("filters.region")` |
507
+ | `use(pathOrSelect)` | Hook: the value, re-rendering only when it changes. Call it at the top of your component |
508
+ | `set(path, value)` | Writes your own state. Throws for runtime-owned roots; use `setFilter`, `setUi` or actions for those |
509
+ | `setFilter(name, value)` | Sets a filter |
510
+ | `subscribe(path, fn)` | Calls `fn(value)` when the value changes; returns the unsubscribe function |
511
+
512
+ `renderSlot` options: `className`, `style`, `data` (what children see when they have no
513
+ data of their own), `item` and `index` (for repeated children), `empty` (shown in an
514
+ editor when the slot is empty).
515
+
516
+ #### `WidgetDefinition`
517
+
518
+ | Field | What it is |
519
+ |---|---|
520
+ | `kind`, `version`, `meta`, `schema`, `component` | Required |
521
+ | `defaults` | Starting props for editors |
522
+ | `events`, `parts` | Events it emits and the parts they happen on (`row`, `legend`…) |
523
+ | `slots` | Extra slots: `{ name: { label, accepts?: "any" \| "small" \| string[], max? } }`. `header` and `footer` always exist |
524
+ | `openSlots` | Any slot name is allowed (like Tabs) |
525
+ | `small` | It may sit in header slots |
526
+ | `frame` | `"card"` (default) or `"plain"` |
527
+ | `header` | `"widget"` when the widget draws its own title (like Kpi) |
528
+ | `fnProps` | Props that hold functions, with their parameter names |
529
+ | `migrations` | Upgrades for older saved props ([below](#versions-and-migrations)) |
530
+ | `implements`, `exposes` | Role and published state ([below](#roles-and-aliases)) |
531
+
532
+ ### `lazyWidget`: load the code on first use
533
+
534
+ A widget with a heavy dependency (a map, a 3D viewer) can download only when a dashboard
535
+ uses it. Every panel of that kind shares one download.
536
+
537
+ ```tsx
538
+ import { lazyWidget } from "@dashspec/renderer";
539
+ import { z } from "zod";
540
+
541
+ export const AcmeMap = lazyWidget({
542
+ kind: "acme.Map",
543
+ version: 1,
544
+ meta: { label: "Map", category: "Acme" },
545
+ schema: z.object({ title: z.string().optional(), zoom: z.number().default(10) }),
546
+ load: () => import("./AcmeMapWidget"), // default export: a component taking WidgetProps
547
+ fallback: <div className="my-skeleton" />,
548
+ });
549
+ ```
550
+
551
+ ### Versions and migrations
552
+
553
+ When a widget's props change shape, bump `version` and add a step in `migrations`:
554
+ `migrations[n]` turns props of version `n` into version `n + 1`. Documents saved with
555
+ the old version are upgraded when loaded; the stored JSON isn't changed.
556
+
557
+ ```ts
558
+ export const BatteryWidget = defineWidget({
559
+ kind: "acme.Battery",
560
+ version: 2,
561
+ // v1 had `limit`; v2 calls it `max`.
562
+ migrations: {
563
+ 1: ({ limit, ...rest }) => ({ ...rest, max: limit }),
564
+ },
565
+ // …meta, schema, component
566
+ });
567
+ ```
568
+
569
+ A node records the version it was saved with (`"version": 1`, default 1). A node saved
570
+ with a newer version than the registered widget still renders, with a `widget-version`
571
+ warning.
572
+
573
+ ### Roles and aliases
574
+
575
+ `implements` names the role a widget fills (`"table"`, `"kpi"`, `"chart"`…). Widgets
576
+ with the same role take the same JSON, so a document can switch between them by
577
+ changing `kind`. Each built-in declares one: `Table` is a `"table"`, `Kpi` a `"kpi"`,
578
+ the charts are `"chart"`.
579
+
580
+ `aliases` points a kind at another widget, so existing documents switch without being
581
+ edited. Both widgets must declare the same role, or the renderer throws:
582
+
583
+ ```tsx
584
+ // Every "kind": "Table" in every document now draws AcmeTable.
585
+ <DashSpecProvider widgets={[AcmeTable]} aliases={{ Table: "acme.Table" }}>
586
+ ```
587
+
588
+ `exposes` documents what the widget publishes to the state for other widgets, e.g.
589
+ `{ selection: "the clicked row" }`. It is informational, for editors.
590
+
591
+ ### Test with `checkWidget`
592
+
593
+ `checkWidget` returns the contract problems of a definition: an invalid kind, a missing
594
+ label or component, `defaults` that fail the schema, bad slot or `exposes` names.
595
+
596
+ ```ts
597
+ import { type AnyWidgetDefinition, checkWidget } from "@dashspec/renderer";
598
+ import { expect, test } from "vitest";
599
+ import { AcmeTable, BatteryWidget } from "./widgets";
600
+
601
+ const widgets: AnyWidgetDefinition[] = [AcmeTable, BatteryWidget];
602
+
603
+ test.each(widgets)("$kind honours the widget contract", (widget) => {
604
+ expect(checkWidget(widget)).toEqual([]);
605
+ });
606
+ ```