Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions .agents/skills/adding-dashboard-v2-widget-types/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
---
name: adding-dashboard-v2-widget-types
description: >
Guides adding or changing a widget type in dashboards v2 (`products/dashboards_v2/frontend/widgets/`):
the WidgetSpec, defineWidget, config schema, tile slots (Component, Loading, SampleData, HeaderExtra, Footer),
menuActions, allowedCustomizations and lazy loading, with the markdown type as the worked example.
Use when creating a new kind of tile content for a dashboards v2 host, changing a widget type's config,
or reviewing a diff under `frontend/widgets/`. Not for v1 dashboard widgets (`manage-dashboard-widgets`).
---

# Adding a dashboards v2 widget type

A widget type is the content a tile shows, such as a chart or markdown.
The tile owns the frame: title, description, menu, dragging, resizing and the error boundary.
Read `products/dashboards_v2/.agents/primitives.md` and `.agents/performance.md` first.

## Files

Give the type its own folder, `frontend/widgets/<type>/`:

- `<type>Spec.ts` holds the config schema, the `WidgetSpec` and the `defineWidget` call.
- Each component has its own file, such as `<Type>Widget.tsx`.

The layout functions, `validateDashboard` and tools that write dashboards as code load the spec file, sometimes outside the browser.
So the spec file loads its components with `React.lazy` and never imports one directly.
`widgetDefinition.tsx` depends only on React, so keep it that way: UI such as messages and error reporting goes in `WidgetView` or the tile.

## Rules

- Define `config` as a `z.strictObject`, and take its TypeScript type from the schema with `z.infer`. `defineWidget` checks every saved config against the schema before any part of the type gets it, so the parts never cast `config` and never type it as `unknown`.
- Give the spec its config type and its literal type name: `WidgetSpec<MarkdownConfig, 'markdown'>`.
- The `type` and every config field are saved in dashboard documents. Renaming one breaks saved dashboards, so it needs a migration, not a rename.
- A widget type fills only its slots: `Component`, `Loading`, `SampleData`, `HeaderExtra`, `Footer` and `menuActions`. Do not draw a title or add an error boundary in a widget.
- Give the type a `Loading` shaped like its content when it has one. Off-screen tiles and suspended tiles show it, so a tile looks like itself before it mounts.
- Give the type a `SampleData` when it shows data. A host passes `sampleData` to `DashboardView` while it has no real data, and the tile then shows this part instead of `Component` and runs no queries. Mark it as sample data and keep its made-up numbers out of tooltips.
- Components read only the small contexts they need, such as `FiltersContext` and `WidgetHostContext`, and never the dashboard state.
- `allowedCustomizations` lists the tile customizations the type allows, such as `['backgroundColor']`. The values a person picks are saved on the tile's `widget.appearance`.
- `menuActions(actions, context)` returns the tile's menu. Append entries to `actions` with a stable `key`, and change the config with `context.setConfig`, which saves one undo step.
- Add the type to `DEFAULT_WIDGETS` only when every host should get it. Otherwise a host passes the type in its own list.
- A pure function in the spec, such as `sizeFor`, gets a unit test.

## Example: markdown

`frontend/widgets/markdown/markdownSpec.ts`:

```ts
export const markdownConfigSchema = z.strictObject({ text: z.string() })

export type MarkdownConfig = z.infer<typeof markdownConfigSchema>

export const markdownSpec: WidgetSpec<MarkdownConfig, 'markdown'> = {
type: 'markdown',
size: { w: 8, h: 8, minW: 3, minH: 4 },
configSchema: markdownConfigSchema,
allowedCustomizations: ['backgroundColor'],
}

const MarkdownWidget = lazy(() => import('./MarkdownWidget').then((module) => ({ default: module.MarkdownWidget })))

export const markdownWidget = defineWidget({
...markdownSpec,
addTileOptions: [
{ label: 'Text', create: () => ({ type: 'markdown', config: { text: 'Write notes in **Markdown**.' } }) },
],
Component: MarkdownWidget,
})
```

`MarkdownWidget` gets `widget: ContentWidget<MarkdownConfig>`, so `widget.config.text` is a checked string.
A host passes the type in its list, such as `widgets={[createChartWidget({ runQuery }), markdownWidget]}`.

The chart type is a factory instead, `createChartWidget`, because a host adds its own kinds of chart and its query runner.
Follow it only when a host must configure the type.

## Before you report done

- `pnpm --filter=@posthog/frontend typescript:check` and the dashboards v2 Jest tests pass.
- The new type renders on the `/dashboard-v2` kitchen sink: its content, its loading state, and the "not valid" message for a broken config.
- Its tile can still be moved, resized and removed when the widget throws.
2 changes: 1 addition & 1 deletion frontend/src/productScenes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
import('../../products/customer_analytics/frontend/scenes/CustomerJourneyTemplatesScene/CustomerJourneyTemplatesScene'),
WarehouseProperties: () =>
import('../../products/customer_analytics/frontend/scenes/WarehousePropertiesScene/WarehousePropertiesScene'),
DashboardV2: () => import('../../products/dashboards_v2/frontend/DashboardV2Scene'),
DashboardV2: () => import('../../products/dashboards_v2/frontend/scene/DashboardScene'),
DataCatalog: () => import('../../products/data_catalog/frontend/DataCatalogScene'),
DataCatalogMetric: () => import('../../products/data_catalog/frontend/DataCatalogMetricScene'),
DataCatalogNewMetric: () => import('../../products/data_catalog/frontend/DataCatalogNewMetricScene'),
Expand Down
72 changes: 72 additions & 0 deletions products/dashboards_v2/.agents/performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Performance

Read this before you change how tiles, widgets or the grid render, what a context holds, or when a query runs.

Dashboards v2 aims for high performance and smooth frames on big dashboards, such as 200 tiles.
A change that is fine on a small dashboard can be slow or janky on a big one.
Judge each change at that size, not at the size of the fixture.
The sections between "Understand the cost" and "Measuring" go from the biggest effect on a big dashboard to the smallest.

## Understand the cost

- Cost is how often work runs, times how many elements it reaches, times what each element costs. A small cost repeated across hundreds of tiles on every pointer event blocks interaction.
- Tile count alone is a weak measure. Count rendered DOM nodes, chart points, observers and retained memory too. A few dense tables can cost more than many simple charts.
- A frame at 60 Hz lasts about 16.7 ms, shared with style, layout and paint. Scheduling work in an animation frame does not make it cheaper.
- Separate the phases before you optimize: initial load, the first movement of a gesture, continuous movement, release, and scroll and revisit. Each has different costs.

## Off-screen tiles

- A tile mounts its widget only once it scrolls into view (`grid/tileMounting.ts`). Do not add work that runs for every tile on load, such as a query, a measurement or a subscription, outside that gate.
- An unmounted tile keeps its place and shows a cheap placeholder, so a fast scroll never shows an empty cell.
- When many tiles come into view together, spread their mounts across frames, and cancel a pending mount when its tile leaves view first.
- Work that a tile does when it mounts must also be correct when it mounts late, such as after a filter changed while it was off screen.

## Charts and queries

- Moving or resizing a tile reuses its chart instance and its query results. Only data changes run queries.
- When a canvas changes size, draw the new image in the same frame, so the chart never shows blank.
- Charts that mount together share one request through the query batch runner. Do not add a path that sends one request per tile.
- A change that runs queries again, such as a filter or a refresh, runs them for every mounted chart. Keep that set to the charts on screen, and make sure visible tiles do not wait behind off-screen ones.

## Re-renders

- Every consumer of a context re-renders when its value changes, and `memo` does not stop that. Before you add a field to a context, check how often it changes and how many components read it. `DashboardStateContext` changes on every edit, so a tile that reads it re-renders on every edit.
- Keep fast-changing state close to where it is used. Gesture geometry stays in the grid or the active tile, and filter drafts stay in the filter bar. Do not push them into a wide context on every pointer event or keystroke.
- Widgets read only the small contexts they need (`FiltersContext`, `WidgetHostContext`) and never the dashboard state. This keeps a dashboard edit from redrawing every chart.
- Keep a light wrapper for a tile's position separate from its expensive content, so moving a tile does not re-render what is inside it.
- Keep context values, props and callbacks stable between renders with `useMemo` and `useCallback`. A host that rebuilds its `DashboardController` on every render makes every consumer re-render every time.
- Keep tile keys and chart instances stable across moves, resizes and mode changes.
- Memoization saves React work only. It does not stop browser layout or canvas drawing when a size changes.
- When a context makes many components re-render for a change most of them ignore, split it, or put a stable store in it that components subscribe to by slice. Measure first.

## Layout and paint

- A class toggled on the grid restyles every tile it reaches, even when React skips their renders. End each rule under a gesture class on a narrow target, such as the placeholder or the dragged tile, and not on tile content. An inherited property set on tiles, such as `cursor` or `pointer-events`, has the same cost.
- Mount transient overlays, such as a drop hint, through a portal outside the grid, so inserting them does not restyle the tiles.
- Group geometry reads before DOM writes. Alternating them across tiles forces layout for each tile.
- Do not mount large control trees only because a gesture starts or ends.

## Work frequency

- Pointer events, resize observers and state updates can ask for the same work several times in one frame. Keep the latest state and combine the updates.
- Saving and other persistence stay out of the pointer event path. Save the finished layout.
- Throttling does not fix expensive work. A long callback still blocks every frame it runs in.
- Cancel scheduled work and listeners when a gesture ends or its target goes away.

## Code loading

- Load a widget type's or a kind of chart's component with `React.lazy`, so a page fetches only the kinds it draws. `WidgetView` and `ChartWidget` already wrap them in `Suspense` with the type's loading state.
- Keep specs, schemas and the tile frame eager. Layout and validation need specs before any tile mounts, and the frame renders on every tile.
- Lazy-load at module level, once per component. A `lazy()` call inside a render makes a new component each time, which remounts the tile.
- Do not lazy-load a small component that every tile draws on first paint. A request per kind costs more than the bytes it saves.

## Measuring

- Check a change that touches any of the above on a big dashboard, not only on the kitchen sink fixture. Use invented data with dense tables and charts.
- Use the React profiler for re-renders and a browser trace for scripting, style, layout and paint. Fix the viewport, zoom and device pixel ratio, record a baseline, and change one thing at a time.
- Measure cold and warm separately: the first gesture after a fresh load, a repeat gesture, and a gesture after scrolling through every tile.
- Measure in a visible window. A hidden or covered window throttles animation frames, so its timings are not valid.
- Tests protect behavior. They do not show frame rate.
- In production, each load, refresh, filter change and tab switch sends a `dashboard v2 loaded` event, tagged with the host's `surface`. It carries the time to the first and last query result, query and cache counts, long main-thread tasks, and whether the page was hidden. A DevTools trace shows the same span as a `dashboard v2 <trigger>` measure.

[`products/dashboards/PERFORMANCE.md`](../../dashboards/PERFORMANCE.md) covers the v1 dashboard in more depth. Its code references and grid details do not apply to v2, but its measuring method does.
60 changes: 60 additions & 0 deletions products/dashboards_v2/.agents/primitives.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Primitives

Read this before you write or review any file under `frontend/`.

A team picks only the primitives it wants and composes them anywhere, the way it uses Quill components.
A design is right when any product can take one primitive and use it without the others.

## Primitives are not tied to a scene

The primitives are the grid, tiles, sections, tabs, widgets, filters and the time range picker.
The `/dashboard-v2` scene is one host that composes them. It is not where they belong.

- A host picks which primitives it uses and how. It can render a full dashboard, one tile, or a filter bar over its own content.
- Components know nothing about the scene around them. They get data and callbacks through props, a `DashboardController`, or a small context such as `FiltersContext`. They never read a scene logic, the URL, feature flags or the current team.
- The host owns everything scene-specific: where the document comes from and how it is saved, who can edit it, which widget types and filter kinds exist, and how queries run. `scene/` holds that code for the `/dashboard-v2` scene, and no primitive imports from it.
- A primitive renders with only the providers it needs. Do not add a provider that every primitive must have before it can render.

### A dashboard in another product

Pass your own state to `DashboardView` as props. Pick the widget types and the query runner your product needs.
`scene/DashboardScene.tsx` is the full example.

```tsx
const { filters, timeRange } = useDashboardFilters({ types: myFilterTypes, time: { timezone } })
return (
<DashboardView
dashboard={dashboard}
activeTabId={activeTabId}
widgets={MY_WIDGETS}
disabledReasonFor={disabledReasonFor}
onEdit={onEdit}
onActiveTabChange={setActiveTab}
filters={filters}
timeRange={timeRange}
header={<MyHeader />}
/>
)
```

Event handlers, `history` and `refresh` can be written inline. Keep `dashboard`, `widgets`, `filters`, `timeRange`, `disabledReasonFor`, `tileActions`, `tilePlacementActions` and `dashboardActions` the same between renders, such as from a logic, a hook or a module constant. A new one re-renders every tile.

Leave out what you do not need. With no `filters`, `timeRange`, `refresh` or `history`, the dashboard shows no filter bar, picker, refresh button or undo.

### One tile on its own

Render `WidgetCard` with the widget and the widget types that can draw it. No dashboard, grid or controller is needed.
A tile's menu takes two lists: `actions` for what the tile does to itself, and `placementActions` for where it sits, such as moving or removing it. A tile on its own passes only `actions`, or neither for no menu.
Wrap it in `FiltersContext` or `WidgetHostContext` only when the page has filters, a refresh or sample data to pass down.

```tsx
<FiltersContext.Provider value={{ time: { from: 'now-30d', to: 'now' }, filters: [] }}>
<WidgetCard widget={signupsChart} widgets={[createChartWidget({ runQuery: myRunner })]} />
</FiltersContext.Provider>
```

## Tiles and widgets

- A tile is the container. It owns what every tile shares: where it sits in the grid, dragging and resizing, the right-click menu, and its parts and appearance. Tile code lives in `frontend/tiles/`.
- A widget is the content a tile shows, such as a chart or markdown. A team adds its own widget type through a `WidgetDefinition` and passes it to the dashboard. Widget code lives in `frontend/widgets/`. To add or change a widget type, use the `/adding-dashboard-v2-widget-types` skill.
- A tile does not know which widget it holds. Behavior that only one kind of content needs goes in that widget type, not in the tile.
21 changes: 21 additions & 0 deletions products/dashboards_v2/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Dashboards v2 agent guide

Dashboards v2 is a set of primitives that a host composes: grid, tiles, sections, tabs, widgets, filters and the time range picker.
The `/dashboard-v2` scene, behind the `dashboards-v2` feature flag, is one host.
Other products, such as APM and web analytics, compose the same primitives on their own pages.

## Read the guide for your area first

Topic rules live in [`.agents/`](.agents/).
Before you write or review code in an area below, open its guide.
Each row is the only place that says when to read a guide, so a new guide gets a new row here.

| Guide | Read it before you write or review |
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
| [.agents/primitives.md](.agents/primitives.md) | Any file under `frontend/`, or a change to what one primitive imports from another or from the host |
| [.agents/performance.md](.agents/performance.md) | A change to how tiles, widgets or the grid render, what a context holds, or when a query runs |

## Rules for every change

- Temporary code has a dated TODO directly above it: `// TODO(YYYY-MM-DD): <what replaces it>`, dated the day it was added, with a second line that says why it is temporary. Temporary code includes fixture data used as real data, placeholder rendering, hardcoded queries and stubbed saving. The change that replaces the code removes the comment. `grep -rn "TODO(" products/dashboards_v2` lists the open items.
- Skills published to users stay in [`skills/`](skills/), because `hogli build:skills` and CI collect only `products/*/skills/`. A skill that needs a repository checkout goes in the root `.agents/skills/`.
1 change: 1 addition & 0 deletions products/dashboards_v2/CLAUDE.md
Loading
Loading