From 04bbb55a40c46bd5f51f281d7ad657235543ee12 Mon Sep 17 00:00:00 2001 From: Matt Pua Date: Wed, 25 Nov 2026 15:23:01 -0500 Subject: [PATCH 01/10] chore(dashboards): trim v2 comments and drop the readme Co-Authored-By: Claude Opus 5.5 --- products/dashboards_v2/README.md | 229 ------------------ .../DashboardV2Unavailable.stories.tsx | 1 - .../frontend/dashboard/dashboardSchema.ts | 11 +- .../frontend/dashboard/dashboardTypes.ts | 3 +- .../frontend/dashboard/dashboardV2Context.ts | 1 - .../frontend/dashboard/tileTree.ts | 1 - .../frontend/filters/ValueList.tsx | 2 +- .../frontend/filters/filterSpec.ts | 1 - .../filters/property/ConditionEditor.tsx | 1 - .../filters/property/PropertyFilter.tsx | 1 - .../filters/property/propertyOperators.ts | 2 +- .../frontend/filters/useDashboardFilters.ts | 1 - .../dashboards_v2/frontend/grid/TileGrid.tsx | 1 - .../frontend/grid/gridCompactor.ts | 2 - .../frontend/grid/tileMounting.ts | 2 - .../frontend/tiles/ContentTile.tsx | 1 - .../frontend/tiles/DashboardTileGrid.css | 1 - .../frontend/tiles/DashboardTileGrid.tsx | 1 - .../frontend/tiles/SectionTile.tsx | 1 - .../frontend/tiles/TileContextMenu.tsx | 1 - .../frontend/tiles/WidgetCard.tsx | 1 - .../frontend/widgets/chart/vizTypes.ts | 1 - .../frontend/widgets/widgetDefinition.ts | 1 - .../frontend/widgets/widgetSpec.ts | 1 - 24 files changed, 7 insertions(+), 261 deletions(-) delete mode 100644 products/dashboards_v2/README.md diff --git a/products/dashboards_v2/README.md b/products/dashboards_v2/README.md deleted file mode 100644 index fc3843c43d7bc..0000000000000 --- a/products/dashboards_v2/README.md +++ /dev/null @@ -1,229 +0,0 @@ -# Dashboards v2 - -A layout primitive for dashboards that any PostHog team can build on. -It covers the grid, tiles, sections, tabs, and the drag and resize behavior. - -Update this file in the same change whenever a rule below changes. - -## The model - -A dashboard has tabs. A tab has one grid. A grid holds tiles, and nothing else. - -| Term | Meaning | -| ------- | ---------------------------------------------------------------------------- | -| Tile | One cell-aligned box in a grid, with a place: `x`, `y`, `w`, `h`. | -| Widget | What a tile shows: a number, a chart, text, or a section. | -| Section | A widget that is itself a grid. A section can sit inside another section. | -| Tab | A named grid. Tabs belong to the dashboard only. A section cannot hold tabs. | - -The whole dashboard is one JSON tree (`Dashboard` in `frontend/dashboard/dashboardTypes.ts`). -It has a `title` and an optional `description`, shown under the title. - -## Tabs - -A tab holds a grid of tiles, or is a link elsewhere: `{ id, title, tiles }` or `{ id, title, href }`. -A link tab opens a PostHog path or a full URL in a new browser tab. It holds no tiles, so a tile cannot move to it. -A dashboard keeps at least one tab with tiles, and a link tab never becomes the tab that shows. - -## The grid - -- A tab's grid has 24 columns. A row is 10px tall and the gap between tiles is 12px, so heights move in 22px steps. -- A tile's place is in whole columns and rows. -- A tile added to a grid scrolls into view. -- Tiles never overlap, and no tile has an empty row above it that it could move into. - -## Sections - -A section is drawn as a card inside its own space, like a tile, so sections side by side keep the grid gap between them. -Its grid has one column for each column the section covers, and sits 12px in from the card's sides (`GRID.sectionInsetPx`). -So tiles inside a section are slightly narrower than the same number of columns outside it, and do not line up with them. -A tile keeps its column count when it moves in or out of a section, unless the grid it lands in is narrower than the tile or the row it joins is full. - -A section is resized like a tile, from any edge or corner. Its height is at least the rows for its card header and the padding above and below its tiles (`GRID.sectionChromeRows`), plus the rows its tiles need. A section resized taller keeps that height (`minRows`) and still grows when its tiles need more. Resized back down to what its tiles need, it follows them again. -A closed section is three rows, enough for its card's header (`GRID.collapsedSectionRows`). An empty open section keeps four rows for its tiles, so it can take a drop. -Anyone can open or close a section, for their own view only. It is not saved and is not an undo step. -A section cannot be resized narrower than its tiles need. -A section moved into a narrower grid gets narrower, and its tiles are placed again to fit. -A section's tiles can be laid out in 1 to 4 equal columns with Auto layout in its menu (`autoLayout`). Its tiles fill the columns row by row in reading order and keep their heights. - -## Where a tile goes - -One function decides every place: `placeTiles` in `frontend/grid/placeTiles.ts`. -A drag inside a grid, a drop from another grid, and a saved dashboard all go through it. - -1. With no drag or resize running, tiles only move up to close gaps. -2. During a drag or resize, every other tile starts from where it was when the gesture began. - The result depends on where the pointer is now, not on the path it took. -3. A tile dropped on the upper half of a row joins that row. - The row's tiles keep their order and slide apart to make room. -4. If the row is full, its tiles get narrower to fit, down to each widget's minimum width. - The row does not wrap. -5. If the row cannot get narrow enough, the tile takes that place and whatever it lands on moves down. -6. A tile dropped on the lower half of a row goes under that row. -7. A resize never changes another tile's width. Tiles in the way move down. - -## Drag and resize - -`react-grid-layout` moves and sizes the tiles inside one grid (`frontend/grid/TileGrid.tsx`). The grid knows nothing of the dashboard: `frontend/tiles/DashboardTileGrid.tsx` hands it the tiles to draw and turns its moves into edits. -It does not decide places: its compactor is `placeTiles`. - -- A tile is dragged by its title bar. A tile without a title is dragged by its body. A section is dragged by its header. -- The tile follows the pointer. A dashed outline shows where it will land, and it lands exactly there. -- While a tile is over another grid, that grid shows the outline and makes room. - The tile's own grid closes up. -- The grid a tile is over is decided from where every grid was when the drag began (`frontend/grid/dropTargets.ts`). - A preview moves and resizes grids, so reading them during the drag makes the outline jump between two grids. -- A tile leaves a section when the pointer leaves the area the section covered when the drag began. -- A tile dropped on another tab's name moves to the bottom of that tab. -- A section grows while a tile is dragged or resized inside it, and the tiles below it move down. -- A tile or an open section resizes from any edge or corner. A closed section resizes in width only. - -## Editing - -- Every change goes through one pure function, `applyEdit` in `frontend/dashboard/dashboardEdits.ts`, and comes out settled: no overlaps, no gaps, and correct section heights. -- Tabs can be added, renamed, and removed. The last tab cannot be removed. -- Undo and redo cover every edit, and a press that moves nothing adds no undo step. -- Only people who can edit dashboards can change the layout. Everyone else sees it read-only. - -## Embedding a dashboard - -The frontend is grouped by concept: `dashboard/`, `grid/`, `tiles/`, `widgets/`, `presentation/` and `access/`. Only the `/dashboard-v2` host, `DashboardV2Scene.tsx` and `dashboardV2Logic.ts`, sits at the root. - -The components hold no business logic and never import a kea logic, so any page can render a dashboard. - -- `DashboardV2View` in `frontend/dashboard/DashboardV2View.tsx` renders the tabs and the grid from a `DashboardV2Controller` (`frontend/dashboard/dashboardV2Context.ts`). -- The host owns the dashboard, undo history, access rules, saving and the URL. `recordEdit`, `undoEdit` and `redoEdit` in `frontend/dashboard/dashboardHistory.ts` give every host the same undo behavior, and `useDashboardHistory` wraps them for a host that keeps its dashboard in React state. It passes values in and gets edits back through `onEdit`. -- The view owns only what the screen and a drag decide: the stacked layout on narrow screens, the drop target, and the undo shortcut. -- The view passes the controller down through context. The drop target has a context of its own, so a drag re-renders only what reads it. -- `dashboardV2Logic` is the host for the `/dashboard-v2` scene. Another product supplies its own host, and its own header through the `header` slot. -- When a dashboard can't load, the host can render `DashboardV2Unavailable` (`frontend/dashboard/DashboardV2Unavailable.tsx`) in place of the view. Each problem has a default hedgehog, title and description, and the host can replace any of them or add `actions`, such as a link back to its own list. - -## Narrow screens - -Below 768px of canvas width (`GRID.stackBelowPx`), every tile is full width and tiles cannot be dragged or resized. - -- Tiles stack in reading order: top to bottom, then left to right. Sections stack their own tiles the same way. -- Text and number tiles keep their height. Line and bar charts stay between 10 and 16 rows, so one chart never fills the screen. -- The stacked layout is worked out from the saved one each time and is never saved. -- Only arranging tiles (`placeTiles`) is refused. Other edits, such as moving a tile to another tab, still work. -- A disabled menu entry shows its reason under its label, since a touch screen shows no tooltip. - -## Widgets - -The dashboard does not know any widget type. The host passes the types it supports as `widgets` on the controller. - -A type has two parts, so code outside the browser can use the first without React: - -- A `WidgetSpec` (`frontend/widgets/widgetSpec.ts`) is plain data: its add menu items, its default and minimum size, a zod `configSchema` for the widget's `config`, and whether its data refreshes. -- A `WidgetDefinition` (`frontend/widgets/widgetDefinition.ts`) is the spec plus the `Component` that renders it. The controller takes these. - -A widget's own fields sit in `config`. The fields every tile has (`type`, `title`, `description`, `refreshedAt`, `parts`) sit beside it. -A tile's `description` shows in a tooltip on an info icon beside its title. -A tile is dragged by its header, or by its body when it has no header. A widget marks text people should be able to select with the `TileGrid__text` class, and pressing on it selects instead of dragging. - -How the dashboard uses them: - -- The add menu lists every add menu item of the host's widgets, then Section. A section is part of the grid, so it is built in and has no spec. -- A saved widget whose type is not in the list keeps a place in the grid and shows that the dashboard can't render it. -- The layout functions in `frontend/grid/gridTiles.ts` take a `sizeOf` function instead of importing widgets. Build it from specs with `sizeOfWidgets`. The view does this itself, and a host that calls `applyEdit` does the same. -- `DEFAULT_WIDGETS` in `frontend/widgets/defaultWidgets.ts` is the set that ships with dashboards v2. A host can pass it, a subset, or its own list. - -A widget type can also: - -- add controls to its tile's header with `HeaderActions`, such as an interval picker or an "Open as insight" button; -- replace what its footer shows with `Footer`; -- set what its tile shows while its component suspends with `Loading`. Without it, the tile shows `WidgetLoading`, a skeleton a widget can also render itself while it loads; -- change its tile's right-click menu: `menuActions` adds entries, and `tileActions(actions, { widget })` receives the whole list to remove, disable, reorder or add entries by `key`. - -A host can also pass `tileActions(actions, { id, widget })` on the controller. It runs last, for content tiles and sections, so a page can hide `remove` everywhere or `chart-type` on one dashboard. The order is built-in actions, widget `menuActions`, widget `tileActions`, host `tileActions`. The built-in keys are listed on `MenuAction.key`. - -The dashboard has its own menu, beside undo and redo. Its built-in action, `download-image`, downloads the active tab as a PNG or WebP image, with every tile drawn first. A host passes `dashboardActions(actions)` on the controller to hide, disable or add entries the same way. - -To hide a tab from someone, such as a tab behind a feature flag, the host leaves it out of the dashboard it passes in. Whatever the host passes reaches the browser, so tabs a person may not see are removed where the dashboard is loaded, not in the view. - -To add a widget type, write its spec and component in `frontend/widgets//`, then pass `defineWidget({ ...spec, Component })` in the host's list. - -### One widget on its own - -`WidgetCard` in `frontend/tiles/WidgetCard.tsx` renders one widget in its card, with no dashboard around it: ``. -Inside a dashboard, `ContentTile` renders the same card with the tile's actions. - -### Hiding tiles for one view - -`withoutTiles(dashboard, ids, sizeOf)` removes tiles from what one person sees, such as a tile with nothing to show yet, and closes the gaps they leave. -It is never saved, so the tiles return to their places when they are shown again. -Combine it with `withFolds` in the dashboard the host passes to the view, and pass the same function as the view to `applyEdit`. - -### Charts - -A chart is one widget type, `chart`, whose config is a query and a kind of chart: `{ query, viz: { type, options } }`. -The query is `{ language, query }` in one of three languages: `hogql` with a HogQL `SELECT`, `metrics` with a `MetricsQuery` node, or `traces` with a `TraceSpansQuery` or `TraceSpansAggregationQuery` node. -The data and the way it is drawn are separate, so changing a chart from a line to a bar never runs its query again. - -- A kind of chart is a `VizSpec` (`frontend/widgets/chart/vizType.ts`): a label, a size, and a zod schema for its options. A `VizDefinition` adds the component that draws a query result. -- `createChartWidget({ extraVizTypes, runQuery, states, menuActions })` builds the chart widget type. It draws every built-in kind of chart, so a dashboard saved by another host still renders. A host adds its own kinds with `extraVizTypes` and supplies `runQuery`, so the dashboard never fetches data itself. `runQuery` gets `{ query, time, filters? }` and returns `{ frames, fetchedAt?, stale? }`. A query's `language` is `hogql`, `metrics`, `traces`, or `insight` for any node `/query` runs. In the request, `time` is the chart's own `config.time`, or else the range from `TimeRangeContext`, which `DashboardV2View` fills from the dashboard's `time` (default `now-7d` to `now`). `filters` holds the dashboard's filters that have a value, and is left out when none do. -- A query result is a list of `DataFrame`s. A kind of chart only draws rows. Loading, empty and error states come from the kind of chart if it sets them, then from the `states` the host passes to `createChartWidget`, then from built-in ones. The built-in kinds set a skeleton shaped like their chart, and a host's `states` replace the built-in kinds' states but not those of its own kinds. A kind of chart can also decide what counts as empty with `isEmpty`. -- When a chart's time range or query changes, the tile keeps its last result on screen, faded, until the new one arrives. -- The add menu has one "Chart" item, which starts as a line chart. The tile's "Chart type" menu switches its kind, and its "Chart options" menu sets the options that kind declares. A chart takes its size from its kind of chart. - -To add a kind of chart, write its spec and component in `frontend/widgets/chart/viz//`. Pass it as `extraVizTypes`, or add it to `DEFAULT_VIZ_TYPES` in `frontend/widgets/chart/createChartWidget.tsx` to ship it with dashboards v2. - -## Filters - -A filter narrows the data every widget shows, such as one browser or one service. Each piece is separate, so a page takes only the ones it wants. - -| Piece | What it does | -| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `FilterSpec`, `FilterDefinition` (`frontend/filters/`) | A kind of filter. The spec is plain data: add menu items, a zod `configSchema`, and `fieldOf`. The definition adds the `Control` a person picks a value with. Wrap it in `defineFilter`. | -| `createSelectFilter(fields)` (`frontend/filters/select/`) | A kind that picks one or more values of a field. It saves the field's `key` and `options` in the filter's config. | -| `FiltersContext` | Gives widgets the filters that have a value, the way `TimeRangeContext` gives them the time range. A chart adds them to its request as `filters`, left out when none apply. | -| `FilterPill` | One filter's control, with a remove button when the page passes `onRemove`. | -| `FitRow` | Keeps items on one line. Items that don't fit open from a "+N filters" button. | -| `AddFilterMenu` | Lists the add menu items of the kinds it gets, and disables a field already added. | -| `FilterBar` | The default arrangement: filters with a value first, in a `FitRow`, after `AddFilterMenu`. | - -A page without a dashboard can render `FilterPill`s, or a `FilterBar`, and wrap its own widgets in `FiltersContext`. - -### Filters on a dashboard - -- A host offers a time range picker by passing `timeRange: { value, onChange }` on the controller. `useTimeRangeController(ranges)` builds it, where `ranges` are the quick ranges the picker offers, such as `{ label: 'Last hour', from: 'now-1h' }` for APM. Left out, the picker offers `DEFAULT_QUICK_RANGES`, from the last 24 hours to the last 90 days. The viewer's range overrides the dashboard's saved `time` and is never saved. `TimeRangePicker` (`frontend/time/`) wraps quill's `DateTimePicker`, and saves a quick range as a range relative to now, such as `now-7d`. -- A host offers filters by passing `filters: { types, values, onValueChange }` on the controller. `useFiltersController(types)` builds it with the values kept in component state; a host that keeps them elsewhere, such as the URL, builds it itself. Left out, the dashboard has no filters. -- `useDashboardFilters({ types, Bar, time: { ranges } })` builds both parts in one call. Each option left out drops its part, so a host can offer only filters or only a time range. `filters.Bar` replaces `FilterBar`, such as with a bar that has no overflow. -- A dashboard shows its filter bar only when an editor turns on "Allow filters" in the dashboard menu (`allowFilters`, the `allow-filters` action). It is off by default. -- Editors add and remove filters. Which filters a dashboard has is saved, as `filters`, and is an undo step. A dashboard has one filter per field (`fieldOf`, such as a select filter's `key`). -- The value each person picks is not saved and is not an edit. The host keeps it, such as in its logic or the URL, so viewers who cannot edit can still filter. -- The host's `runQuery` applies the kinds of filter it knows to each query, so the dashboard never builds a query itself. -- `validateDashboard(document, widgets, filters)` reports a filter of an unknown kind, an invalid config, or a second filter on the same field. - -### Analytics filters - -`createPropertyFilter({ featured, search })` (`frontend/filters/property/`) filters on any event or person property. A person picks one or more conditions, all of which must hold, such as "is not Chrome" and "contains Safari". Each condition has an operator that fits the property's type (`is`, `is not`, `contains`, `doesn't contain`, `matches`, `is set`, `is not set`, or `>` and `<` for numbers), then values suggested from the project's data or typed text. `featured` are the properties the add menu names, so a product can put the ones it cares about first. `search` adds a menu entry, such as "More properties", that opens `FieldSearch` over the properties its `load` returns, so a product can offer its own custom events. A kind of filter adds an entry like this with `pickerLabel` on its spec and `Picker` on its definition. A filter with no value yet has a dashed outline and reads "Pick a value", because it does not narrow the widgets. - -`ANALYTICS_FILTER_TYPES` (`frontend/filters/analytics/`) is a property filter featuring browser, OS, device type and country. `analyticsPropertyFilters(request.filters)` turns property and select filters into property filters a query's `properties` takes. - -## Dashboards as code - -A dashboard is one JSON document, so it can live in a repo or be written by a tool. -The zod schemas in `frontend/dashboard/dashboardSchema.ts` are the only definition of the document: its types are inferred from them. -`validateDashboard(document, specs)` in `frontend/dashboard/validateDashboard.ts` checks a document against them before it loads, and returns each problem with its path. - -- It reports a document that is not a v2 dashboard, an unknown widget type, a missing or misspelled widget field, a tile smaller than its widget's minimum, a tile past the edge of its grid, and an id used twice. -- Overlaps and gaps are not problems, because loading a dashboard settles them. -- It needs only specs, so a CI check or an MCP tool can run it without rendering anything. - -A widget can show on more than one tile, such as the same chart on two tabs. -The document stores it once, in `widgets`, and each tile points at it with `{ "ref": "" }`, plus its own `parts` and `appearance`. -Its type, title, description and config are shared, so changing a chart's query or kind on one tile changes it on every tile. -Size, position, parts and appearance belong to each tile. - -- `loadDashboard(document)` in `frontend/dashboard/sharedWidgets.ts` puts each shared widget back on its tiles, with `ref` set, so the rest of the code sees whole widgets. `saveDashboard(dashboard)` stores them once again and drops any no tile shows. -- "Also show on tab" in a tile's menu (`addToGrid`) places a second tile for the same widget on another tab. Removing either tile leaves the other. -- `validateDashboard` reports a tile pointing at a widget the document does not have. - -## Checking a change - -Layout bugs show up under a real pointer, not in a unit test. - -1. `frontend/grid/placeTiles.test.ts` covers the placement rules as a table. Add a row for a new rule. -2. The stories in `frontend/DashboardV2Scene.stories.tsx` drag real tiles in a browser and assert that each one lands on its outline with nothing overlapping. Add a story for a new gesture. -3. Try the gesture by hand with a real pointer. diff --git a/products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.stories.tsx b/products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.stories.tsx index fd5fbbaa4f469..dd419df15b28b 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.stories.tsx +++ b/products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.stories.tsx @@ -16,7 +16,6 @@ const meta: Meta = { } export default meta -/** The default view for each problem. */ export const Defaults: StoryObj = { render: () => (
diff --git a/products/dashboards_v2/frontend/dashboard/dashboardSchema.ts b/products/dashboards_v2/frontend/dashboard/dashboardSchema.ts index 0af14844b59e1..005e843834c16 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardSchema.ts +++ b/products/dashboards_v2/frontend/dashboard/dashboardSchema.ts @@ -53,11 +53,6 @@ export const widgetQuerySchema = z.union([ z.strictObject({ language: z.literal('logql'), query: z.string().regex(/\S/).max(MAX_QUERY_TEXT) }), ]) as unknown as z.ZodType -/** - * The time range a query runs over. Each end is an expression such as `now-7d` or `now`, or an ISO 8601 time. Keep - * relative ends relative, because the backend then caches the result under the same key on every reload. - */ -/** `now-` and an amount of seconds (`s`), minutes (`m`), hours (`h`), days (`d`), weeks (`w`), months (`M`) or years (`y`). */ export const RELATIVE_TIME = /^now-(\d+)([smhdwMy])$/ const timePointSchema = z @@ -68,6 +63,10 @@ const timePointSchema = z 'Use now, now-, or an ISO 8601 time' ) +/** + * The time range a query runs over. Each end is an expression such as `now-7d` or `now`, or an ISO 8601 time. Keep + * relative ends relative, because the backend then caches the result under the same key on every reload. + */ export const timeRangeSchema = z.strictObject({ from: timePointSchema, to: timePointSchema }) export const tilePlaceSchema = z.strictObject({ @@ -100,7 +99,6 @@ export const contentWidgetSchema = z.strictObject({ type: z.string().refine((type) => type !== 'section', 'A section needs a title and tiles'), title: z.string().optional(), description: z.string().optional(), - /** When the widget's data was last computed, as an ISO timestamp. */ refreshedAt: z.iso.datetime({ offset: true }).optional(), parts: contentWidgetPartsSchema.optional(), appearance: tileAppearanceSchema.optional(), @@ -143,7 +141,6 @@ export const tileSchema = z.strictObject({ }, }) -/** A tab that holds a grid of tiles. */ export const gridTabSchema = z.strictObject({ id: z.string().min(1), title: z.string(), diff --git a/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts b/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts index 0dd5d53ed0f6f..201a1d43b604c 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts +++ b/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts @@ -65,7 +65,6 @@ export interface WidgetSize { stackedRows?: { min: number; max: number } } -/** A tile's content. `Config` is the widget type's own config, which its spec declares. */ export type ContentWidget = Omit, 'config'> & { config: Config } export type SectionWidget = z.infer @@ -98,7 +97,7 @@ export function isGridTab(tab: DashboardTab): tab is GridTab { return 'tiles' in tab } -/** The tabs that hold tiles. A valid dashboard has at least one. */ +/** A valid dashboard has at least one. */ export function gridTabs(dashboard: Dashboard): GridTab[] { return dashboard.tabs.filter(isGridTab) } diff --git a/products/dashboards_v2/frontend/dashboard/dashboardV2Context.ts b/products/dashboards_v2/frontend/dashboard/dashboardV2Context.ts index d5d3ee25e22aa..ca850f8d02272 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardV2Context.ts +++ b/products/dashboards_v2/frontend/dashboard/dashboardV2Context.ts @@ -33,7 +33,6 @@ export interface DashboardV2Controller { * returns the list to show. Lets a page hide, disable or add actions by `MenuAction.key`, such as `remove`. */ tileActions?: (actions: MenuAction[], tile: { id: string; widget: Widget }) => MenuAction[] - /** Like `tileActions`, for the dashboard menu. */ dashboardActions?: (actions: MenuAction[]) => MenuAction[] /** * Left out, the dashboard shows no refresh button. Each refresh, from the button or the interval picked there, runs diff --git a/products/dashboards_v2/frontend/dashboard/tileTree.ts b/products/dashboards_v2/frontend/dashboard/tileTree.ts index a2f24b09b0716..9dd708f60342d 100644 --- a/products/dashboards_v2/frontend/dashboard/tileTree.ts +++ b/products/dashboards_v2/frontend/dashboard/tileTree.ts @@ -1,6 +1,5 @@ import { type Dashboard, type Tile, isGridTab, isSection } from './dashboardTypes' -/** The tiles in a grid and in every section inside it. */ export function everyTile(tiles: Tile[]): Tile[] { return tiles.flatMap((tile) => (isSection(tile) ? [tile, ...everyTile(tile.widget.tiles)] : [tile])) } diff --git a/products/dashboards_v2/frontend/filters/ValueList.tsx b/products/dashboards_v2/frontend/filters/ValueList.tsx index ed5b7f17606ca..3fee6eda5417e 100644 --- a/products/dashboards_v2/frontend/filters/ValueList.tsx +++ b/products/dashboards_v2/frontend/filters/ValueList.tsx @@ -12,7 +12,7 @@ export interface ValueOption { } export interface ValueListProps { - /** Returns the values that match the typed text. Left out, the person types each value. */ + /** Left out, the person types each value. */ load?: OptionsLoader selected: string[] onChange: (selected: string[]) => void diff --git a/products/dashboards_v2/frontend/filters/filterSpec.ts b/products/dashboards_v2/frontend/filters/filterSpec.ts index 5bf055d95e8ad..84de7fc2674da 100644 --- a/products/dashboards_v2/frontend/filters/filterSpec.ts +++ b/products/dashboards_v2/frontend/filters/filterSpec.ts @@ -4,7 +4,6 @@ import type { DashboardFilter } from '../dashboard/dashboardTypes' export interface AddFilterMenuItem { label: string - /** Builds the filter the menu adds. The dashboard gives it an id. */ create: () => Omit, 'id'> } diff --git a/products/dashboards_v2/frontend/filters/property/ConditionEditor.tsx b/products/dashboards_v2/frontend/filters/property/ConditionEditor.tsx index fb701856ce270..3504a004b3c78 100644 --- a/products/dashboards_v2/frontend/filters/property/ConditionEditor.tsx +++ b/products/dashboards_v2/frontend/filters/property/ConditionEditor.tsx @@ -25,7 +25,6 @@ export function ConditionEditor({ if (!next) { return } - // A value carries over only to an operator that takes the same kind of value. const keep = next.input === option.input && next.input !== 'none' onChange({ id: draft.id, operator: next.operator, value: keep ? draft.value : undefined }) } diff --git a/products/dashboards_v2/frontend/filters/property/PropertyFilter.tsx b/products/dashboards_v2/frontend/filters/property/PropertyFilter.tsx index d05a3670b7bcc..df6de9d3ce800 100644 --- a/products/dashboards_v2/frontend/filters/property/PropertyFilter.tsx +++ b/products/dashboards_v2/frontend/filters/property/PropertyFilter.tsx @@ -68,7 +68,6 @@ export function PropertyFilter({ {filter.label ?? key} {drafts.map((draft, index) => ( - // The joining word sits beside its condition, so the list reads top to bottom as one sentence.
{index === 0 ? 'where' : 'and'} diff --git a/products/dashboards_v2/frontend/filters/property/propertyOperators.ts b/products/dashboards_v2/frontend/filters/property/propertyOperators.ts index b89c4ff0ad0c6..ec969cb1296d6 100644 --- a/products/dashboards_v2/frontend/filters/property/propertyOperators.ts +++ b/products/dashboards_v2/frontend/filters/property/propertyOperators.ts @@ -52,7 +52,7 @@ const DATE = [option(PropertyOperator.IsDateAfter, 'after'), option(PropertyOper const BOOLEAN = [option(PropertyOperator.Exact, 'is'), ...SET] -/** The operators that fit a property's type. An unknown type is treated as text. */ +/** An unknown type is treated as text. */ export function operatorsFor(type: PropertyType | null | undefined): OperatorOption[] { switch (type) { case PropertyType.Numeric: diff --git a/products/dashboards_v2/frontend/filters/useDashboardFilters.ts b/products/dashboards_v2/frontend/filters/useDashboardFilters.ts index 5c411861a9eb1..a35e771b35c8c 100644 --- a/products/dashboards_v2/frontend/filters/useDashboardFilters.ts +++ b/products/dashboards_v2/frontend/filters/useDashboardFilters.ts @@ -18,7 +18,6 @@ export function useDashboardFilters({ types, Bar, time }: DashboardFiltersOption filters?: FiltersController timeRange?: TimeRangeController } { - // Both hooks always run, as hooks must; an option left out only drops its part from the result. const filters = useFiltersController(types ?? [], Bar) const timeRange = useTimeRangeController(time?.ranges, time?.timezone) return { filters: types ? filters : undefined, timeRange: time ? timeRange : undefined } diff --git a/products/dashboards_v2/frontend/grid/TileGrid.tsx b/products/dashboards_v2/frontend/grid/TileGrid.tsx index 771fa6c55abd7..2ef98773764c3 100644 --- a/products/dashboards_v2/frontend/grid/TileGrid.tsx +++ b/products/dashboards_v2/frontend/grid/TileGrid.tsx @@ -148,7 +148,6 @@ export function TileGrid({ }) }, []) - // A tile carried in from another grid. Only the grid under the pointer gets a value. const incoming: DropTarget | null = dropTarget?.grid === gridId ? dropTarget : null const shownTiles = useMemo(() => { const carried = incoming && findCarried(incoming.tileId) diff --git a/products/dashboards_v2/frontend/grid/gridCompactor.ts b/products/dashboards_v2/frontend/grid/gridCompactor.ts index bd104ae81352c..bf1acf219dffb 100644 --- a/products/dashboards_v2/frontend/grid/gridCompactor.ts +++ b/products/dashboards_v2/frontend/grid/gridCompactor.ts @@ -7,13 +7,11 @@ import { type Gesture, type PlacedItem, bottomOf, placeTiles } from './placeTile * so these are read through functions that return the grid's current values, not captured once. */ export interface GridCompactorState { - /** The drag or resize running in this grid, or null. */ gesture: () => Gesture | null /** Whether the dragged tile is over another grid, which this grid then closes up behind. */ tileAway: () => boolean /** Heights of sections that are growing during the gesture, by tile id. */ liveRows: () => Record - /** Called with how many rows the grid needs during a gesture. */ onRows: (rows: number) => void /** Called with the place the dragged tile will land, to move the landing outline there. */ onLanding: (place: PlacedItem | undefined) => void diff --git a/products/dashboards_v2/frontend/grid/tileMounting.ts b/products/dashboards_v2/frontend/grid/tileMounting.ts index 0fcfac991d7aa..b7599c153cd98 100644 --- a/products/dashboards_v2/frontend/grid/tileMounting.ts +++ b/products/dashboards_v2/frontend/grid/tileMounting.ts @@ -88,7 +88,6 @@ export function createTileMountScheduler(): TileMountScheduler { const onScroll = (): void => { if (!scrolling) { scrolling = true - // Swap a pending idle callback for a frame callback. idle?.cancel() idle = null schedule() @@ -156,7 +155,6 @@ export const TileMountContext = createContext(null) /** The tile being captured as an image. It and everything inside it mount, whatever the scheduler says. */ export const CapturingTileContext = createContext(null) -/** Whether the tile around `ref` should mount its content now. */ export function useTileMounted(ref: RefObject): boolean { const scheduler = useContext(TileMountContext) const [mounted, setMounted] = useState(scheduler === null) diff --git a/products/dashboards_v2/frontend/tiles/ContentTile.tsx b/products/dashboards_v2/frontend/tiles/ContentTile.tsx index 902b8fde09490..f32da0df48434 100644 --- a/products/dashboards_v2/frontend/tiles/ContentTile.tsx +++ b/products/dashboards_v2/frontend/tiles/ContentTile.tsx @@ -5,7 +5,6 @@ import { useDashboardV2 } from '../dashboard/dashboardV2Context' import { useContentTileActions } from './TileContextMenu' import { WidgetCard } from './WidgetCard' -/** A widget card inside a dashboard, with the actions the dashboard allows on it. */ export function ContentTile({ id, widget, diff --git a/products/dashboards_v2/frontend/tiles/DashboardTileGrid.css b/products/dashboards_v2/frontend/tiles/DashboardTileGrid.css index cb322dff62735..e04cfc0660320 100644 --- a/products/dashboards_v2/frontend/tiles/DashboardTileGrid.css +++ b/products/dashboards_v2/frontend/tiles/DashboardTileGrid.css @@ -5,7 +5,6 @@ pointer-events: none; } -/* Holds a tile's place until its card mounts. */ .DashboardTileGrid__placeholder { width: 100%; height: 100%; diff --git a/products/dashboards_v2/frontend/tiles/DashboardTileGrid.tsx b/products/dashboards_v2/frontend/tiles/DashboardTileGrid.tsx index 37e9f0e3502a3..b678e1fafdb54 100644 --- a/products/dashboards_v2/frontend/tiles/DashboardTileGrid.tsx +++ b/products/dashboards_v2/frontend/tiles/DashboardTileGrid.tsx @@ -62,7 +62,6 @@ function renderSectionGrid(props: SectionGridProps): JSX.Element { return } -/** A grid of the dashboard's tiles, wired to the dashboard it sits in. */ export function DashboardTileGrid({ gridId, tiles, diff --git a/products/dashboards_v2/frontend/tiles/SectionTile.tsx b/products/dashboards_v2/frontend/tiles/SectionTile.tsx index 0d3546b5ab791..2ab226e1900f2 100644 --- a/products/dashboards_v2/frontend/tiles/SectionTile.tsx +++ b/products/dashboards_v2/frontend/tiles/SectionTile.tsx @@ -210,7 +210,6 @@ export function SectionCount({ count }: { count: number }): JSX.Element { return {count} } -/** Pushed to the end of the header, and shown only while the header is hovered or focused. */ export function SectionActions({ children }: { children: ReactNode }): JSX.Element { return {children} } diff --git a/products/dashboards_v2/frontend/tiles/TileContextMenu.tsx b/products/dashboards_v2/frontend/tiles/TileContextMenu.tsx index 359edf7af2216..4fc85214311ec 100644 --- a/products/dashboards_v2/frontend/tiles/TileContextMenu.tsx +++ b/products/dashboards_v2/frontend/tiles/TileContextMenu.tsx @@ -47,7 +47,6 @@ function isUsable(action: MenuAction): boolean { return action.submenu ? action.submenu.some(isUsable) : true } -/** Whether `TileContextMenu` opens a menu for these actions. */ export function hasTileMenu(actions: MenuAction[]): boolean { return actions.some(isUsable) } diff --git a/products/dashboards_v2/frontend/tiles/WidgetCard.tsx b/products/dashboards_v2/frontend/tiles/WidgetCard.tsx index d81e4db822f6f..bec955eae8144 100644 --- a/products/dashboards_v2/frontend/tiles/WidgetCard.tsx +++ b/products/dashboards_v2/frontend/tiles/WidgetCard.tsx @@ -72,7 +72,6 @@ export function WidgetCard({ widgets: WidgetDefinition[] /** What a person can do to the tile, shown on right-click. Left out, the card has no menu. */ actions?: MenuAction[] - /** Marks where the card is dragged by. */ editable?: boolean /** Lets a widget that edits in place, such as text, save its config. Left out, the widget is read-only. */ setConfig?: (config: unknown) => void diff --git a/products/dashboards_v2/frontend/widgets/chart/vizTypes.ts b/products/dashboards_v2/frontend/widgets/chart/vizTypes.ts index b816fa3a054c8..ced67bf03620a 100644 --- a/products/dashboards_v2/frontend/widgets/chart/vizTypes.ts +++ b/products/dashboards_v2/frontend/widgets/chart/vizTypes.ts @@ -44,7 +44,6 @@ export type RunQuery = (request: QueryRequest) => Promise export interface VizSpec { /** Matches `config.viz.type` on the charts it draws. */ type: string - /** The name the add menu shows. */ label: string size: WidgetSize /** The shape of `config.viz.options`. Missing options are `{}`. */ diff --git a/products/dashboards_v2/frontend/widgets/widgetDefinition.ts b/products/dashboards_v2/frontend/widgets/widgetDefinition.ts index 5e15808aa57b7..3d8511e30fd91 100644 --- a/products/dashboards_v2/frontend/widgets/widgetDefinition.ts +++ b/products/dashboards_v2/frontend/widgets/widgetDefinition.ts @@ -32,7 +32,6 @@ export interface WidgetMenuContext { widget: ContentWidget /** Saves a new config for this widget, as one undo step. */ setConfig: (config: Config) => void - /** Why the person cannot change this widget's config, or null when they can. */ disabledReason: string | null } diff --git a/products/dashboards_v2/frontend/widgets/widgetSpec.ts b/products/dashboards_v2/frontend/widgets/widgetSpec.ts index 2cb1e69786a6f..567685c3043ba 100644 --- a/products/dashboards_v2/frontend/widgets/widgetSpec.ts +++ b/products/dashboards_v2/frontend/widgets/widgetSpec.ts @@ -5,7 +5,6 @@ import type { ContentWidget, SizeOf, WidgetSize } from '../dashboard/dashboardTy /** One entry in the add menu. A widget type can offer several, such as a chart type offering each kind of chart. */ export interface AddMenuItem { label: string - /** Builds the new widget the add menu inserts. */ create: () => ContentWidget } From 83d9fd7ad51996cbc086a0e1bf3584d6412f15cc Mon Sep 17 00:00:00 2001 From: Matt Pua Date: Wed, 25 Nov 2026 16:27:09 -0500 Subject: [PATCH 02/10] refactor(dashboards): simplify v2 naming, access, filters and agent docs Co-Authored-By: Claude Opus 5.5 --- frontend/src/productScenes.tsx | 2 +- products/dashboards_v2/.agents/performance.md | 63 +++ products/dashboards_v2/.agents/primitives.md | 12 + products/dashboards_v2/AGENTS.md | 21 + products/dashboards_v2/CLAUDE.md | 1 + .../frontend/access/dashboardV2Access.ts | 46 --- ...oardV2Actions.tsx => DashboardActions.tsx} | 8 +- ...{DashboardV2Tabs.css => DashboardTabs.css} | 16 +- ...{DashboardV2Tabs.tsx => DashboardTabs.tsx} | 14 +- ...s.tsx => DashboardUnavailable.stories.tsx} | 16 +- ...available.tsx => DashboardUnavailable.tsx} | 14 +- ...{DashboardV2View.css => DashboardView.css} | 4 +- ...{DashboardV2View.tsx => DashboardView.tsx} | 162 ++++---- ...hboardV2Context.ts => dashboardContext.ts} | 24 +- .../frontend/dashboard/dashboardImage.ts | 2 +- .../frontend/dashboard/dashboardTypes.ts | 3 +- .../frontend/dashboard/useDashboardActions.ts | 6 +- .../frontend/dashboard/useDashboardRefresh.ts | 2 +- .../frontend/dashboardV2Logic.test.ts | 24 -- .../frontend/dashboardV2Logic.ts | 385 ------------------ .../frontend/filters/FilterBar.tsx | 123 ++++-- .../dashboards_v2/frontend/filters/FitRow.tsx | 86 ---- .../frontend/filters/filtersContext.ts | 15 +- .../frontend/filters/fitCount.test.ts | 21 - .../frontend/filters/fitCount.ts | 19 - .../{ => filters}/time/TimeRangePicker.tsx | 2 +- .../{ => filters}/time/timeRanges.test.ts | 2 +- .../frontend/{ => filters}/time/timeRanges.ts | 4 +- .../time/useTimeRangeController.ts | 4 +- .../frontend/filters/useDashboardFilters.ts | 4 +- .../frontend/fixtures/kitchenSinkDashboard.ts | 3 + .../frontend/fixtures/runSampleQuery.ts | 3 + .../DashboardScene.tsx} | 36 +- .../frontend/scene/dashboardSceneLogic.ts | 163 ++++++++ .../frontend/tiles/AddTileMenu.tsx | 4 +- .../frontend/tiles/ContentTile.tsx | 4 +- .../frontend/tiles/DashboardTileGrid.tsx | 4 +- .../frontend/tiles/PresentedTile.tsx | 4 +- .../frontend/tiles/SectionTile.tsx | 4 +- .../frontend/tiles/TileContextMenu.tsx | 8 +- .../frontend/widgets/chart/ChartWidget.tsx | 4 +- .../frontend/widgets/timeRangeContext.ts | 11 - products/dashboards_v2/manifest.tsx | 2 +- 43 files changed, 547 insertions(+), 808 deletions(-) create mode 100644 products/dashboards_v2/.agents/performance.md create mode 100644 products/dashboards_v2/.agents/primitives.md create mode 100644 products/dashboards_v2/AGENTS.md create mode 120000 products/dashboards_v2/CLAUDE.md delete mode 100644 products/dashboards_v2/frontend/access/dashboardV2Access.ts rename products/dashboards_v2/frontend/dashboard/{DashboardV2Actions.tsx => DashboardActions.tsx} (84%) rename products/dashboards_v2/frontend/dashboard/{DashboardV2Tabs.css => DashboardTabs.css} (83%) rename products/dashboards_v2/frontend/dashboard/{DashboardV2Tabs.tsx => DashboardTabs.tsx} (96%) rename products/dashboards_v2/frontend/dashboard/{DashboardV2Unavailable.stories.tsx => DashboardUnavailable.stories.tsx} (70%) rename products/dashboards_v2/frontend/dashboard/{DashboardV2Unavailable.tsx => DashboardUnavailable.tsx} (81%) rename products/dashboards_v2/frontend/dashboard/{DashboardV2View.css => DashboardView.css} (78%) rename products/dashboards_v2/frontend/dashboard/{DashboardV2View.tsx => DashboardView.tsx} (63%) rename products/dashboards_v2/frontend/dashboard/{dashboardV2Context.ts => dashboardContext.ts} (81%) delete mode 100644 products/dashboards_v2/frontend/dashboardV2Logic.test.ts delete mode 100644 products/dashboards_v2/frontend/dashboardV2Logic.ts delete mode 100644 products/dashboards_v2/frontend/filters/FitRow.tsx delete mode 100644 products/dashboards_v2/frontend/filters/fitCount.test.ts delete mode 100644 products/dashboards_v2/frontend/filters/fitCount.ts rename products/dashboards_v2/frontend/{ => filters}/time/TimeRangePicker.tsx (96%) rename products/dashboards_v2/frontend/{ => filters}/time/timeRanges.test.ts (97%) rename products/dashboards_v2/frontend/{ => filters}/time/timeRanges.ts (96%) rename products/dashboards_v2/frontend/{ => filters}/time/useTimeRangeController.ts (87%) rename products/dashboards_v2/frontend/{DashboardV2Scene.tsx => scene/DashboardScene.tsx} (79%) create mode 100644 products/dashboards_v2/frontend/scene/dashboardSceneLogic.ts delete mode 100644 products/dashboards_v2/frontend/widgets/timeRangeContext.ts diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsx index 7ee36b7e1cd25..c844b6e7efdaa 100644 --- a/frontend/src/productScenes.tsx +++ b/frontend/src/productScenes.tsx @@ -92,7 +92,7 @@ export const productScenes: Record Promise> = { 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'), diff --git a/products/dashboards_v2/.agents/performance.md b/products/dashboards_v2/.agents/performance.md new file mode 100644 index 0000000000000..3e7239b8f2f4e --- /dev/null +++ b/products/dashboards_v2/.agents/performance.md @@ -0,0 +1,63 @@ +# 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. + +## 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. + +## 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`, `RefreshContext`) 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. + +## 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. + +## 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. + +## 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. + +## 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. + +[`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. diff --git a/products/dashboards_v2/.agents/primitives.md b/products/dashboards_v2/.agents/primitives.md new file mode 100644 index 0000000000000..f64084b99ca73 --- /dev/null +++ b/products/dashboards_v2/.agents/primitives.md @@ -0,0 +1,12 @@ +# 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. + +## 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/`. +- 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. diff --git a/products/dashboards_v2/AGENTS.md b/products/dashboards_v2/AGENTS.md new file mode 100644 index 0000000000000..2c893bfc5938a --- /dev/null +++ b/products/dashboards_v2/AGENTS.md @@ -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 `dashboard-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): `, 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/`. diff --git a/products/dashboards_v2/CLAUDE.md b/products/dashboards_v2/CLAUDE.md new file mode 120000 index 0000000000000..47dc3e3d863cf --- /dev/null +++ b/products/dashboards_v2/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/products/dashboards_v2/frontend/access/dashboardV2Access.ts b/products/dashboards_v2/frontend/access/dashboardV2Access.ts deleted file mode 100644 index 3bd720719d922..0000000000000 --- a/products/dashboards_v2/frontend/access/dashboardV2Access.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils' - -import { AccessControlLevel, AccessControlResourceType } from '~/types' - -import type { DashboardEdit } from '../dashboard/dashboardEdits' - -/** - * Everything a person can do to a v2 dashboard, and the access level it needs. Each edit kind must appear here, so a - * new edit does not type-check until someone decides who may make it. - */ -export type DashboardV2Action = DashboardEdit['edit'] | 'undo' | 'redo' - -export const DASHBOARD_V2_REQUIRED_LEVEL: Record = { - placeTiles: AccessControlLevel.Editor, - moveTile: AccessControlLevel.Editor, - addTile: AccessControlLevel.Editor, - removeTile: AccessControlLevel.Editor, - addToGrid: AccessControlLevel.Editor, - autoLayout: AccessControlLevel.Editor, - updateSection: AccessControlLevel.Editor, - setTilesParts: AccessControlLevel.Editor, - setTilesAppearance: AccessControlLevel.Editor, - setWidgetConfig: AccessControlLevel.Editor, - addTab: AccessControlLevel.Editor, - renameTab: AccessControlLevel.Editor, - removeTab: AccessControlLevel.Editor, - moveTab: AccessControlLevel.Editor, - setAllowFilters: AccessControlLevel.Editor, - addFilter: AccessControlLevel.Editor, - removeFilter: AccessControlLevel.Editor, - undo: AccessControlLevel.Editor, - redo: AccessControlLevel.Editor, -} - -/** Without a dashboard-level `userAccessLevel`, this falls back to the project-wide dashboard level. */ -export function dashboardV2DisabledReason( - action: DashboardV2Action, - userAccessLevel: AccessControlLevel | undefined -): string | null { - return getAccessControlDisabledReason( - AccessControlResourceType.Dashboard, - DASHBOARD_V2_REQUIRED_LEVEL[action], - userAccessLevel, - false - ) -} diff --git a/products/dashboards_v2/frontend/dashboard/DashboardV2Actions.tsx b/products/dashboards_v2/frontend/dashboard/DashboardActions.tsx similarity index 84% rename from products/dashboards_v2/frontend/dashboard/DashboardV2Actions.tsx rename to products/dashboards_v2/frontend/dashboard/DashboardActions.tsx index d7f3e20dfa370..7a75836b98951 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardV2Actions.tsx +++ b/products/dashboards_v2/frontend/dashboard/DashboardActions.tsx @@ -3,14 +3,14 @@ import { Button } from '@posthog/quill' import { AddTileMenu } from '../tiles/AddTileMenu' import { AutoRefreshButton } from './AutoRefreshButton' +import { useDashboard } from './dashboardContext' import { DashboardMenu } from './DashboardMenu' -import { useDashboardV2 } from './dashboardV2Context' -export function DashboardV2Actions(): JSX.Element { - const { history, refresh, can, activeTab } = useDashboardV2() +export function DashboardActions(): JSX.Element { + const { history, refresh, can, activeTab } = useDashboard() return ( -
+
{can('addTile') && } {refresh && } {history && can('undo') && ( diff --git a/products/dashboards_v2/frontend/dashboard/DashboardV2Tabs.css b/products/dashboards_v2/frontend/dashboard/DashboardTabs.css similarity index 83% rename from products/dashboards_v2/frontend/dashboard/DashboardV2Tabs.css rename to products/dashboards_v2/frontend/dashboard/DashboardTabs.css index 0c981f5470dc9..e6384169fb7c9 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardV2Tabs.css +++ b/products/dashboards_v2/frontend/dashboard/DashboardTabs.css @@ -10,7 +10,7 @@ initial-value: 0; } -@keyframes DashboardV2Tabs__fade { +@keyframes DashboardTabs__fade { 0% { --dv2-fade-start: 0; --dv2-fade-end: var(--dv2-fade-size); @@ -29,8 +29,8 @@ } /* A bar on the side a dragged tab will land, drawn outside the trigger so quill's own styles leave it alone. */ -.DashboardV2Tabs__tab--insert-before, -.DashboardV2Tabs__tab--insert-after { +.DashboardTabs__tab--insert-before, +.DashboardTabs__tab--insert-after { position: relative; &::after { @@ -44,15 +44,15 @@ } } -.DashboardV2Tabs__tab--insert-before::after { +.DashboardTabs__tab--insert-before::after { left: -1px; } -.DashboardV2Tabs__tab--insert-after::after { +.DashboardTabs__tab--insert-after::after { right: -1px; } -.DashboardV2Tabs__tab--drop-target { +.DashboardTabs__tab--drop-target { border-radius: var(--radius); outline: 2px solid var(--dv2-interaction-color); outline-offset: 2px; @@ -60,7 +60,7 @@ /* Tabs that don't fit scroll sideways with no scrollbar, and fade out on whichever side has more to scroll to. The fade follows the scroll position, so it needs no script; a browser without scroll timelines shows no fade. */ -.DashboardV2Tabs__scroller { +.DashboardTabs__scroller { --dv2-fade-size: 24px; @supports (animation-timeline: scroll()) { @@ -71,7 +71,7 @@ #000 calc(100% - var(--dv2-fade-end)), transparent ); - animation: DashboardV2Tabs__fade linear both; + animation: DashboardTabs__fade linear both; animation-timeline: scroll(self inline); } } diff --git a/products/dashboards_v2/frontend/dashboard/DashboardV2Tabs.tsx b/products/dashboards_v2/frontend/dashboard/DashboardTabs.tsx similarity index 96% rename from products/dashboards_v2/frontend/dashboard/DashboardV2Tabs.tsx rename to products/dashboards_v2/frontend/dashboard/DashboardTabs.tsx index 568d179a31c49..0e31f090f97f7 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardV2Tabs.tsx +++ b/products/dashboards_v2/frontend/dashboard/DashboardTabs.tsx @@ -1,4 +1,4 @@ -import './DashboardV2Tabs.css' +import './DashboardTabs.css' import clsx from 'clsx' import { useEffect, useState } from 'react' @@ -19,8 +19,8 @@ import { import { hasDangerousScheme } from 'lib/utils/url' import { useGridDrag } from '../grid/gridDrag' +import { useDashboard } from './dashboardContext' import { type DashboardTab, isGridTab } from './dashboardTypes' -import { useDashboardV2 } from './dashboardV2Context' interface TabDraft { id: string @@ -32,8 +32,8 @@ interface TabInsert { side: 'before' | 'after' } -export function DashboardV2Tabs(): JSX.Element | null { - const { dashboard, activeTab, disabledReasonFor, can, onActiveTabChange, onEdit } = useDashboardV2() +export function DashboardTabs(): JSX.Element | null { + const { dashboard, activeTab, disabledReasonFor, can, onActiveTabChange, onEdit } = useDashboard() const { dropTarget } = useGridDrag() const [draft, setDraft] = useState(null) const [draggedId, setDraggedId] = useState(null) @@ -103,7 +103,7 @@ export function DashboardV2Tabs(): JSX.Element | null {
onActiveTabChange(String(value))} > @@ -138,7 +138,7 @@ export function DashboardV2Tabs(): JSX.Element | null { } const isDropTarget = dropTarget?.grid === tab.id && tab.id !== activeTab.id const insertClass = - insert?.id === tab.id ? `DashboardV2Tabs__tab--insert-${insert.side}` : undefined + insert?.id === tab.id ? `DashboardTabs__tab--insert-${insert.side}` : undefined const moves = [ { key: 'left', @@ -211,7 +211,7 @@ export function DashboardV2Tabs(): JSX.Element | null { key={tab.id} value={tab.id} data-dv2-tab={tab.id === activeTab.id ? undefined : tab.id} - className={isDropTarget ? 'DashboardV2Tabs__tab--drop-target' : insertClass} + className={isDropTarget ? 'DashboardTabs__tab--drop-target' : insertClass} onClick={(event) => event.currentTarget.scrollIntoView({ block: 'nearest', inline: 'nearest' }) } diff --git a/products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.stories.tsx b/products/dashboards_v2/frontend/dashboard/DashboardUnavailable.stories.tsx similarity index 70% rename from products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.stories.tsx rename to products/dashboards_v2/frontend/dashboard/DashboardUnavailable.stories.tsx index dd419df15b28b..34a2be0f67147 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.stories.tsx +++ b/products/dashboards_v2/frontend/dashboard/DashboardUnavailable.stories.tsx @@ -5,23 +5,23 @@ import { Button } from '@posthog/quill' import { pngHoggie } from 'lib/brand/hoggies' -import { DashboardV2Unavailable } from './DashboardV2Unavailable' +import { DashboardUnavailable } from './DashboardUnavailable' const HedgehogRocket = pngHoggie(rocket) -const meta: Meta = { - title: 'Products/Dashboards v2/DashboardV2Unavailable', - component: DashboardV2Unavailable, +const meta: Meta = { + title: 'Products/Dashboards v2/DashboardUnavailable', + component: DashboardUnavailable, parameters: { testOptions: { snapshotBrowsers: [] } }, } export default meta -export const Defaults: StoryObj = { +export const Defaults: StoryObj = { render: () => (
{(['notFound', 'noAccess'] as const).map((problem) => (
- +
))}
@@ -29,10 +29,10 @@ export const Defaults: StoryObj = { } /** A product that replaces the words and hedgehog, and adds its own next step. */ -export const Customized: StoryObj = { +export const Customized: StoryObj = { render: () => (
- } title="This service dashboard is private" diff --git a/products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.tsx b/products/dashboards_v2/frontend/dashboard/DashboardUnavailable.tsx similarity index 81% rename from products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.tsx rename to products/dashboards_v2/frontend/dashboard/DashboardUnavailable.tsx index cc736492a89ef..02703fc93572b 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardV2Unavailable.tsx +++ b/products/dashboards_v2/frontend/dashboard/DashboardUnavailable.tsx @@ -10,7 +10,7 @@ import { pngHoggie } from 'lib/brand/hoggies' const HedgehogSearching = pngHoggie(magnifyingGlass) const HedgehogDenied = pngHoggie(stampDenied) -export type DashboardV2Problem = 'notFound' | 'noAccess' +export type UnavailableReason = 'notFound' | 'noAccess' interface ProblemView { illustration: ReactNode @@ -18,7 +18,7 @@ interface ProblemView { description: ReactNode } -const DEFAULT_VIEWS: Record = { +const DEFAULT_VIEWS: Record = { notFound: { illustration: , title: 'Dashboard not found', @@ -31,25 +31,25 @@ const DEFAULT_VIEWS: Record = { }, } -export interface DashboardV2UnavailableProps extends Partial { - problem: DashboardV2Problem +export interface DashboardUnavailableProps extends Partial { + problem: UnavailableReason /** Buttons or links for the next step, such as going back to a list. The default view has none. */ actions?: ReactNode className?: string } /** - * What a host renders in place of `DashboardV2View` when the dashboard can't load. Each slot replaces the default for + * What a host renders in place of `DashboardView` when the dashboard can't load. Each slot replaces the default for * that problem, so a product can change only the words, or add its own next step. */ -export function DashboardV2Unavailable({ +export function DashboardUnavailable({ problem, illustration, title, description, actions, className, -}: DashboardV2UnavailableProps): JSX.Element { +}: DashboardUnavailableProps): JSX.Element { const defaults = DEFAULT_VIEWS[problem] return ( diff --git a/products/dashboards_v2/frontend/dashboard/DashboardV2View.css b/products/dashboards_v2/frontend/dashboard/DashboardView.css similarity index 78% rename from products/dashboards_v2/frontend/dashboard/DashboardV2View.css rename to products/dashboards_v2/frontend/dashboard/DashboardView.css index f4aa2ab7c1f95..733f6cd513331 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardV2View.css +++ b/products/dashboards_v2/frontend/dashboard/DashboardView.css @@ -2,13 +2,13 @@ --dv2-interaction-color: var(--color-blue-500); } -.DashboardV2View__canvas { +.DashboardView__canvas { min-width: 0; /* Room below the last row, so a tile can be dragged under everything. */ padding-bottom: 30vh; - .DashboardV2View--capturing & { + .DashboardView--capturing & { padding-bottom: 0; } } diff --git a/products/dashboards_v2/frontend/dashboard/DashboardV2View.tsx b/products/dashboards_v2/frontend/dashboard/DashboardView.tsx similarity index 63% rename from products/dashboards_v2/frontend/dashboard/DashboardV2View.tsx rename to products/dashboards_v2/frontend/dashboard/DashboardView.tsx index 6630596e2847e..f8a3fb4089e7e 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardV2View.tsx +++ b/products/dashboards_v2/frontend/dashboard/DashboardView.tsx @@ -1,4 +1,4 @@ -import './DashboardV2View.css' +import './DashboardView.css' import clsx from 'clsx' import { type ReactNode, type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react' @@ -8,32 +8,35 @@ import { useContainerWidth } from 'react-grid-layout' // oxlint-disable-next-line no-restricted-imports import { lemonToast } from 'lib/lemon-ui/LemonToast' -import type { DashboardV2Action } from '../access/dashboardV2Access' import { FilterBar } from '../filters/FilterBar' -import { FiltersContext, appliedFilters } from '../filters/filtersContext' +import { type ActiveFilters, DEFAULT_TIME_RANGE, FiltersContext, appliedFilters } from '../filters/filtersContext' +import { TimeRangePicker } from '../filters/time/TimeRangePicker' import type { DropTarget } from '../grid/dropTargets' import { GridDragContext, type GridDragState } from '../grid/gridDrag' import { stackTiles } from '../grid/gridTiles' import { CapturingTileContext, TileMountContext, createTileMountScheduler } from '../grid/tileMounting' import { DashboardTileGrid } from '../tiles/DashboardTileGrid' import { PresentedTile } from '../tiles/PresentedTile' -import { TimeRangePicker } from '../time/TimeRangePicker' import { RefreshContext } from '../widgets/refreshContext' -import { DEFAULT_TIME_RANGE, TimeRangeContext } from '../widgets/timeRangeContext' import { sizeOfWidgets } from '../widgets/widgetSpec' +import { + type DashboardAction, + type DashboardController, + type DashboardState, + DashboardStateContext, +} from './dashboardContext' import { withFolds } from './dashboardEdits' import { type ImageFormat, downloadDashboardImage } from './dashboardImage' +import { DashboardTabs } from './DashboardTabs' import { type Dashboard, GRID, activeGridTab, gridTabs } from './dashboardTypes' -import { type DashboardV2Controller, type DashboardV2State, DashboardV2StateContext } from './dashboardV2Context' -import { DashboardV2Tabs } from './DashboardV2Tabs' import { findTile } from './tileTree' import { useDashboardRefresh } from './useDashboardRefresh' // A stacked column is not the saved layout, so only dragging and resizing tiles in it is blocked. const STACKED_REASON = 'Open this dashboard on a wider screen to arrange tiles' -export interface DashboardV2ViewProps { - controller: DashboardV2Controller +export interface DashboardViewProps { + controller: DashboardController /** Rendered above the tabs, inside the dashboard, so it can use the dashboard's own controls. */ header?: ReactNode } @@ -79,7 +82,7 @@ function imageWords( } /** A whole dashboard: tabs and grid. Its own state is only what the screen and a drag in progress decide. */ -export function DashboardV2View({ controller, header }: DashboardV2ViewProps): JSX.Element { +export function DashboardView({ controller, header }: DashboardViewProps): JSX.Element { const { width, containerRef, mounted } = useContainerWidth() const stacked = width > 0 && width < GRID.stackBelowPx const [dropTarget, setDropTarget] = useState(null) @@ -120,9 +123,9 @@ export function DashboardV2View({ controller, header }: DashboardV2ViewProps): J [controller] ) - const state = useMemo(() => { + const state = useMemo(() => { const { activeTabId, disabledReasonFor: hostReason, onEdit: hostOnEdit, ...rest } = controller - const disabledReasonFor = (action: DashboardV2Action): string | null => + const disabledReasonFor = (action: DashboardAction): string | null => hostReason(action) ?? (stacked && action === 'placeTiles' ? STACKED_REASON : null) const view = (dashboard: Dashboard): Dashboard => withFolds(dashboard, folds, sizeOf) const dashboard = view(rest.dashboard) @@ -166,6 +169,7 @@ export function DashboardV2View({ controller, header }: DashboardV2ViewProps): J [filtersOn, savedFilters, filterValues] ) const time = controller.timeRange?.value ?? controller.dashboard.time ?? DEFAULT_TIME_RANGE + const activeFilters = useMemo(() => ({ time, filters: applied }), [time, applied]) const tiles = useMemo( () => (stacked ? stackTiles(activeTab.tiles, GRID.columns, sizeOf) : activeTab.tiles), [stacked, activeTab.tiles, sizeOf] @@ -195,80 +199,78 @@ export function DashboardV2View({ controller, header }: DashboardV2ViewProps): J }, [undoable, can]) return ( - + - - - - - -
- {header} - {(filtersOn || controller.timeRange) && ( -
- {controller.timeRange && ( - + + + +
+ {header} + {(filtersOn || controller.timeRange) && ( +
+ {controller.timeRange && ( + + )} +
+ {filtersOn && controller.filters && ( + + state.onEdit({ edit: 'addFilter', filter }) + : undefined + } + onRemove={ + can('removeFilter') + ? (id) => state.onEdit({ edit: 'removeFilter', id }) + : undefined + } /> )} -
- {filtersOn && controller.filters && ( - - state.onEdit({ edit: 'addFilter', filter }) - : undefined - } - onRemove={ - can('removeFilter') - ? (id) => state.onEdit({ edit: 'removeFilter', id }) - : undefined - } - /> - )} -
- )} - - -
} - className="DashboardV2View__canvas" - > - {mounted && width > 0 && ( - - )}
+ )} + + +
} + className="DashboardView__canvas" + > + {mounted && width > 0 && ( + + )}
- - - - - - +
+ + + + + - + ) } diff --git a/products/dashboards_v2/frontend/dashboard/dashboardV2Context.ts b/products/dashboards_v2/frontend/dashboard/dashboardContext.ts similarity index 81% rename from products/dashboards_v2/frontend/dashboard/dashboardV2Context.ts rename to products/dashboards_v2/frontend/dashboard/dashboardContext.ts index ca850f8d02272..89c54bf1af519 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardV2Context.ts +++ b/products/dashboards_v2/frontend/dashboard/dashboardContext.ts @@ -1,8 +1,7 @@ import { createContext, useContext } from 'react' -import type { DashboardV2Action } from '../access/dashboardV2Access' +import type { TimeRangeController } from '../filters/time/useTimeRangeController' import type { FiltersController } from '../filters/useFiltersController' -import type { TimeRangeController } from '../time/useTimeRangeController' import type { WidgetDefinition } from '../widgets/widgetDefinition' import type { AutoRefreshProps } from './AutoRefreshButton' import type { DashboardEdit, View } from './dashboardEdits' @@ -10,18 +9,21 @@ import type { ImageFormat } from './dashboardImage' import type { Dashboard, GridTab, SizeOf, Widget } from './dashboardTypes' import type { MenuAction } from './menuAction' +/** Everything a person can do to a dashboard. A host's `disabledReasonFor` can give each one its own answer. */ +export type DashboardAction = DashboardEdit['edit'] | 'undo' | 'redo' + /** - * What a host passes to `DashboardV2View`. The host owns the state and the rules behind it (history, access, saving, + * What a host passes to `DashboardView`. The host owns the state and the rules behind it (history, access, saving, * the URL), so the components render the same on any page that embeds them. */ -export interface DashboardV2Controller { +export interface DashboardController { /** The saved dashboard. The view folds closed sections itself. */ dashboard: Dashboard /** Unknown or unset shows the first tab. */ activeTabId: string | null /** The widget types this dashboard can show and add. Keep the array stable between renders, or every tile re-renders. */ widgets: WidgetDefinition[] - disabledReasonFor: (action: DashboardV2Action) => string | null + disabledReasonFor: (action: DashboardAction) => string | null /** * Called with each edit, and with how the person saw the dashboard when they made it. Pass `view` to `applyEdit`, * so a tile lands where the person dropped it in a layout with closed sections. @@ -65,7 +67,7 @@ export interface RefreshController { } /** What the components read: the controller, plus what the view works out from it. */ -export interface DashboardV2State extends Omit { +export interface DashboardState extends Omit { refresh?: AutoRefreshProps /** The dashboard as this person sees it, with the sections they closed folded. */ dashboard: Dashboard @@ -74,7 +76,7 @@ export interface DashboardV2State extends Omit void activeTab: GridTab sizeOf: SizeOf - can: (action: DashboardV2Action) => boolean + can: (action: DashboardAction) => boolean /** Downloads the tab on screen, or with `tileId`, just that tile. */ downloadImage: (format: ImageFormat, tileId?: string) => void downloadingImage: boolean @@ -83,12 +85,12 @@ export interface DashboardV2State extends Omit void } -export const DashboardV2StateContext = createContext(null) +export const DashboardStateContext = createContext(null) -export function useDashboardV2(): DashboardV2State { - const state = useContext(DashboardV2StateContext) +export function useDashboard(): DashboardState { + const state = useContext(DashboardStateContext) if (!state) { - throw new Error('useDashboardV2 must be used inside DashboardV2View') + throw new Error('useDashboard must be used inside DashboardView') } return state } diff --git a/products/dashboards_v2/frontend/dashboard/dashboardImage.ts b/products/dashboards_v2/frontend/dashboard/dashboardImage.ts index 0840658c1537c..a2cc1e55e8225 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardImage.ts +++ b/products/dashboards_v2/frontend/dashboard/dashboardImage.ts @@ -12,7 +12,7 @@ export const IMAGE_FORMATS: { format: ImageFormat; label: string }[] = [ ] const LEFT_OUT = - '.TileHoverReveal, .react-resizable-handle, .TileGrid__drop-preview, .DashboardV2Actions, [data-attr="dashboard-v2-add-tab"]' + '.TileHoverReveal, .react-resizable-handle, .TileGrid__drop-preview, .DashboardActions, [data-attr="dashboard-v2-add-tab"]' const NOT_READY = '.DashboardTileGrid__placeholder, [aria-busy="true"]' const READY_TIMEOUT_MS = 20000 const POLL_MS = 100 diff --git a/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts b/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts index 201a1d43b604c..0037a1104d685 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts +++ b/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts @@ -108,7 +108,8 @@ export function activeGridTab(dashboard: Dashboard, activeTabId: string | null): return tabs.find((tab) => tab.id === activeTabId) ?? tabs[0] } -export type Dashboard = z.infer +// An interface rather than an alias, so kea-typegen writes `Dashboard` instead of every field of it. +export interface Dashboard extends z.infer {} export type DashboardDocument = z.infer diff --git a/products/dashboards_v2/frontend/dashboard/useDashboardActions.ts b/products/dashboards_v2/frontend/dashboard/useDashboardActions.ts index f7a61b6738e3d..4c380017b9347 100644 --- a/products/dashboards_v2/frontend/dashboard/useDashboardActions.ts +++ b/products/dashboards_v2/frontend/dashboard/useDashboardActions.ts @@ -1,15 +1,15 @@ import { useMemo } from 'react' import { showAction } from '../presentation/tileAppearance' +import { useDashboard } from './dashboardContext' import { downloadImageAction } from './dashboardImage' import { gridTabs } from './dashboardTypes' -import { useDashboardV2 } from './dashboardV2Context' import type { MenuAction } from './menuAction' import { everyTile } from './tileTree' /** * The dashboard's own actions, after the host's `dashboardActions`. `DashboardMenu` shows them; a host with its own menu, - * such as a scene's menu bar, can render them there instead. Call it inside `DashboardV2View`, such as in its `header`. + * such as a scene's menu bar, can render them there instead. Call it inside `DashboardView`, such as in its `header`. */ export function useDashboardActions(): MenuAction[] { const { @@ -22,7 +22,7 @@ export function useDashboardActions(): MenuAction[] { downloadingImage, dashboardActions, filters, - } = useDashboardV2() + } = useDashboard() const hasFilterTypes = !!filters && filters.types.length > 0 const allowFilters = !!dashboard.allowFilters // The image shows only the tab on screen, so with several tabs the menu names it. diff --git a/products/dashboards_v2/frontend/dashboard/useDashboardRefresh.ts b/products/dashboards_v2/frontend/dashboard/useDashboardRefresh.ts index 9d6c64ecc6a69..928755c88dc6e 100644 --- a/products/dashboards_v2/frontend/dashboard/useDashboardRefresh.ts +++ b/products/dashboards_v2/frontend/dashboard/useDashboardRefresh.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react' import type { AutoRefreshProps } from './AutoRefreshButton' -import type { RefreshController } from './dashboardV2Context' +import type { RefreshController } from './dashboardContext' /** `count` goes up on every refresh, from the button or the timer, so each chart runs its query again. */ export function useDashboardRefresh(refresh: RefreshController | undefined): { diff --git a/products/dashboards_v2/frontend/dashboardV2Logic.test.ts b/products/dashboards_v2/frontend/dashboardV2Logic.test.ts deleted file mode 100644 index ee8d263522b5c..0000000000000 --- a/products/dashboards_v2/frontend/dashboardV2Logic.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { initKeaTests } from '~/test/init' -import { AccessControlLevel } from '~/types' - -import { dashboardV2Logic } from './dashboardV2Logic' - -describe('dashboardV2Logic access', () => { - it.each([ - [AccessControlLevel.Viewer, 1], - [AccessControlLevel.Editor, 2], - ])('with %s access, adding a tab leaves %i tabs', (level, tabs) => { - initKeaTests() - const logic = dashboardV2Logic() - logic.mount() - logic.actions.commitDashboard({ - ...logic.values.dashboard, - user_access_level: level, - tabs: logic.values.dashboard.tabs.slice(0, 1), - }) - - logic.actions.applyDashboardEdit({ edit: 'addTab', title: 'Another' }) - - expect(logic.values.dashboard.tabs).toHaveLength(tabs) - }) -}) diff --git a/products/dashboards_v2/frontend/dashboardV2Logic.ts b/products/dashboards_v2/frontend/dashboardV2Logic.ts deleted file mode 100644 index 79b3892b3fda4..0000000000000 --- a/products/dashboards_v2/frontend/dashboardV2Logic.ts +++ /dev/null @@ -1,385 +0,0 @@ -import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea' -import { actionToUrl, router, urlToAction } from 'kea-router' - -import type { AccessControlLevel } from '~/types' - -import { type DashboardV2Action, dashboardV2DisabledReason } from './access/dashboardV2Access' -import { type DashboardEdit, type View, applyEdit, settleDashboard } from './dashboard/dashboardEdits' -import { type DashboardHistory, recordEdit, redoEdit, startHistory, undoEdit } from './dashboard/dashboardHistory' -import { type Dashboard, type GridTab, activeGridTab } from './dashboard/dashboardTypes' -import { kitchenSinkDashboard } from './fixtures/kitchenSinkDashboard' -import { DEFAULT_WIDGETS } from './widgets/defaultWidgets' -import { sizeOfWidgets } from './widgets/widgetSpec' - -// The scene passes the same list to the view, so edits here and the grid on screen use the same sizes. -const sizeOf = sizeOfWidgets(DEFAULT_WIDGETS) - -// Generated by kea-typegen. Update if you're an agent, ignore if you're human. -export interface dashboardV2LogicValues { - activeTab: GridTab - activeTabId: string | null - canRedo: boolean - canUndo: boolean - dashboard: Dashboard - disabledReasonFor: (action: DashboardV2Action) => string | null - history: DashboardHistory -} - -// Generated by kea-typegen. Update if you're an agent, ignore if you're human. -export interface dashboardV2LogicActions { - applyDashboardEdit: ( - edit: DashboardEdit, - view?: View - ) => { - edit: DashboardEdit - view: View | undefined - } - commitDashboard: (dashboard: Dashboard) => { - dashboard: { - allowFilters?: boolean | undefined - description?: string | undefined - filters?: - | { - config: unknown - id: string - label?: string | undefined - type: string - }[] - | undefined - tabs: ( - | { - href: string - id: string - title: string - } - | { - id: string - tiles: { - id: string - place: { - h: number - w: number - x: number - y: number - } - widget: - | { - appearance?: - | { - background?: boolean | undefined - backgroundColor?: string | undefined - border?: boolean | undefined - } - | undefined - collapsed?: boolean | undefined - minRows?: number | undefined - tiles: any - title: string - type: 'section' - } - | { - appearance?: - | { - background?: boolean | undefined - backgroundColor?: string | undefined - border?: boolean | undefined - } - | undefined - config: unknown - description?: string | undefined - parts?: - | { - footer?: boolean | undefined - header?: boolean | undefined - } - | undefined - ref?: string | undefined - refreshedAt?: string | undefined - title?: string | undefined - type: string - } - }[] - title: string - } - )[] - time?: - | { - from: string - to: string - } - | undefined - title: string - user_access_level?: AccessControlLevel | undefined - version: 2 - } - } - redo: () => { - value: true - } - setActiveTab: (tabId: string) => { - tabId: string - } - stepHistory: (step: 'back' | 'forward') => { - step: 'back' | 'forward' - } - undo: () => { - value: true - } -} - -// Generated by kea-typegen. Update if you're an agent, ignore if you're human. -export interface dashboardV2LogicMeta { - __keaTypeGenInternalSelectorTypes: { - dashboard: (history: DashboardHistory) => Dashboard - canUndo: (history: DashboardHistory) => boolean - canRedo: (history: DashboardHistory) => boolean - disabledReasonFor: (dashboard: { - allowFilters?: boolean | undefined - description?: string | undefined - filters?: - | { - config: unknown - id: string - label?: string | undefined - type: string - }[] - | undefined - tabs: ( - | { - href: string - id: string - title: string - } - | { - id: string - tiles: { - id: string - place: { - h: number - w: number - x: number - y: number - } - widget: - | { - appearance?: - | { - background?: boolean | undefined - backgroundColor?: string | undefined - border?: boolean | undefined - } - | undefined - collapsed?: boolean | undefined - minRows?: number | undefined - tiles: any - title: string - type: 'section' - } - | { - appearance?: - | { - background?: boolean | undefined - backgroundColor?: string | undefined - border?: boolean | undefined - } - | undefined - config: unknown - description?: string | undefined - parts?: - | { - footer?: boolean | undefined - header?: boolean | undefined - } - | undefined - ref?: string | undefined - refreshedAt?: string | undefined - title?: string | undefined - type: string - } - }[] - title: string - } - )[] - time?: - | { - from: string - to: string - } - | undefined - title: string - user_access_level?: AccessControlLevel | undefined - version: 2 - }) => (action: DashboardV2Action) => string | null - activeTab: ( - dashboard: { - allowFilters?: boolean | undefined - description?: string | undefined - filters?: - | { - config: unknown - id: string - label?: string | undefined - type: string - }[] - | undefined - tabs: ( - | { - href: string - id: string - title: string - } - | { - id: string - tiles: { - id: string - place: { - h: number - w: number - x: number - y: number - } - widget: - | { - appearance?: - | { - background?: boolean | undefined - backgroundColor?: string | undefined - border?: boolean | undefined - } - | undefined - collapsed?: boolean | undefined - minRows?: number | undefined - tiles: any - title: string - type: 'section' - } - | { - appearance?: - | { - background?: boolean | undefined - backgroundColor?: string | undefined - border?: boolean | undefined - } - | undefined - config: unknown - description?: string | undefined - parts?: - | { - footer?: boolean | undefined - header?: boolean | undefined - } - | undefined - ref?: string | undefined - refreshedAt?: string | undefined - title?: string | undefined - type: string - } - }[] - title: string - } - )[] - time?: - | { - from: string - to: string - } - | undefined - title: string - user_access_level?: AccessControlLevel | undefined - version: 2 - }, - activeTabId: string | null - ) => GridTab - } -} - -export type dashboardV2LogicType = MakeLogicType< - dashboardV2LogicValues, - dashboardV2LogicActions, - Record, - dashboardV2LogicMeta -> - -export const dashboardV2Logic = kea([ - path(['products', 'dashboardsV2', 'dashboardV2Logic']), - actions({ - /** The one entry point for edits to the layout. Drags and menus call it, so the permission check lives here only. */ - applyDashboardEdit: (edit: DashboardEdit, view?: View) => ({ edit, view }), - commitDashboard: (dashboard: Dashboard) => ({ dashboard }), - undo: true, - redo: true, - stepHistory: (step: 'back' | 'forward') => ({ step }), - setActiveTab: (tabId: string) => ({ tabId }), - }), - reducers({ - history: [ - // TODO(2026-11-23): Load the dashboard from the API and save edits back to it. - // The kitchen sink fixture is temporary. The scene starts from it on every load, so no edit is saved. - startHistory(settleDashboard(kitchenSinkDashboard, sizeOf)) as DashboardHistory, - { - commitDashboard: (state, { dashboard }) => recordEdit(state, dashboard), - stepHistory: (state, { step }) => (step === 'back' ? undoEdit(state) : redoEdit(state)), - }, - ], - activeTabId: [null as string | null, { setActiveTab: (_, { tabId }) => tabId }], - }), - selectors({ - dashboard: [(s) => [s.history], (history: DashboardHistory): Dashboard => history.present], - canUndo: [(s) => [s.history], (history: DashboardHistory): boolean => history.past.length > 0], - canRedo: [(s) => [s.history], (history: DashboardHistory): boolean => history.future.length > 0], - disabledReasonFor: [ - (s) => [s.dashboard], - (dashboard: Dashboard): ((action: DashboardV2Action) => string | null) => - (action) => - dashboardV2DisabledReason(action, dashboard.user_access_level), - ], - activeTab: [ - (s) => [s.dashboard, s.activeTabId], - (dashboard: Dashboard, activeTabId: string | null): GridTab => activeGridTab(dashboard, activeTabId), - ], - }), - listeners(({ actions, values }) => ({ - applyDashboardEdit: ({ edit, view }) => { - if (values.disabledReasonFor(edit.edit)) { - return - } - const next = applyEdit(values.dashboard, edit, sizeOf, view) - if (recordEdit(values.history, next) === values.history) { - return - } - // With no tab in the URL the first tab shows, so a reorder would switch tabs unless the shown one is pinned. - if (edit.edit === 'moveTab' && values.activeTabId === null) { - actions.setActiveTab(values.activeTab.id) - } - actions.commitDashboard(next) - if (edit.edit === 'addTab') { - actions.setActiveTab(next.tabs[next.tabs.length - 1].id) - } - }, - undo: () => { - if (!values.disabledReasonFor('undo')) { - actions.stepHistory('back') - } - }, - redo: () => { - if (!values.disabledReasonFor('redo')) { - actions.stepHistory('forward') - } - }, - })), - actionToUrl(({ values }) => ({ - setActiveTab: () => [ - router.values.location.pathname, - { ...router.values.searchParams, tab: values.activeTab.id }, - router.values.hashParams, - { replace: true }, - ], - })), - urlToAction(({ actions, values }) => ({ - '*': (_, searchParams) => { - if (searchParams.tab && searchParams.tab !== values.activeTabId) { - actions.setActiveTab(searchParams.tab) - } - }, - })), -]) diff --git a/products/dashboards_v2/frontend/filters/FilterBar.tsx b/products/dashboards_v2/frontend/filters/FilterBar.tsx index dad4f0a1339f7..01582af1bb6a6 100644 --- a/products/dashboards_v2/frontend/filters/FilterBar.tsx +++ b/products/dashboards_v2/frontend/filters/FilterBar.tsx @@ -1,11 +1,13 @@ -import { useLayoutEffect, useMemo, useRef } from 'react' +import { useLayoutEffect, useRef, useState } from 'react' + +import { IconChevronDown, IconFilter } from '@posthog/icons' +import { Button, Popover, PopoverContent, PopoverTrigger, Separator, Text } from '@posthog/quill' import type { DashboardFilter } from '../dashboard/dashboardTypes' import { AddFilterMenu } from './AddFilterMenu' import type { FilterDefinition } from './filterDefinition' import { FilterPill } from './FilterPill' import { activeFirst, filterValue } from './filtersContext' -import { FitRow } from './FitRow' export interface FilterBarProps { filters: DashboardFilter[] @@ -17,8 +19,8 @@ export interface FilterBarProps { } /** - * The default arrangement of the filter pieces: pills with a value first, on one line that overflows into "+N filters", - * after the add filter menu. A page that wants less composes `FilterPill`, `FitRow` and `AddFilterMenu` itself. + * The default arrangement of the filter pieces: one "N filters" button that opens every filter, with the add filter + * menu inside. A page that wants another layout composes `FilterPill` and `AddFilterMenu` itself. */ export function FilterBar({ filters, @@ -28,47 +30,100 @@ export function FilterBar({ onAdd, onRemove, }: FilterBarProps): JSX.Element | null { - // The filter this bar just added mounts with its picker open. Undo or redo bringing a filter back does not. + const [open, setOpen] = useState(false) + // A filter this bar just added stays on the bar with its picker open until it has a value. Undo or redo bringing + // a filter back does not count as added here. + const [pendingId, setPendingId] = useState(null) const addedHere = useRef(false) const knownIds = useRef(new Set(filters.map((filter) => filter.id))) - const justAdded = addedHere.current ? filters.find((filter) => !knownIds.current.has(filter.id))?.id : undefined useLayoutEffect(() => { + if (addedHere.current) { + const added = filters.find((filter) => !knownIds.current.has(filter.id)) + if (added) { + setPendingId(added.id) + } + } knownIds.current = new Set(filters.map((filter) => filter.id)) addedHere.current = false }, [filters]) - const items = useMemo( - () => - activeFirst(filters, values).map((filter) => ({ - id: filter.id, - element: ( - onValueChange(filter.id, value)} - onRemove={onRemove && (() => onRemove(filter.id))} - defaultOpen={filter.id === justAdded} - /> - ), - })), - [filters, types, values, onValueChange, onRemove, justAdded] - ) + + const pending = filters.find((filter) => filter.id === pendingId && filterValue(values, filter.id) === undefined) + const listed = activeFirst(filters, values).filter((filter) => filter !== pending) if (filters.length === 0 && !onAdd) { return null } + + const pill = (filter: DashboardFilter): JSX.Element => ( + onValueChange(filter.id, value)} + onRemove={onRemove && (() => onRemove(filter.id))} + defaultOpen={filter === pending} + /> + ) + const addMenu = onAdd && ( + { + addedHere.current = true + setOpen(false) + onAdd(filter) + }} + /> + ) + + if (listed.length === 0) { + return ( +
+ {pending && pill(pending)} + {addMenu} +
+ ) + } + + const countLabel = listed.length === 1 ? '1 filter' : `${listed.length} filters` + const withValue = listed.filter((filter) => filterValue(values, filter.id) !== undefined) return (
- {onAdd && ( - { - addedHere.current = true - onAdd(filter) - }} - /> - )} - + + } + > + + {countLabel} + + + +
+ }> + Filters + · {countLabel} + + {withValue.length > 0 && ( + + )} +
+
+ {listed.map(pill)} +
+ {addMenu && ( + <> + +
{addMenu}
+ + )} +
+
+ {pending && pill(pending)}
) } diff --git a/products/dashboards_v2/frontend/filters/FitRow.tsx b/products/dashboards_v2/frontend/filters/FitRow.tsx deleted file mode 100644 index b986f1ffd0d2d..0000000000000 --- a/products/dashboards_v2/frontend/filters/FitRow.tsx +++ /dev/null @@ -1,86 +0,0 @@ -import { type ReactNode, useLayoutEffect, useRef, useState } from 'react' - -import { Button, Popover, PopoverContent, PopoverTrigger } from '@posthog/quill' - -import { fitCount } from './fitCount' - -// Before an item has been on screen its width is unknown, so it is counted as about one filter pill wide. -const UNMEASURED_WIDTH_PX = 160 -const MORE_WIDTH_PX = 96 - -export interface FitRowItem { - id: string - element: ReactNode -} - -export function FitRow({ items }: { items: FitRowItem[] }): JSX.Element { - const rowRef = useRef(null) - const elements = useRef(new Map()) - // Kept for items in the popover too, so the row knows whether one would fit back in without showing it first. - const widths = useRef(new Map()) - const [available, setAvailable] = useState(0) - const [shown, setShown] = useState(items.length) - - useLayoutEffect(() => { - const row = rowRef.current - if (!row) { - return - } - const observer = new ResizeObserver(([entry]) => setAvailable(entry.contentRect.width)) - observer.observe(row) - return () => observer.disconnect() - }, []) - - useLayoutEffect(() => { - elements.current.forEach((element, id) => widths.current.set(id, element.offsetWidth)) - const fit = fitCount( - items.map((item) => widths.current.get(item.id) ?? UNMEASURED_WIDTH_PX), - available, - MORE_WIDTH_PX - ) - setShown(available > 0 ? fit : items.length) - // An item's content can change its width, and an item back from the popover is measured once it shows. - }, [items, available, shown]) - - const hidden = items.slice(shown) - return ( -
- {items.slice(0, shown).map((item) => ( -
{ - if (element) { - elements.current.set(item.id, element) - } else { - elements.current.delete(item.id) - } - }} - > - {item.element} -
- ))} - {hidden.length > 0 && ( - - - } - > - +{hidden.length} {hidden.length === 1 ? 'filter' : 'filters'} - - - {hidden.map((item) => ( -
{item.element}
- ))} -
-
- )} -
- ) -} diff --git a/products/dashboards_v2/frontend/filters/filtersContext.ts b/products/dashboards_v2/frontend/filters/filtersContext.ts index dcf422966c003..e175cd9fd0c20 100644 --- a/products/dashboards_v2/frontend/filters/filtersContext.ts +++ b/products/dashboards_v2/frontend/filters/filtersContext.ts @@ -1,6 +1,6 @@ import { createContext } from 'react' -import type { DashboardFilter } from '../dashboard/dashboardTypes' +import type { DashboardFilter, TimeRange } from '../dashboard/dashboardTypes' export interface AppliedFilter { id: string @@ -9,11 +9,18 @@ export interface AppliedFilter { value: Value } +export const DEFAULT_TIME_RANGE: TimeRange = { from: 'now-7d', to: 'now' } + +export interface ActiveFilters { + time: TimeRange + filters: AppliedFilter[] +} + /** - * The filters that apply to the widgets inside it. `DashboardV2View` provides the dashboard's, and a host that renders - * a widget on its own can provide its own, so widgets never read the dashboard to get them. + * The time range and filters that apply to the widgets inside it. `DashboardView` provides the dashboard's, and a host + * that renders a widget on its own can provide its own, so widgets never read the dashboard to get them. */ -export const FiltersContext = createContext([]) +export const FiltersContext = createContext({ time: DEFAULT_TIME_RANGE, filters: [] }) /** A filter's value, read as an own property, so an id such as `constructor` never picks up an inherited one. */ export function filterValue(values: Record, id: string): unknown { diff --git a/products/dashboards_v2/frontend/filters/fitCount.test.ts b/products/dashboards_v2/frontend/filters/fitCount.test.ts deleted file mode 100644 index 28466909c11ea..0000000000000 --- a/products/dashboards_v2/frontend/filters/fitCount.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { fitCount } from './fitCount' - -describe('fitCount', () => { - test.each([ - { name: 'every item when they all fit', widths: [100, 100], available: 208, expected: 2 }, - { - name: 'one fewer when the last fits only without the more button', - widths: [100, 100, 100], - available: 250, - expected: 1, - }, - { - name: 'none when even the first leaves no room for the more button', - widths: [200, 100], - available: 250, - expected: 0, - }, - ])('shows $name', ({ widths, available, expected }) => { - expect(fitCount(widths, available, 80)).toBe(expected) - }) -}) diff --git a/products/dashboards_v2/frontend/filters/fitCount.ts b/products/dashboards_v2/frontend/filters/fitCount.ts deleted file mode 100644 index 5f2712046f5d3..0000000000000 --- a/products/dashboards_v2/frontend/filters/fitCount.ts +++ /dev/null @@ -1,19 +0,0 @@ -// `FitRow`'s `gap-2`. -export const ITEM_GAP_PX = 8 - -/** - * How many items, in order, fit on one line of `available` pixels. When some do not fit, room for the "+N filters" - * button (`moreWidth`) is kept at the end, so the last item that shows may be one fewer than fits on its own. - */ -export function fitCount(widths: number[], available: number, moreWidth: number): number { - let used = 0 - for (let index = 0; index < widths.length; index++) { - const next = used + (index > 0 ? ITEM_GAP_PX : 0) + widths[index] - const reserve = index < widths.length - 1 ? ITEM_GAP_PX + moreWidth : 0 - if (next + reserve > available) { - return index - } - used = next - } - return widths.length -} diff --git a/products/dashboards_v2/frontend/time/TimeRangePicker.tsx b/products/dashboards_v2/frontend/filters/time/TimeRangePicker.tsx similarity index 96% rename from products/dashboards_v2/frontend/time/TimeRangePicker.tsx rename to products/dashboards_v2/frontend/filters/time/TimeRangePicker.tsx index b1dd8717fe497..fe9fc9285eaa4 100644 --- a/products/dashboards_v2/frontend/time/TimeRangePicker.tsx +++ b/products/dashboards_v2/frontend/filters/time/TimeRangePicker.tsx @@ -3,7 +3,7 @@ import { useState } from 'react' import { IconCalendar } from '@posthog/icons' import { Button, DateTimePicker, Popover, PopoverContent, PopoverTrigger } from '@posthog/quill' -import type { TimeRange } from '../dashboard/dashboardTypes' +import type { TimeRange } from '../../dashboard/dashboardTypes' import { DEFAULT_QUICK_RANGES, type QuickRange, diff --git a/products/dashboards_v2/frontend/time/timeRanges.test.ts b/products/dashboards_v2/frontend/filters/time/timeRanges.test.ts similarity index 97% rename from products/dashboards_v2/frontend/time/timeRanges.test.ts rename to products/dashboards_v2/frontend/filters/time/timeRanges.test.ts index 732a3db72dcc1..2d66d90a304a1 100644 --- a/products/dashboards_v2/frontend/time/timeRanges.test.ts +++ b/products/dashboards_v2/frontend/filters/time/timeRanges.test.ts @@ -1,6 +1,6 @@ import { CUSTOM_RANGE } from '@posthog/quill' -import type { TimeRange } from '../dashboard/dashboardTypes' +import type { TimeRange } from '../../dashboard/dashboardTypes' import { type QuickRange, fromPickerValue, toPickerValue } from './timeRanges' const RANGES: QuickRange[] = [ diff --git a/products/dashboards_v2/frontend/time/timeRanges.ts b/products/dashboards_v2/frontend/filters/time/timeRanges.ts similarity index 96% rename from products/dashboards_v2/frontend/time/timeRanges.ts rename to products/dashboards_v2/frontend/filters/time/timeRanges.ts index 4561a09e530d6..ac98208681009 100644 --- a/products/dashboards_v2/frontend/time/timeRanges.ts +++ b/products/dashboards_v2/frontend/filters/time/timeRanges.ts @@ -2,8 +2,8 @@ import { type DateTimeRange, type DateTimeValue, CUSTOM_RANGE } from '@posthog/q import { type Dayjs, dayjs } from 'lib/dayjs' -import { RELATIVE_TIME } from '../dashboard/dashboardSchema' -import type { TimeRange } from '../dashboard/dashboardTypes' +import { RELATIVE_TIME } from '../../dashboard/dashboardSchema' +import type { TimeRange } from '../../dashboard/dashboardTypes' /** A preset the picker offers, which runs from `from` to now, such as `{ label: 'Last hour', from: 'now-1h' }`. */ export interface QuickRange { diff --git a/products/dashboards_v2/frontend/time/useTimeRangeController.ts b/products/dashboards_v2/frontend/filters/time/useTimeRangeController.ts similarity index 87% rename from products/dashboards_v2/frontend/time/useTimeRangeController.ts rename to products/dashboards_v2/frontend/filters/time/useTimeRangeController.ts index 2bf723fe3376d..4b0447b075596 100644 --- a/products/dashboards_v2/frontend/time/useTimeRangeController.ts +++ b/products/dashboards_v2/frontend/filters/time/useTimeRangeController.ts @@ -1,10 +1,10 @@ import { useMemo, useState } from 'react' -import type { TimeRange } from '../dashboard/dashboardTypes' +import type { TimeRange } from '../../dashboard/dashboardTypes' import type { QuickRange } from './timeRanges' export interface TimeRangeController { - /** Undefined shows the dashboard's saved range. */ + /** Undefined shows the saved range. */ value: TimeRange | undefined onChange: (time: TimeRange | undefined) => void ranges?: QuickRange[] diff --git a/products/dashboards_v2/frontend/filters/useDashboardFilters.ts b/products/dashboards_v2/frontend/filters/useDashboardFilters.ts index a35e771b35c8c..a7a428f15257f 100644 --- a/products/dashboards_v2/frontend/filters/useDashboardFilters.ts +++ b/products/dashboards_v2/frontend/filters/useDashboardFilters.ts @@ -1,9 +1,9 @@ import type { ComponentType } from 'react' -import type { QuickRange } from '../time/timeRanges' -import { type TimeRangeController, useTimeRangeController } from '../time/useTimeRangeController' import type { FilterBarProps } from './FilterBar' import type { FilterDefinition } from './filterDefinition' +import type { QuickRange } from './time/timeRanges' +import { type TimeRangeController, useTimeRangeController } from './time/useTimeRangeController' import { type FiltersController, useFiltersController } from './useFiltersController' export interface DashboardFiltersOptions { diff --git a/products/dashboards_v2/frontend/fixtures/kitchenSinkDashboard.ts b/products/dashboards_v2/frontend/fixtures/kitchenSinkDashboard.ts index bcb15d4df831b..eadfc1a7d0188 100644 --- a/products/dashboards_v2/frontend/fixtures/kitchenSinkDashboard.ts +++ b/products/dashboards_v2/frontend/fixtures/kitchenSinkDashboard.ts @@ -6,6 +6,9 @@ import { type ContentWidget, type Dashboard, GRID, type Tile } from '../dashboar import type { ChartConfig } from '../widgets/chart/chartSpec' import { type StatOptions, statSpec } from '../widgets/chart/viz/stat/statSpec' +// TODO(2026-11-25): Delete once the scene loads dashboards from the API. +// It stands in for a saved dashboard and shows every widget and layout case. + const chartOf = (title: string, query: WidgetQuery, viz: ChartConfig['viz']): ContentWidget => ({ type: 'chart', title, diff --git a/products/dashboards_v2/frontend/fixtures/runSampleQuery.ts b/products/dashboards_v2/frontend/fixtures/runSampleQuery.ts index 5dce2f56c0bc0..b71627705699b 100644 --- a/products/dashboards_v2/frontend/fixtures/runSampleQuery.ts +++ b/products/dashboards_v2/frontend/fixtures/runSampleQuery.ts @@ -3,6 +3,9 @@ import { PropertyOperator } from '~/types' import { type AnalyticsPropertyFilter, analyticsPropertyFilters } from '../filters/analytics/analyticsPropertyFilters' import type { DataFrame, RunQuery, WidgetQuery } from '../widgets/chart/vizTypes' +// TODO(2026-11-25): Delete once the scene always runs real queries through the query batch runner. +// Without both v2 query flags, the scene draws charts from these seeded sample frames. + const DAYS = 14 function seededRandom(seed: string): () => number { diff --git a/products/dashboards_v2/frontend/DashboardV2Scene.tsx b/products/dashboards_v2/frontend/scene/DashboardScene.tsx similarity index 79% rename from products/dashboards_v2/frontend/DashboardV2Scene.tsx rename to products/dashboards_v2/frontend/scene/DashboardScene.tsx index cc73c1f19f9ef..db86af497e172 100644 --- a/products/dashboards_v2/frontend/DashboardV2Scene.tsx +++ b/products/dashboards_v2/frontend/scene/DashboardScene.tsx @@ -8,26 +8,26 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic' import { SceneExport } from 'scenes/sceneTypes' import { teamLogic } from 'scenes/teamLogic' -import { DashboardV2Actions } from './dashboard/DashboardV2Actions' -import type { DashboardV2Controller } from './dashboard/dashboardV2Context' -import { DashboardV2View } from './dashboard/DashboardV2View' -import { dashboardV2Logic } from './dashboardV2Logic' -import { createQueryBatchRunner } from './data/queryBatchRunner' -import { ANALYTICS_FILTER_TYPES } from './filters/analytics/analyticsFilterTypes' -import { useDashboardFilters } from './filters/useDashboardFilters' -import { runSampleQuery } from './fixtures/runSampleQuery' -import { createChartWidget } from './widgets/chart/createChartWidget' -import { DEFAULT_WIDGETS } from './widgets/defaultWidgets' +import { DashboardActions } from '../dashboard/DashboardActions' +import type { DashboardController } from '../dashboard/dashboardContext' +import { DashboardView } from '../dashboard/DashboardView' +import { createQueryBatchRunner } from '../data/queryBatchRunner' +import { ANALYTICS_FILTER_TYPES } from '../filters/analytics/analyticsFilterTypes' +import { useDashboardFilters } from '../filters/useDashboardFilters' +import { runSampleQuery } from '../fixtures/runSampleQuery' +import { createChartWidget } from '../widgets/chart/createChartWidget' +import { DEFAULT_WIDGETS } from '../widgets/defaultWidgets' +import { dashboardSceneLogic } from './dashboardSceneLogic' const NON_CHART_WIDGETS = DEFAULT_WIDGETS.filter((widget) => widget.type !== 'chart') const SAMPLE_WIDGETS = [createChartWidget({ runQuery: runSampleQuery }), ...NON_CHART_WIDGETS] export const scene: SceneExport = { - component: DashboardV2Scene, - logic: dashboardV2Logic, + component: DashboardScene, + logic: dashboardSceneLogic, } -export function DashboardV2Scene(): JSX.Element { +export function DashboardScene(): JSX.Element { return ( }> @@ -36,8 +36,8 @@ export function DashboardV2Scene(): JSX.Element { } function DashboardV2(): JSX.Element { - const { dashboard, activeTabId, disabledReasonFor, canUndo, canRedo } = useValues(dashboardV2Logic) - const { applyDashboardEdit, setActiveTab, undo, redo } = useActions(dashboardV2Logic) + const { dashboard, activeTabId, disabledReasonFor, canUndo, canRedo } = useValues(dashboardSceneLogic) + const { applyDashboardEdit, setActiveTab, undo, redo } = useActions(dashboardSceneLogic) const { featureFlags } = useValues(featureFlagLogic) const { currentTeamId, timezone } = useValues(teamLogic) const tabRef = useRef(activeTabId) @@ -69,7 +69,7 @@ function DashboardV2(): JSX.Element { types: runsRealQueries ? undefined : ANALYTICS_FILTER_TYPES, time: { timezone }, }) - const controller = useMemo( + const controller = useMemo( () => ({ dashboard, activeTabId, @@ -99,7 +99,7 @@ function DashboardV2(): JSX.Element { ) return ( - @@ -109,7 +109,7 @@ function DashboardV2(): JSX.Element {

{dashboard.description}

)}
- + } /> diff --git a/products/dashboards_v2/frontend/scene/dashboardSceneLogic.ts b/products/dashboards_v2/frontend/scene/dashboardSceneLogic.ts new file mode 100644 index 0000000000000..84a330a685e07 --- /dev/null +++ b/products/dashboards_v2/frontend/scene/dashboardSceneLogic.ts @@ -0,0 +1,163 @@ +import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea' +import { actionToUrl, router, urlToAction } from 'kea-router' + +import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils' + +import { AccessControlLevel, AccessControlResourceType } from '~/types' + +import type { DashboardAction } from '../dashboard/dashboardContext' +import { type DashboardEdit, type View, applyEdit, settleDashboard } from '../dashboard/dashboardEdits' +import { type DashboardHistory, recordEdit, redoEdit, startHistory, undoEdit } from '../dashboard/dashboardHistory' +import { type Dashboard, type GridTab, activeGridTab } from '../dashboard/dashboardTypes' +import { kitchenSinkDashboard } from '../fixtures/kitchenSinkDashboard' +import { DEFAULT_WIDGETS } from '../widgets/defaultWidgets' +import { sizeOfWidgets } from '../widgets/widgetSpec' + +// The scene passes the same list to the view, so edits here and the grid on screen use the same sizes. +const sizeOf = sizeOfWidgets(DEFAULT_WIDGETS) + +// Generated by kea-typegen. Update if you're an agent, ignore if you're human. +export interface dashboardSceneLogicValues { + activeTab: GridTab + activeTabId: string | null + canRedo: boolean + canUndo: boolean + dashboard: Dashboard + disabledReasonFor: (action: DashboardAction) => string | null + history: DashboardHistory +} + +// Generated by kea-typegen. Update if you're an agent, ignore if you're human. +export interface dashboardSceneLogicActions { + applyDashboardEdit: ( + edit: DashboardEdit, + view?: View + ) => { + edit: DashboardEdit + view: View | undefined + } + commitDashboard: (dashboard: Dashboard) => { + dashboard: Dashboard + } + redo: () => { + value: true + } + setActiveTab: (tabId: string) => { + tabId: string + } + stepHistory: (step: 'back' | 'forward') => { + step: 'back' | 'forward' + } + undo: () => { + value: true + } +} + +// Generated by kea-typegen. Update if you're an agent, ignore if you're human. +export interface dashboardSceneLogicMeta { + __keaTypeGenInternalSelectorTypes: { + dashboard: (history: DashboardHistory) => Dashboard + canUndo: (history: DashboardHistory) => boolean + canRedo: (history: DashboardHistory) => boolean + disabledReasonFor: (dashboard: Dashboard) => (action: DashboardAction) => string | null + activeTab: (dashboard: Dashboard, activeTabId: string | null) => GridTab + } +} + +export type dashboardSceneLogicType = MakeLogicType< + dashboardSceneLogicValues, + dashboardSceneLogicActions, + Record, + dashboardSceneLogicMeta +> + +export const dashboardSceneLogic = kea([ + path(['products', 'dashboardsV2', 'scene', 'dashboardSceneLogic']), + actions({ + /** The one entry point for edits to the layout. Drags and menus call it, so the permission check lives here only. */ + applyDashboardEdit: (edit: DashboardEdit, view?: View) => ({ edit, view }), + commitDashboard: (dashboard: Dashboard) => ({ dashboard }), + undo: true, + redo: true, + stepHistory: (step: 'back' | 'forward') => ({ step }), + setActiveTab: (tabId: string) => ({ tabId }), + }), + reducers({ + history: [ + // TODO(2026-11-23): Load the dashboard from the API and save edits back to it. + // The kitchen sink fixture is temporary. The scene starts from it on every load, so no edit is saved. + startHistory(settleDashboard(kitchenSinkDashboard, sizeOf)) as DashboardHistory, + { + commitDashboard: (state, { dashboard }) => recordEdit(state, dashboard), + stepHistory: (state, { step }) => (step === 'back' ? undoEdit(state) : redoEdit(state)), + }, + ], + activeTabId: [null as string | null, { setActiveTab: (_, { tabId }) => tabId }], + }), + selectors({ + dashboard: [(s) => [s.history], (history: DashboardHistory): Dashboard => history.present], + canUndo: [(s) => [s.history], (history: DashboardHistory): boolean => history.past.length > 0], + canRedo: [(s) => [s.history], (history: DashboardHistory): boolean => history.future.length > 0], + disabledReasonFor: [ + (s) => [s.dashboard], + // Every edit needs Editor, as on v1 dashboards. When the dashboard has no `user_access_level`, this + // falls back to the project-wide dashboard level. + (dashboard: Dashboard): ((action: DashboardAction) => string | null) => + () => + getAccessControlDisabledReason( + AccessControlResourceType.Dashboard, + AccessControlLevel.Editor, + dashboard.user_access_level, + false + ), + ], + activeTab: [ + (s) => [s.dashboard, s.activeTabId], + (dashboard: Dashboard, activeTabId: string | null): GridTab => activeGridTab(dashboard, activeTabId), + ], + }), + listeners(({ actions, values }) => ({ + applyDashboardEdit: ({ edit, view }) => { + if (values.disabledReasonFor(edit.edit)) { + return + } + const next = applyEdit(values.dashboard, edit, sizeOf, view) + if (recordEdit(values.history, next) === values.history) { + return + } + // With no tab in the URL the first tab shows, so a reorder would switch tabs unless the shown one is pinned. + if (edit.edit === 'moveTab' && values.activeTabId === null) { + actions.setActiveTab(values.activeTab.id) + } + actions.commitDashboard(next) + if (edit.edit === 'addTab') { + actions.setActiveTab(next.tabs[next.tabs.length - 1].id) + } + }, + undo: () => { + if (!values.disabledReasonFor('undo')) { + actions.stepHistory('back') + } + }, + redo: () => { + if (!values.disabledReasonFor('redo')) { + actions.stepHistory('forward') + } + }, + })), + actionToUrl(({ values }) => ({ + setActiveTab: () => [ + router.values.location.pathname, + { ...router.values.searchParams, tab: values.activeTab.id }, + router.values.hashParams, + { replace: true }, + ], + })), + urlToAction(({ actions, values }) => ({ + '*': (_, searchParams) => { + if (searchParams.tab && searchParams.tab !== values.activeTabId) { + actions.setActiveTab(searchParams.tab) + } + }, + })), +]) diff --git a/products/dashboards_v2/frontend/tiles/AddTileMenu.tsx b/products/dashboards_v2/frontend/tiles/AddTileMenu.tsx index 59aac4a17dfce..5707c7ca7abac 100644 --- a/products/dashboards_v2/frontend/tiles/AddTileMenu.tsx +++ b/products/dashboards_v2/frontend/tiles/AddTileMenu.tsx @@ -10,10 +10,10 @@ import { DropdownMenuTrigger, } from '@posthog/quill' -import { useDashboardV2 } from '../dashboard/dashboardV2Context' +import { useDashboard } from '../dashboard/dashboardContext' export function AddTileMenu({ gridId, label }: { gridId: string; label?: string }): JSX.Element { - const { widgets, onEdit } = useDashboardV2() + const { widgets, onEdit } = useDashboard() return ( & Partial>): JSX.Element { - const { dashboard, onEdit, sizeOf, can } = useDashboardV2() + const { dashboard, onEdit, sizeOf, can } = useDashboard() const renderTile = useCallback( (tile: Tile, columnPx: number, onSectionRows: OnSectionRows) => ( diff --git a/products/dashboards_v2/frontend/tiles/PresentedTile.tsx b/products/dashboards_v2/frontend/tiles/PresentedTile.tsx index 08c58b4528d62..f68079555ae06 100644 --- a/products/dashboards_v2/frontend/tiles/PresentedTile.tsx +++ b/products/dashboards_v2/frontend/tiles/PresentedTile.tsx @@ -5,8 +5,8 @@ import { useEffect } from 'react' import { IconChevronLeft, IconChevronRight } from '@posthog/icons' import { Button, Dialog, DialogContent, DialogTitle } from '@posthog/quill' +import { useDashboard } from '../dashboard/dashboardContext' import { type ContentWidget, type Tile, isSectionWidget } from '../dashboard/dashboardTypes' -import { useDashboardV2 } from '../dashboard/dashboardV2Context' import { inReadingOrder } from '../grid/gridTiles' import { WidgetCard } from './WidgetCard' @@ -18,7 +18,7 @@ function contentTilesInOrder(tiles: Tile[]): { id: string; widget: ContentWidget } export function PresentedTile(): JSX.Element { - const { activeTab, widgets, presentedTileId, presentTile } = useDashboardV2() + const { activeTab, widgets, presentedTileId, presentTile } = useDashboard() const tiles = contentTilesInOrder(activeTab.tiles) const index = tiles.findIndex((tile) => tile.id === presentedTileId) const widget = tiles[index]?.widget ?? null diff --git a/products/dashboards_v2/frontend/tiles/SectionTile.tsx b/products/dashboards_v2/frontend/tiles/SectionTile.tsx index 2ab226e1900f2..08c2cc2dc00f5 100644 --- a/products/dashboards_v2/frontend/tiles/SectionTile.tsx +++ b/products/dashboards_v2/frontend/tiles/SectionTile.tsx @@ -7,8 +7,8 @@ import { type ReactNode, useCallback, useState } from 'react' import { IconChevronRight } from '@posthog/icons' import { Button, Card, CardAction, CardContent, CardHeader, CardTitle, Input } from '@posthog/quill' +import { useDashboard } from '../dashboard/dashboardContext' import { GRID, type SectionWidget, type Tile, spanPx } from '../dashboard/dashboardTypes' -import { useDashboardV2 } from '../dashboard/dashboardV2Context' import type { OnSectionRows } from '../grid/TileGrid' import { showsBorder } from '../presentation/tileAppearance' import { AddTileMenu } from './AddTileMenu' @@ -42,7 +42,7 @@ export function SectionTile({ /** Draws the section's own grid. Passed in because that grid draws sections too. */ renderGrid: (grid: SectionGridProps) => ReactNode }): JSX.Element { - const { onEdit, onSectionFoldedChange, can } = useDashboardV2() + const { onEdit, onSectionFoldedChange, can } = useDashboard() const collapsed = !!widget.collapsed const [draft, setDraft] = useState(null) const actions = useSectionActions(id, widget, () => setDraft(widget.title)) diff --git a/products/dashboards_v2/frontend/tiles/TileContextMenu.tsx b/products/dashboards_v2/frontend/tiles/TileContextMenu.tsx index 4fc85214311ec..eb20428891ff1 100644 --- a/products/dashboards_v2/frontend/tiles/TileContextMenu.tsx +++ b/products/dashboards_v2/frontend/tiles/TileContextMenu.tsx @@ -16,10 +16,10 @@ import { ContextMenuTrigger, } from '@posthog/quill' +import { type DashboardState, useDashboard } from '../dashboard/dashboardContext' import type { DashboardEdit } from '../dashboard/dashboardEdits' import { downloadImageAction } from '../dashboard/dashboardImage' import { type ContentWidget, type SectionWidget, gridTabs, widgetRef } from '../dashboard/dashboardTypes' -import { type DashboardV2State, useDashboardV2 } from '../dashboard/dashboardV2Context' import type { MenuAction } from '../dashboard/menuAction' import { MenuActionList, type MenuParts } from '../dashboard/MenuActionList' import { everyTile } from '../dashboard/tileTree' @@ -62,7 +62,7 @@ export function useContentTileActions(id: string, widget: ContentWidget): MenuAc downloadImage, downloadingImage, presentTile, - } = useDashboardV2() + } = useDashboard() const otherTabs = gridTabs(dashboard).filter((tab) => tab.id !== activeTab.id) const definition = findWidget(widgets, widget.type) @@ -165,7 +165,7 @@ const TILE_BACKGROUND_COLOR = { function tileImageAction( id: string, downloadingImage: boolean, - downloadImage: DashboardV2State['downloadImage'] + downloadImage: DashboardState['downloadImage'] ): MenuAction { return downloadImageAction('Download as image', 'dashboard-v2-tile-download-image', downloadingImage, (format) => downloadImage(format, id) @@ -197,7 +197,7 @@ function autoLayoutAction( } export function useSectionActions(id: string, widget: SectionWidget, onStartRename: () => void): MenuAction[] { - const { widgets, disabledReasonFor, onEdit, tileActions, downloadImage, downloadingImage } = useDashboardV2() + const { widgets, disabledReasonFor, onEdit, tileActions, downloadImage, downloadingImage } = useDashboard() const show = showAction(TILE_SHOW, [{ id, widget }], widgets, disabledReasonFor('setTilesAppearance'), onEdit) const actions: MenuAction[] = [ { diff --git a/products/dashboards_v2/frontend/widgets/chart/ChartWidget.tsx b/products/dashboards_v2/frontend/widgets/chart/ChartWidget.tsx index 5ee0f533854bb..ea21f0b1a2736 100644 --- a/products/dashboards_v2/frontend/widgets/chart/ChartWidget.tsx +++ b/products/dashboards_v2/frontend/widgets/chart/ChartWidget.tsx @@ -3,7 +3,6 @@ import { useContext, useMemo } from 'react' import type { ContentWidget } from '../../dashboard/dashboardTypes' import { FiltersContext } from '../../filters/filtersContext' -import { TimeRangeContext } from '../timeRangeContext' import { WidgetLoading } from '../WidgetLoading' import { type ChartConfig, chartTargets } from './chartSpec' import { type TargetFailure, combineTargetResults } from './targetResults' @@ -52,8 +51,7 @@ function ChartData({ runQuery: RunQuery states?: ChartStates }): JSX.Element { - const surroundingTime = useContext(TimeRangeContext) - const filters = useContext(FiltersContext) + const { time: surroundingTime, filters } = useContext(FiltersContext) const time = widget.config.time ?? surroundingTime const targets = chartTargets(widget.config) // Filters are left out when empty, so a chart's cached result from before any filter existed still matches. diff --git a/products/dashboards_v2/frontend/widgets/timeRangeContext.ts b/products/dashboards_v2/frontend/widgets/timeRangeContext.ts deleted file mode 100644 index 26202a3089015..0000000000000 --- a/products/dashboards_v2/frontend/widgets/timeRangeContext.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createContext } from 'react' - -import type { TimeRange } from '../dashboard/dashboardTypes' - -export const DEFAULT_TIME_RANGE: TimeRange = { from: 'now-7d', to: 'now' } - -/** - * The time range of widgets that do not set their own. `DashboardV2View` provides the dashboard's range, and a host - * that renders a widget on its own can provide one, so widgets never read the dashboard to get it. - */ -export const TimeRangeContext = createContext(DEFAULT_TIME_RANGE) diff --git a/products/dashboards_v2/manifest.tsx b/products/dashboards_v2/manifest.tsx index 8cec3e0d64e8a..fb75c8dbf09c0 100644 --- a/products/dashboards_v2/manifest.tsx +++ b/products/dashboards_v2/manifest.tsx @@ -5,7 +5,7 @@ export const manifest: ProductManifest = { scenes: { DashboardV2: { name: 'Dashboard v2', - import: () => import('./frontend/DashboardV2Scene'), + import: () => import('./frontend/scene/DashboardScene'), projectBased: true, }, }, From d1ee9a61066f24cb38e2cf0a3b1995a27a05faa9 Mon Sep 17 00:00:00 2001 From: Matt Pua Date: Wed, 25 Nov 2026 17:43:20 -0500 Subject: [PATCH 03/10] refactor(dashboards): type widget boundaries and tidy v2 primitives - Check widget configs at defineWidget with required generics instead of unknown and casts - Merge background options into one backgroundColor setting - Rename addMenuItems to addTileOptions/addFilterOptions and HeaderActions to HeaderExtra - Merge tileActions into menuActions - Add widget and dashboard error boundaries with the error hoggie - Use type aliases instead of interfaces; group primitives into folders Co-Authored-By: Claude Opus 5.5 --- products/dashboards_v2/.agents/primitives.md | 47 +++++++ .../dashboard/DashboardErrorBoundary.tsx | 38 ++++++ .../frontend/dashboard/DashboardTabs.tsx | 8 +- .../dashboard/DashboardUnavailable.tsx | 13 +- .../frontend/dashboard/DashboardView.tsx | 53 +++++--- .../{ => actions}/AutoRefreshButton.tsx | 2 +- .../{ => actions}/DashboardActions.tsx | 4 +- .../dashboard/{ => actions}/DashboardMenu.tsx | 2 +- .../dashboard/{ => actions}/dashboardImage.ts | 4 +- .../{ => actions}/useDashboardActions.ts | 10 +- .../{ => actions}/useDashboardRefresh.ts | 2 +- .../frontend/dashboard/dashboardContext.ts | 24 ++-- .../{ => document}/dashboardSchema.ts | 5 +- .../{ => document}/dashboardTypes.ts | 18 ++- .../{ => document}/sharedWidgets.test.ts | 0 .../dashboard/{ => document}/sharedWidgets.ts | 0 .../dashboard/{ => document}/tileTree.ts | 0 .../{ => document}/validateDashboard.test.ts | 35 +++-- .../{ => document}/validateDashboard.ts | 25 ++-- .../{ => edits}/dashboardEdits.test.ts | 13 +- .../dashboard/{ => edits}/dashboardEdits.ts | 14 +- .../{ => edits}/dashboardHistory.test.ts | 2 +- .../dashboard/{ => edits}/dashboardHistory.ts | 4 +- .../{ => edits}/useDashboardHistory.ts | 2 +- .../frontend/dashboard/useStableController.ts | 84 ++++++++++++ .../frontend/data/queryBatchLines.ts | 6 +- .../frontend/data/queryBatchRunner.test.ts | 2 +- .../frontend/data/queryBatchRunner.ts | 9 +- .../filters/{ => bar}/AddFilterMenu.tsx | 14 +- .../frontend/filters/{ => bar}/FilterBar.tsx | 14 +- .../frontend/filters/{ => bar}/FilterPill.tsx | 10 +- .../filters/{ => bar}/FilterPillContent.tsx | 2 +- .../frontend/filters/filterDefinition.ts | 8 +- .../frontend/filters/filterEdits.ts | 6 +- .../frontend/filters/filterSpec.ts | 14 +- .../frontend/filters/filtersContext.ts | 17 ++- .../filters/{ => pickers}/FieldSearch.tsx | 4 +- .../filters/{ => pickers}/ValueList.tsx | 4 +- .../{ => pickers}/useSearchedOptions.ts | 20 ++- .../filters/property/ConditionEditor.tsx | 4 +- .../filters/property/PropertyFilter.tsx | 2 +- .../filters/property/PropertyFilterPicker.tsx | 4 +- .../filters/property/propertyFilterSpec.ts | 10 +- .../filters/property/propertyOperators.ts | 4 +- .../filters/property/useConditionDrafts.ts | 2 +- .../frontend/filters/select/SelectFilter.tsx | 2 +- .../filters/select/selectFilterSpec.ts | 6 +- .../frontend/filters/time/TimeRangePicker.tsx | 11 +- .../frontend/filters/time/timeRanges.test.ts | 2 +- .../frontend/filters/time/timeRanges.ts | 6 +- .../filters/time/useTimeRangeController.ts | 4 +- .../frontend/filters/useDashboardFilters.ts | 10 +- .../frontend/filters/useFiltersController.ts | 14 +- .../frontend/fixtures/kitchenSinkDashboard.ts | 6 +- .../dashboards_v2/frontend/grid/TileGrid.tsx | 18 +-- .../frontend/grid/{ => drag}/dropTargets.ts | 8 +- .../frontend/grid/{ => drag}/gridDrag.ts | 2 +- .../grid/{ => drag}/resizeFeedback.ts | 0 .../frontend/grid/{ => drag}/scrollParent.ts | 0 .../grid/{ => layout}/gridCompactor.ts | 2 +- .../frontend/grid/{ => layout}/gridTiles.ts | 2 +- .../grid/{ => layout}/placeTiles.test.ts | 0 .../frontend/grid/{ => layout}/placeTiles.ts | 4 +- .../frontend/grid/tileMounting.ts | 4 +- .../{dashboard => menu}/MenuActionList.tsx | 2 +- .../{dashboard => menu}/menuAction.ts | 6 +- .../presentation/presentationEdits.ts | 4 +- .../presentation/tileAppearance.test.ts | 12 +- .../frontend/presentation/tileAppearance.ts | 36 ++--- .../frontend/presentation/tileParts.test.ts | 4 +- .../frontend/presentation/tileParts.ts | 12 +- .../frontend/scene/DashboardScene.tsx | 43 ++---- .../frontend/scene/dashboardSceneLogic.ts | 18 ++- .../frontend/schema/parseOnce.ts | 25 ++++ .../frontend/tiles/ContentTile.tsx | 34 ----- .../frontend/tiles/DashboardTileGrid.tsx | 45 +++++-- .../frontend/tiles/SectionTile.tsx | 33 ++--- .../frontend/tiles/TileHoverReveal.css | 25 ---- .../{PresentedTile.css => TileSlideshow.css} | 8 +- .../{PresentedTile.tsx => TileSlideshow.tsx} | 42 +++--- .../frontend/tiles/WidgetCard.stories.tsx | 50 ------- .../frontend/tiles/applyTileActions.test.ts | 37 ------ .../frontend/tiles/applyTileActions.ts | 18 --- .../frontend/tiles/{ => card}/WidgetCard.css | 0 .../frontend/tiles/{ => card}/WidgetCard.tsx | 74 +++++------ .../frontend/tiles/{ => menu}/AddTileMenu.tsx | 28 ++-- .../frontend/tiles/menu/TileActions.css | 20 +++ .../frontend/tiles/menu/TileActions.tsx | 31 +++++ .../tiles/{ => menu}/TileContextMenu.tsx | 61 ++++----- .../tiles/{ => menu}/TileMenuButton.tsx | 0 .../frontend/widgets/WidgetErrorBoundary.tsx | 49 +++++++ .../frontend/widgets/WidgetLoading.tsx | 9 -- .../frontend/widgets/WidgetView.tsx | 99 ++++++-------- .../frontend/widgets/chart/ChartWidget.tsx | 8 +- .../widgets/chart/chartMenuActions.test.ts | 4 +- .../widgets/chart/chartMenuActions.ts | 2 +- .../frontend/widgets/chart/chartSpec.ts | 41 +++--- .../widgets/chart/createChartWidget.tsx | 36 +++-- .../chart/{ => data}/queryCache.test.ts | 2 +- .../widgets/chart/{ => data}/queryCache.ts | 2 +- .../chart/{ => data}/targetResults.test.ts | 2 +- .../widgets/chart/{ => data}/targetResults.ts | 6 +- .../chart/{ => data}/timeSeriesFrames.test.ts | 2 +- .../chart/{ => data}/timeSeriesFrames.ts | 4 +- .../chart/{ => data}/useQueryFrames.test.ts | 0 .../chart/{ => data}/useQueryFrames.ts | 4 +- .../frontend/widgets/chart/viz/bar/BarViz.tsx | 2 +- .../widgets/chart/viz/line/LineViz.tsx | 2 +- .../widgets/chart/viz/stat/StatViz.tsx | 2 +- .../frontend/widgets/chart/vizTypes.ts | 26 ++-- .../frontend/widgets/defaultWidgets.ts | 10 +- .../frontend/widgets/markdown/markdownSpec.ts | 5 +- .../frontend/widgets/widgetDefinition.ts | 54 -------- .../frontend/widgets/widgetDefinition.tsx | 125 ++++++++++++++++++ .../frontend/widgets/widgetSpec.ts | 66 +++++---- 115 files changed, 1064 insertions(+), 832 deletions(-) create mode 100644 products/dashboards_v2/frontend/dashboard/DashboardErrorBoundary.tsx rename products/dashboards_v2/frontend/dashboard/{ => actions}/AutoRefreshButton.tsx (98%) rename products/dashboards_v2/frontend/dashboard/{ => actions}/DashboardActions.tsx (93%) rename products/dashboards_v2/frontend/dashboard/{ => actions}/DashboardMenu.tsx (95%) rename products/dashboards_v2/frontend/dashboard/{ => actions}/dashboardImage.ts (92%) rename products/dashboards_v2/frontend/dashboard/{ => actions}/useDashboardActions.ts (89%) rename products/dashboards_v2/frontend/dashboard/{ => actions}/useDashboardRefresh.ts (95%) rename products/dashboards_v2/frontend/dashboard/{ => document}/dashboardSchema.ts (98%) rename products/dashboards_v2/frontend/dashboard/{ => document}/dashboardTypes.ts (83%) rename products/dashboards_v2/frontend/dashboard/{ => document}/sharedWidgets.test.ts (100%) rename products/dashboards_v2/frontend/dashboard/{ => document}/sharedWidgets.ts (100%) rename products/dashboards_v2/frontend/dashboard/{ => document}/tileTree.ts (100%) rename products/dashboards_v2/frontend/dashboard/{ => document}/validateDashboard.test.ts (89%) rename products/dashboards_v2/frontend/dashboard/{ => document}/validateDashboard.ts (91%) rename products/dashboards_v2/frontend/dashboard/{ => edits}/dashboardEdits.test.ts (98%) rename products/dashboards_v2/frontend/dashboard/{ => edits}/dashboardEdits.ts (97%) rename products/dashboards_v2/frontend/dashboard/{ => edits}/dashboardHistory.test.ts (94%) rename products/dashboards_v2/frontend/dashboard/{ => edits}/dashboardHistory.ts (93%) rename products/dashboards_v2/frontend/dashboard/{ => edits}/useDashboardHistory.ts (94%) create mode 100644 products/dashboards_v2/frontend/dashboard/useStableController.ts rename products/dashboards_v2/frontend/filters/{ => bar}/AddFilterMenu.tsx (87%) rename products/dashboards_v2/frontend/filters/{ => bar}/FilterBar.tsx (92%) rename products/dashboards_v2/frontend/filters/{ => bar}/FilterPill.tsx (86%) rename products/dashboards_v2/frontend/filters/{ => bar}/FilterPillContent.tsx (88%) rename products/dashboards_v2/frontend/filters/{ => pickers}/FieldSearch.tsx (97%) rename products/dashboards_v2/frontend/filters/{ => pickers}/ValueList.tsx (97%) rename products/dashboards_v2/frontend/filters/{ => pickers}/useSearchedOptions.ts (76%) rename products/dashboards_v2/frontend/grid/{ => drag}/dropTargets.ts (95%) rename products/dashboards_v2/frontend/grid/{ => drag}/gridDrag.ts (95%) rename products/dashboards_v2/frontend/grid/{ => drag}/resizeFeedback.ts (100%) rename products/dashboards_v2/frontend/grid/{ => drag}/scrollParent.ts (100%) rename products/dashboards_v2/frontend/grid/{ => layout}/gridCompactor.ts (98%) rename products/dashboards_v2/frontend/grid/{ => layout}/gridTiles.ts (99%) rename products/dashboards_v2/frontend/grid/{ => layout}/placeTiles.test.ts (100%) rename products/dashboards_v2/frontend/grid/{ => layout}/placeTiles.ts (99%) rename products/dashboards_v2/frontend/{dashboard => menu}/MenuActionList.tsx (99%) rename products/dashboards_v2/frontend/{dashboard => menu}/menuAction.ts (79%) create mode 100644 products/dashboards_v2/frontend/schema/parseOnce.ts delete mode 100644 products/dashboards_v2/frontend/tiles/ContentTile.tsx delete mode 100644 products/dashboards_v2/frontend/tiles/TileHoverReveal.css rename products/dashboards_v2/frontend/tiles/{PresentedTile.css => TileSlideshow.css} (78%) rename products/dashboards_v2/frontend/tiles/{PresentedTile.tsx => TileSlideshow.tsx} (62%) delete mode 100644 products/dashboards_v2/frontend/tiles/WidgetCard.stories.tsx delete mode 100644 products/dashboards_v2/frontend/tiles/applyTileActions.test.ts delete mode 100644 products/dashboards_v2/frontend/tiles/applyTileActions.ts rename products/dashboards_v2/frontend/tiles/{ => card}/WidgetCard.css (100%) rename products/dashboards_v2/frontend/tiles/{ => card}/WidgetCard.tsx (65%) rename products/dashboards_v2/frontend/tiles/{ => menu}/AddTileMenu.tsx (64%) create mode 100644 products/dashboards_v2/frontend/tiles/menu/TileActions.css create mode 100644 products/dashboards_v2/frontend/tiles/menu/TileActions.tsx rename products/dashboards_v2/frontend/tiles/{ => menu}/TileContextMenu.tsx (82%) rename products/dashboards_v2/frontend/tiles/{ => menu}/TileMenuButton.tsx (100%) create mode 100644 products/dashboards_v2/frontend/widgets/WidgetErrorBoundary.tsx delete mode 100644 products/dashboards_v2/frontend/widgets/WidgetLoading.tsx rename products/dashboards_v2/frontend/widgets/chart/{ => data}/queryCache.test.ts (98%) rename products/dashboards_v2/frontend/widgets/chart/{ => data}/queryCache.ts (97%) rename products/dashboards_v2/frontend/widgets/chart/{ => data}/targetResults.test.ts (97%) rename products/dashboards_v2/frontend/widgets/chart/{ => data}/targetResults.ts (93%) rename products/dashboards_v2/frontend/widgets/chart/{ => data}/timeSeriesFrames.test.ts (99%) rename products/dashboards_v2/frontend/widgets/chart/{ => data}/timeSeriesFrames.ts (98%) rename products/dashboards_v2/frontend/widgets/chart/{ => data}/useQueryFrames.test.ts (100%) rename products/dashboards_v2/frontend/widgets/chart/{ => data}/useQueryFrames.ts (97%) delete mode 100644 products/dashboards_v2/frontend/widgets/widgetDefinition.ts create mode 100644 products/dashboards_v2/frontend/widgets/widgetDefinition.tsx diff --git a/products/dashboards_v2/.agents/primitives.md b/products/dashboards_v2/.agents/primitives.md index f64084b99ca73..7d55870fcc628 100644 --- a/products/dashboards_v2/.agents/primitives.md +++ b/products/dashboards_v2/.agents/primitives.md @@ -5,6 +5,53 @@ 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 ( + } + /> +) +``` + +Event handlers, `history` and `refresh` can be written inline. Keep `dashboard`, `widgets`, `filters`, `timeRange`, `disabledReasonFor`, `tileActions` 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. +Wrap it in `FiltersContext` or `RefreshContext` only when the page has filters or a refresh to pass down. + +```tsx + + + +``` + ## 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/`. diff --git a/products/dashboards_v2/frontend/dashboard/DashboardErrorBoundary.tsx b/products/dashboards_v2/frontend/dashboard/DashboardErrorBoundary.tsx new file mode 100644 index 0000000000000..8381e42aa4718 --- /dev/null +++ b/products/dashboards_v2/frontend/dashboard/DashboardErrorBoundary.tsx @@ -0,0 +1,38 @@ +import posthog from 'posthog-js' +import { Component, type ErrorInfo, type ReactNode } from 'react' + +import { DashboardUnavailable } from './DashboardUnavailable' +import type { Dashboard } from './document/dashboardTypes' + +type DashboardErrorState = { + failed: boolean + dashboard: Dashboard +} + +/** The fallback for an error no widget boundary caught, such as one in the grid, a section or the filter bar. */ +export class DashboardErrorBoundary extends Component< + { dashboard: Dashboard; children: ReactNode }, + DashboardErrorState +> { + override state: DashboardErrorState = { failed: false, dashboard: this.props.dashboard } + + // A new document from the host, such as an undo or a reload, gets another try. + static getDerivedStateFromProps( + props: { dashboard: Dashboard }, + state: DashboardErrorState + ): DashboardErrorState | null { + return props.dashboard === state.dashboard ? null : { failed: false, dashboard: props.dashboard } + } + + static getDerivedStateFromError(): Partial { + return { failed: true } + } + + override componentDidCatch(error: Error, info: ErrorInfo): void { + posthog.captureException(error, { tag: 'dashboards-v2-dashboard', componentStack: info.componentStack }) + } + + override render(): ReactNode { + return this.state.failed ? : this.props.children + } +} diff --git a/products/dashboards_v2/frontend/dashboard/DashboardTabs.tsx b/products/dashboards_v2/frontend/dashboard/DashboardTabs.tsx index 0e31f090f97f7..577e954dcbfee 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardTabs.tsx +++ b/products/dashboards_v2/frontend/dashboard/DashboardTabs.tsx @@ -18,16 +18,16 @@ import { import { hasDangerousScheme } from 'lib/utils/url' -import { useGridDrag } from '../grid/gridDrag' +import { useGridDrag } from '../grid/drag/gridDrag' import { useDashboard } from './dashboardContext' -import { type DashboardTab, isGridTab } from './dashboardTypes' +import { type DashboardTab, isGridTab } from './document/dashboardTypes' -interface TabDraft { +type TabDraft = { id: string title: string } -interface TabInsert { +type TabInsert = { id: string side: 'before' | 'after' } diff --git a/products/dashboards_v2/frontend/dashboard/DashboardUnavailable.tsx b/products/dashboards_v2/frontend/dashboard/DashboardUnavailable.tsx index 02703fc93572b..3641f4c907653 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardUnavailable.tsx +++ b/products/dashboards_v2/frontend/dashboard/DashboardUnavailable.tsx @@ -1,6 +1,7 @@ import clsx from 'clsx' import type { ReactNode } from 'react' +import * as errorHoggie from '@posthog/brand/hoggies/png/error' import * as magnifyingGlass from '@posthog/brand/hoggies/png/magnifying-glass' import * as stampDenied from '@posthog/brand/hoggies/png/stamp-denied' import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@posthog/quill' @@ -9,10 +10,11 @@ import { pngHoggie } from 'lib/brand/hoggies' const HedgehogSearching = pngHoggie(magnifyingGlass) const HedgehogDenied = pngHoggie(stampDenied) +const HedgehogError = pngHoggie(errorHoggie) -export type UnavailableReason = 'notFound' | 'noAccess' +export type UnavailableReason = 'notFound' | 'noAccess' | 'error' -interface ProblemView { +type ProblemView = { illustration: ReactNode title: ReactNode description: ReactNode @@ -29,9 +31,14 @@ const DEFAULT_VIEWS: Record = { title: "You don't have access to this dashboard", description: 'Ask the dashboard owner or a project admin to give you access.', }, + error: { + illustration: , + title: "This dashboard couldn't be shown", + description: 'Refresh the page, and if it keeps happening contact support.', + }, } -export interface DashboardUnavailableProps extends Partial { +export type DashboardUnavailableProps = Partial & { problem: UnavailableReason /** Buttons or links for the next step, such as going back to a list. The default view has none. */ actions?: ReactNode diff --git a/products/dashboards_v2/frontend/dashboard/DashboardView.tsx b/products/dashboards_v2/frontend/dashboard/DashboardView.tsx index f8a3fb4089e7e..4d1ffc16909fc 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardView.tsx +++ b/products/dashboards_v2/frontend/dashboard/DashboardView.tsx @@ -8,35 +8,36 @@ import { useContainerWidth } from 'react-grid-layout' // oxlint-disable-next-line no-restricted-imports import { lemonToast } from 'lib/lemon-ui/LemonToast' -import { FilterBar } from '../filters/FilterBar' -import { type ActiveFilters, DEFAULT_TIME_RANGE, FiltersContext, appliedFilters } from '../filters/filtersContext' +import { FilterBar } from '../filters/bar/FilterBar' +import { type ActiveFilters, FiltersContext, appliedFilters } from '../filters/filtersContext' import { TimeRangePicker } from '../filters/time/TimeRangePicker' -import type { DropTarget } from '../grid/dropTargets' -import { GridDragContext, type GridDragState } from '../grid/gridDrag' -import { stackTiles } from '../grid/gridTiles' +import type { DropTarget } from '../grid/drag/dropTargets' +import { GridDragContext, type GridDragState } from '../grid/drag/gridDrag' +import { stackTiles } from '../grid/layout/gridTiles' import { CapturingTileContext, TileMountContext, createTileMountScheduler } from '../grid/tileMounting' import { DashboardTileGrid } from '../tiles/DashboardTileGrid' -import { PresentedTile } from '../tiles/PresentedTile' +import { TileSlideshow } from '../tiles/TileSlideshow' import { RefreshContext } from '../widgets/refreshContext' import { sizeOfWidgets } from '../widgets/widgetSpec' +import { type ImageFormat, downloadDashboardImage } from './actions/dashboardImage' +import { useDashboardRefresh } from './actions/useDashboardRefresh' import { type DashboardAction, type DashboardController, type DashboardState, DashboardStateContext, } from './dashboardContext' -import { withFolds } from './dashboardEdits' -import { type ImageFormat, downloadDashboardImage } from './dashboardImage' +import { DashboardErrorBoundary } from './DashboardErrorBoundary' import { DashboardTabs } from './DashboardTabs' -import { type Dashboard, GRID, activeGridTab, gridTabs } from './dashboardTypes' -import { findTile } from './tileTree' -import { useDashboardRefresh } from './useDashboardRefresh' +import { type Dashboard, GRID, activeGridTab, gridTabs } from './document/dashboardTypes' +import { findTile } from './document/tileTree' +import { withFolds } from './edits/dashboardEdits' +import { useStableController } from './useStableController' // A stacked column is not the saved layout, so only dragging and resizing tiles in it is blocked. const STACKED_REASON = 'Open this dashboard on a wider screen to arrange tiles' -export interface DashboardViewProps { - controller: DashboardController +export type DashboardViewProps = DashboardController & { /** Rendered above the tabs, inside the dashboard, so it can use the dashboard's own controls. */ header?: ReactNode } @@ -82,7 +83,16 @@ function imageWords( } /** A whole dashboard: tabs and grid. Its own state is only what the screen and a drag in progress decide. */ -export function DashboardView({ controller, header }: DashboardViewProps): JSX.Element { +export function DashboardView(props: DashboardViewProps): JSX.Element { + return ( + + + + ) +} + +function DashboardViewContent({ header, ...props }: DashboardViewProps): JSX.Element { + const controller = useStableController(props) const { width, containerRef, mounted } = useContainerWidth() const stacked = width > 0 && width < GRID.stackBelowPx const [dropTarget, setDropTarget] = useState(null) @@ -94,7 +104,7 @@ export function DashboardView({ controller, header }: DashboardViewProps): JSX.E [] ) const rootRef = useRef(null) - const [presentedTileId, presentTile] = useState(null) + const [slideshowTileId, showSlideshow] = useState(null) const refresh = useDashboardRefresh(controller.refresh) // A capture mounts what it shows, so the image has no placeholders: the whole tab, or with `tileId` that tile only. const [capturing, setCapturing] = useState<{ tileId?: string } | null>(null) @@ -140,8 +150,8 @@ export function DashboardView({ controller, header }: DashboardViewProps): JSX.E onSectionFoldedChange, downloadImage: (format, tileId) => void downloadImage(format, tileId), downloadingImage, - presentedTileId, - presentTile, + slideshowTileId, + showSlideshow, refresh: refresh.button, } }, [ @@ -152,7 +162,7 @@ export function DashboardView({ controller, header }: DashboardViewProps): JSX.E onSectionFoldedChange, downloadImage, downloadingImage, - presentedTileId, + slideshowTileId, refresh.button, ]) const drag = useMemo(() => ({ dropTarget, setDropTarget }), [dropTarget]) @@ -163,12 +173,11 @@ export function DashboardView({ controller, header }: DashboardViewProps): JSX.E const savedFilters = controller.dashboard.filters const filterValues = controller.filters?.values const filtersOn = !!controller.filters && !!controller.dashboard.allowFilters - const FilterBarComponent = controller.filters?.Bar ?? FilterBar const applied = useMemo( () => (filtersOn && filterValues ? appliedFilters(savedFilters ?? [], filterValues) : []), [filtersOn, savedFilters, filterValues] ) - const time = controller.timeRange?.value ?? controller.dashboard.time ?? DEFAULT_TIME_RANGE + const time = controller.timeRange?.value ?? controller.dashboard.time const activeFilters = useMemo(() => ({ time, filters: applied }), [time, applied]) const tiles = useMemo( () => (stacked ? stackTiles(activeTab.tiles, GRID.columns, sizeOf) : activeTab.tiles), @@ -226,7 +235,7 @@ export function DashboardView({ controller, header }: DashboardViewProps): JSX.E )}
{filtersOn && controller.filters && ( -
- +
diff --git a/products/dashboards_v2/frontend/dashboard/AutoRefreshButton.tsx b/products/dashboards_v2/frontend/dashboard/actions/AutoRefreshButton.tsx similarity index 98% rename from products/dashboards_v2/frontend/dashboard/AutoRefreshButton.tsx rename to products/dashboards_v2/frontend/dashboard/actions/AutoRefreshButton.tsx index d11e648124088..332d1495efcd7 100644 --- a/products/dashboards_v2/frontend/dashboard/AutoRefreshButton.tsx +++ b/products/dashboards_v2/frontend/dashboard/actions/AutoRefreshButton.tsx @@ -28,7 +28,7 @@ export function intervalLabel(seconds: number): string { return `${seconds} seconds` } -export interface AutoRefreshProps { +export type AutoRefreshProps = { intervals?: number[] interval: number | null onIntervalChange: (interval: number | null) => void diff --git a/products/dashboards_v2/frontend/dashboard/DashboardActions.tsx b/products/dashboards_v2/frontend/dashboard/actions/DashboardActions.tsx similarity index 93% rename from products/dashboards_v2/frontend/dashboard/DashboardActions.tsx rename to products/dashboards_v2/frontend/dashboard/actions/DashboardActions.tsx index 7a75836b98951..940c46b17f3a9 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardActions.tsx +++ b/products/dashboards_v2/frontend/dashboard/actions/DashboardActions.tsx @@ -1,9 +1,9 @@ import { IconRedo, IconUndo } from '@posthog/icons' import { Button } from '@posthog/quill' -import { AddTileMenu } from '../tiles/AddTileMenu' +import { AddTileMenu } from '../../tiles/menu/AddTileMenu' +import { useDashboard } from '../dashboardContext' import { AutoRefreshButton } from './AutoRefreshButton' -import { useDashboard } from './dashboardContext' import { DashboardMenu } from './DashboardMenu' export function DashboardActions(): JSX.Element { diff --git a/products/dashboards_v2/frontend/dashboard/DashboardMenu.tsx b/products/dashboards_v2/frontend/dashboard/actions/DashboardMenu.tsx similarity index 95% rename from products/dashboards_v2/frontend/dashboard/DashboardMenu.tsx rename to products/dashboards_v2/frontend/dashboard/actions/DashboardMenu.tsx index 4b045544ba6ca..05de189e34d06 100644 --- a/products/dashboards_v2/frontend/dashboard/DashboardMenu.tsx +++ b/products/dashboards_v2/frontend/dashboard/actions/DashboardMenu.tsx @@ -16,7 +16,7 @@ import { DropdownMenuTrigger, } from '@posthog/quill' -import { MenuActionList, type MenuParts } from './MenuActionList' +import { MenuActionList, type MenuParts } from '../../menu/MenuActionList' import { useDashboardActions } from './useDashboardActions' const DROPDOWN_PARTS: MenuParts = { diff --git a/products/dashboards_v2/frontend/dashboard/dashboardImage.ts b/products/dashboards_v2/frontend/dashboard/actions/dashboardImage.ts similarity index 92% rename from products/dashboards_v2/frontend/dashboard/dashboardImage.ts rename to products/dashboards_v2/frontend/dashboard/actions/dashboardImage.ts index a2cc1e55e8225..2428daa91ada7 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardImage.ts +++ b/products/dashboards_v2/frontend/dashboard/actions/dashboardImage.ts @@ -2,7 +2,7 @@ import { captureElementAsImage } from 'lib/utils/copyImageToClipboard' import { downloadFile } from 'lib/utils/dom' import { slugify } from 'lib/utils/strings' -import type { MenuAction } from './menuAction' +import type { MenuAction } from '../../menu/menuAction' export type ImageFormat = 'png' | 'webp' @@ -12,7 +12,7 @@ export const IMAGE_FORMATS: { format: ImageFormat; label: string }[] = [ ] const LEFT_OUT = - '.TileHoverReveal, .react-resizable-handle, .TileGrid__drop-preview, .DashboardActions, [data-attr="dashboard-v2-add-tab"]' + '.TileActions, .react-resizable-handle, .TileGrid__drop-preview, .DashboardActions, [data-attr="dashboard-v2-add-tab"]' const NOT_READY = '.DashboardTileGrid__placeholder, [aria-busy="true"]' const READY_TIMEOUT_MS = 20000 const POLL_MS = 100 diff --git a/products/dashboards_v2/frontend/dashboard/useDashboardActions.ts b/products/dashboards_v2/frontend/dashboard/actions/useDashboardActions.ts similarity index 89% rename from products/dashboards_v2/frontend/dashboard/useDashboardActions.ts rename to products/dashboards_v2/frontend/dashboard/actions/useDashboardActions.ts index 4c380017b9347..7843de536ad9e 100644 --- a/products/dashboards_v2/frontend/dashboard/useDashboardActions.ts +++ b/products/dashboards_v2/frontend/dashboard/actions/useDashboardActions.ts @@ -1,11 +1,11 @@ import { useMemo } from 'react' -import { showAction } from '../presentation/tileAppearance' -import { useDashboard } from './dashboardContext' +import type { MenuAction } from '../../menu/menuAction' +import { showAction } from '../../presentation/tileAppearance' +import { useDashboard } from '../dashboardContext' +import { gridTabs } from '../document/dashboardTypes' +import { everyTile } from '../document/tileTree' import { downloadImageAction } from './dashboardImage' -import { gridTabs } from './dashboardTypes' -import type { MenuAction } from './menuAction' -import { everyTile } from './tileTree' /** * The dashboard's own actions, after the host's `dashboardActions`. `DashboardMenu` shows them; a host with its own menu, diff --git a/products/dashboards_v2/frontend/dashboard/useDashboardRefresh.ts b/products/dashboards_v2/frontend/dashboard/actions/useDashboardRefresh.ts similarity index 95% rename from products/dashboards_v2/frontend/dashboard/useDashboardRefresh.ts rename to products/dashboards_v2/frontend/dashboard/actions/useDashboardRefresh.ts index 928755c88dc6e..ceb20bfff9544 100644 --- a/products/dashboards_v2/frontend/dashboard/useDashboardRefresh.ts +++ b/products/dashboards_v2/frontend/dashboard/actions/useDashboardRefresh.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react' +import type { RefreshController } from '../dashboardContext' import type { AutoRefreshProps } from './AutoRefreshButton' -import type { RefreshController } from './dashboardContext' /** `count` goes up on every refresh, from the button or the timer, so each chart runs its query again. */ export function useDashboardRefresh(refresh: RefreshController | undefined): { diff --git a/products/dashboards_v2/frontend/dashboard/dashboardContext.ts b/products/dashboards_v2/frontend/dashboard/dashboardContext.ts index 89c54bf1af519..4da6dca9a73df 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardContext.ts +++ b/products/dashboards_v2/frontend/dashboard/dashboardContext.ts @@ -2,12 +2,12 @@ import { createContext, useContext } from 'react' import type { TimeRangeController } from '../filters/time/useTimeRangeController' import type { FiltersController } from '../filters/useFiltersController' -import type { WidgetDefinition } from '../widgets/widgetDefinition' -import type { AutoRefreshProps } from './AutoRefreshButton' -import type { DashboardEdit, View } from './dashboardEdits' -import type { ImageFormat } from './dashboardImage' -import type { Dashboard, GridTab, SizeOf, Widget } from './dashboardTypes' -import type { MenuAction } from './menuAction' +import type { MenuAction } from '../menu/menuAction' +import type { WidgetType } from '../widgets/widgetDefinition' +import type { AutoRefreshProps } from './actions/AutoRefreshButton' +import type { ImageFormat } from './actions/dashboardImage' +import type { Dashboard, GridTab, SizeOf, Widget } from './document/dashboardTypes' +import type { DashboardEdit, View } from './edits/dashboardEdits' /** Everything a person can do to a dashboard. A host's `disabledReasonFor` can give each one its own answer. */ export type DashboardAction = DashboardEdit['edit'] | 'undo' | 'redo' @@ -16,13 +16,13 @@ export type DashboardAction = DashboardEdit['edit'] | 'undo' | 'redo' * What a host passes to `DashboardView`. The host owns the state and the rules behind it (history, access, saving, * the URL), so the components render the same on any page that embeds them. */ -export interface DashboardController { +export type DashboardController = { /** The saved dashboard. The view folds closed sections itself. */ dashboard: Dashboard /** Unknown or unset shows the first tab. */ activeTabId: string | null /** The widget types this dashboard can show and add. Keep the array stable between renders, or every tile re-renders. */ - widgets: WidgetDefinition[] + widgets: WidgetType[] disabledReasonFor: (action: DashboardAction) => string | null /** * Called with each edit, and with how the person saw the dashboard when they made it. Pass `view` to `applyEdit`, @@ -57,7 +57,7 @@ export interface DashboardController { history?: { canUndo: boolean; canRedo: boolean; onUndo: () => void; onRedo: () => void } } -export interface RefreshController { +export type RefreshController = { /** The interval choices besides off, in seconds. */ intervals?: number[] /** In seconds. Left out, auto refresh starts off. */ @@ -67,7 +67,7 @@ export interface RefreshController { } /** What the components read: the controller, plus what the view works out from it. */ -export interface DashboardState extends Omit { +export type DashboardState = Omit & { refresh?: AutoRefreshProps /** The dashboard as this person sees it, with the sections they closed folded. */ dashboard: Dashboard @@ -81,8 +81,8 @@ export interface DashboardState extends Omit void downloadingImage: boolean /** The tile shown on its own over the dashboard, or null. Only the screen keeps it. */ - presentedTileId: string | null - presentTile: (id: string | null) => void + slideshowTileId: string | null + showSlideshow: (id: string | null) => void } export const DashboardStateContext = createContext(null) diff --git a/products/dashboards_v2/frontend/dashboard/dashboardSchema.ts b/products/dashboards_v2/frontend/dashboard/document/dashboardSchema.ts similarity index 98% rename from products/dashboards_v2/frontend/dashboard/dashboardSchema.ts rename to products/dashboards_v2/frontend/dashboard/document/dashboardSchema.ts index 005e843834c16..7089692dfb725 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardSchema.ts +++ b/products/dashboards_v2/frontend/dashboard/document/dashboardSchema.ts @@ -84,9 +84,8 @@ export const contentWidgetPartsSchema = z.strictObject({ /** How a tile looks. A setting that is missing is on. A section has no background to change. */ export const tileAppearanceSchema = z.strictObject({ - background: z.boolean().optional(), border: z.boolean().optional(), - /** Any CSS color. The tile mixes it into its background as a tint. */ + /** Any CSS color. The tile mixes it into its background as a tint, and `transparent` removes the background. */ backgroundColor: z.string().min(1).optional(), }) @@ -181,7 +180,7 @@ export const dashboardSchema = z.strictObject({ description: z.string().optional(), /** The viewer's access to this dashboard, as v1 dashboards carry it. Missing means the project-wide level. */ user_access_level: z.enum(AccessControlLevel).optional(), - /** The time range of every widget that does not set its own. Missing means `DEFAULT_TIME_RANGE`. */ + /** The time range of every widget that does not set its own. Missing means each widget keeps its own. */ time: timeRangeSchema.optional(), /** Whether viewers see a filter bar. Missing means no, so a dashboard shows filters only once an editor allows them. */ allowFilters: z.boolean().optional(), diff --git a/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts b/products/dashboards_v2/frontend/dashboard/document/dashboardTypes.ts similarity index 83% rename from products/dashboards_v2/frontend/dashboard/dashboardTypes.ts rename to products/dashboards_v2/frontend/dashboard/document/dashboardTypes.ts index 0037a1104d685..09eded4d26e4b 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardTypes.ts +++ b/products/dashboards_v2/frontend/dashboard/document/dashboardTypes.ts @@ -48,15 +48,16 @@ export type TilePlace = z.infer export type TimeRange = z.infer -export type DashboardFilter = Omit, 'config'> & { - config: Config -} +export type DashboardFilter = Omit, 'config'> & { config: Config } + +/** A filter as saved. Its `config` is checked against its kind's `configSchema` before the kind's own code uses it. */ +export type SavedFilter = DashboardFilter['config']> export type ContentWidgetParts = z.infer export type TileAppearance = z.infer -export interface WidgetSize { +export type WidgetSize = { w: number h: number minW: number @@ -65,17 +66,20 @@ export interface WidgetSize { stackedRows?: { min: number; max: number } } -export type ContentWidget = Omit, 'config'> & { config: Config } +export type ContentWidget = Omit, 'config'> & { config: Config } + +/** A widget as saved. Its `config` is checked against its type's `configSchema` before the type's own code uses it. */ +export type SavedWidget = ContentWidget['config']> export type SectionWidget = z.infer -export type Widget = ContentWidget | SectionWidget +export type Widget = SavedWidget | SectionWidget /** A section's height follows its tiles, so `h` and `minH` only cover a new, empty one. */ export const SECTION_SIZE: WidgetSize = { w: 24, h: 6, minW: 8, minH: 3 } /** Looks up a content widget's size. Layout code takes it as an argument, so it never imports a widget. */ -export type SizeOf = (widget: ContentWidget) => WidgetSize +export type SizeOf = (widget: SavedWidget) => WidgetSize export function isSectionWidget(widget: Widget): widget is SectionWidget { return widget.type === 'section' diff --git a/products/dashboards_v2/frontend/dashboard/sharedWidgets.test.ts b/products/dashboards_v2/frontend/dashboard/document/sharedWidgets.test.ts similarity index 100% rename from products/dashboards_v2/frontend/dashboard/sharedWidgets.test.ts rename to products/dashboards_v2/frontend/dashboard/document/sharedWidgets.test.ts diff --git a/products/dashboards_v2/frontend/dashboard/sharedWidgets.ts b/products/dashboards_v2/frontend/dashboard/document/sharedWidgets.ts similarity index 100% rename from products/dashboards_v2/frontend/dashboard/sharedWidgets.ts rename to products/dashboards_v2/frontend/dashboard/document/sharedWidgets.ts diff --git a/products/dashboards_v2/frontend/dashboard/tileTree.ts b/products/dashboards_v2/frontend/dashboard/document/tileTree.ts similarity index 100% rename from products/dashboards_v2/frontend/dashboard/tileTree.ts rename to products/dashboards_v2/frontend/dashboard/document/tileTree.ts diff --git a/products/dashboards_v2/frontend/dashboard/validateDashboard.test.ts b/products/dashboards_v2/frontend/dashboard/document/validateDashboard.test.ts similarity index 89% rename from products/dashboards_v2/frontend/dashboard/validateDashboard.test.ts rename to products/dashboards_v2/frontend/dashboard/document/validateDashboard.test.ts index 1ce75d1fbf3cd..e235d812ca005 100644 --- a/products/dashboards_v2/frontend/dashboard/validateDashboard.test.ts +++ b/products/dashboards_v2/frontend/dashboard/document/validateDashboard.test.ts @@ -1,17 +1,18 @@ -import { propertyFilterSpec } from '../filters/property/propertyFilterSpec' -import { selectFilterSpec } from '../filters/select/selectFilterSpec' -import { kitchenSinkDashboard } from '../fixtures/kitchenSinkDashboard' -import { chartSpec } from '../widgets/chart/chartSpec' -import { barSpec } from '../widgets/chart/viz/bar/barSpec' -import { lineSpec } from '../widgets/chart/viz/line/lineSpec' -import { statSpec } from '../widgets/chart/viz/stat/statSpec' -import { markdownSpec } from '../widgets/markdown/markdownSpec' +import { propertyFilterSpec } from '../../filters/property/propertyFilterSpec' +import { selectFilterSpec } from '../../filters/select/selectFilterSpec' +import { kitchenSinkDashboard } from '../../fixtures/kitchenSinkDashboard' +import { chartSpec } from '../../widgets/chart/chartSpec' +import { barSpec } from '../../widgets/chart/viz/bar/barSpec' +import { lineSpec } from '../../widgets/chart/viz/line/lineSpec' +import { statSpec } from '../../widgets/chart/viz/stat/statSpec' +import { markdownSpec } from '../../widgets/markdown/markdownSpec' +import { defineWidgetSpec } from '../../widgets/widgetSpec' import { dashboardSchema } from './dashboardSchema' import type { DashboardProblem } from './validateDashboard' import { MAX_SECTION_DEPTH, validateDashboard } from './validateDashboard' // Specs only, with no components, as a CI check or an MCP tool would load them. -const SPECS = [chartSpec([statSpec, lineSpec, barSpec]), markdownSpec] +const SPECS = [defineWidgetSpec(chartSpec([statSpec, lineSpec, barSpec])), defineWidgetSpec(markdownSpec)] const FILTER_SPECS = [selectFilterSpec([]), propertyFilterSpec([])] const withTiles = (tiles: unknown[]): unknown => ({ version: 2, @@ -123,7 +124,7 @@ describe('validateDashboard', () => { config: { targets: [ { refId: 'A', query: { language: 'hogql', query: 'select 1' } }, - { refId: 'A', query: { language: 'promql', query: 'up' } }, + { refId: 'A', query: { language: 'hogql', query: 'select 2' } }, ], viz: { type: 'line' }, }, @@ -234,6 +235,20 @@ describe('validateDashboard', () => { }, expected: [{ path: 'filters[1]', message: 'Another filter already narrows this field' }], }, + { + name: 'a PromQL chart with no time range of its own', + document: withTiles([ + { + id: 'a', + place: { x: 0, y: 0, w: 12, h: 8 }, + widget: { + type: 'chart', + config: { query: { language: 'promql', query: 'up' }, viz: { type: 'line' } }, + }, + }, + ]), + expected: [{ path: 'tabs[0].tiles[0].widget.config.time', message: expect.any(String) }], + }, { name: 'a time range the picker cannot read', document: { ...(withTiles([]) as object), time: { from: 'now-7days', to: 'now' } }, diff --git a/products/dashboards_v2/frontend/dashboard/validateDashboard.ts b/products/dashboards_v2/frontend/dashboard/document/validateDashboard.ts similarity index 91% rename from products/dashboards_v2/frontend/dashboard/validateDashboard.ts rename to products/dashboards_v2/frontend/dashboard/document/validateDashboard.ts index 57e2c49158407..5899a70897832 100644 --- a/products/dashboards_v2/frontend/dashboard/validateDashboard.ts +++ b/products/dashboards_v2/frontend/dashboard/document/validateDashboard.ts @@ -1,7 +1,7 @@ import { z } from 'zod' -import { type FilterSpec, findFilterType, hasFilterOn } from '../filters/filterSpec' -import { type WidgetSpec, findWidget, sizeOfWidgets } from '../widgets/widgetSpec' +import { type FilterSpec, findFilterType, hasFilterOn } from '../../filters/filterSpec' +import { type WidgetTypeSpec, findWidget, sizeOfWidgets } from '../../widgets/widgetSpec' import { dashboardDocumentSchema, documentContentWidgetSchema, @@ -13,12 +13,12 @@ import { tileSchema, widgetRefSchema, } from './dashboardSchema' -import { type ContentWidget, type DashboardFilter, GRID } from './dashboardTypes' +import { type SavedWidget, type SavedFilter, GRID } from './dashboardTypes' // Deeper than anyone builds by hand, and shallow enough that walking a hostile document cannot overflow the stack. export const MAX_SECTION_DEPTH = 10 -export interface DashboardProblem { +export type DashboardProblem = { /** Where the problem is, such as `tabs[0].tiles[2].widget.config.query`. */ path: string message: string @@ -55,7 +55,7 @@ function issuesAt(path: string, error: z.ZodError): DashboardProblem[] { */ export function validateDashboard( document: unknown, - widgets: WidgetSpec[], + widgets: WidgetTypeSpec[], filters: FilterSpec[] = [] ): DashboardProblem[] { const parsed = dashboardHeadSchema.safeParse(document) @@ -66,7 +66,7 @@ export function validateDashboard( const sizeOf = sizeOfWidgets(widgets) const seenIds = new Set() - const checkContent = (widget: WidgetHead, path: string, schema: z.ZodType): ContentWidget | null => { + const checkContent = (widget: WidgetHead, path: string, schema: z.ZodType): SavedWidget | null => { const spec = findWidget(widgets, widget.type) if (!spec) { problems.push({ @@ -79,12 +79,11 @@ export function validateDashboard( if (!fields.success) { problems.push(...issuesAt(path, fields.error)) } - const config = spec.configSchema.safeParse(widget.config) - if (!config.success) { - problems.push(...issuesAt(`${path}.config`, config.error)) - return null + const configError = spec.configError(widget.config) + if (configError) { + problems.push(...issuesAt(`${path}.config`, configError)) } - return { ...widget, config: config.data } as ContentWidget + return fields.success && !configError ? fields.data : null } const shared = new Map( @@ -95,7 +94,7 @@ export function validateDashboard( ) // A widget's size can depend on its config, so it is only worked out from a valid one. - const checkSize = (widget: ContentWidget | null, tile: TileHead, tilePath: string): void => { + const checkSize = (widget: SavedWidget | null, tile: TileHead, tilePath: string): void => { if (!widget) { return } @@ -154,7 +153,7 @@ export function validateDashboard( } const filterIds = new Set() - const validFilters: Omit[] = [] + const validFilters: Omit[] = [] parsed.data.filters?.forEach((filter, index) => { const path = `filters[${index}]` if (filterIds.has(filter.id)) { diff --git a/products/dashboards_v2/frontend/dashboard/dashboardEdits.test.ts b/products/dashboards_v2/frontend/dashboard/edits/dashboardEdits.test.ts similarity index 98% rename from products/dashboards_v2/frontend/dashboard/dashboardEdits.test.ts rename to products/dashboards_v2/frontend/dashboard/edits/dashboardEdits.test.ts index 3af274a9f8352..885f3a37d649e 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardEdits.test.ts +++ b/products/dashboards_v2/frontend/dashboard/edits/dashboardEdits.test.ts @@ -1,7 +1,14 @@ -import { dropIntoGrid, stackTiles } from '../grid/gridTiles' +import { dropIntoGrid, stackTiles } from '../../grid/layout/gridTiles' +import { + type Dashboard, + type SizeOf, + type Tile, + type WidgetSize, + gridTabs, + isSection, +} from '../document/dashboardTypes' +import { findTile } from '../document/tileTree' import { applyEdit, settleDashboard, withFolds, withoutTiles } from './dashboardEdits' -import { type Dashboard, type SizeOf, type Tile, type WidgetSize, gridTabs, isSection } from './dashboardTypes' -import { findTile } from './tileTree' const SIZES: Record = { markdown: { w: 8, h: 8, minW: 3, minH: 4 }, diff --git a/products/dashboards_v2/frontend/dashboard/dashboardEdits.ts b/products/dashboards_v2/frontend/dashboard/edits/dashboardEdits.ts similarity index 97% rename from products/dashboards_v2/frontend/dashboard/dashboardEdits.ts rename to products/dashboards_v2/frontend/dashboard/edits/dashboardEdits.ts index 8cb2a4b1d51c8..18194a97f31c1 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardEdits.ts +++ b/products/dashboards_v2/frontend/dashboard/edits/dashboardEdits.ts @@ -1,8 +1,8 @@ -import { type FilterEdit, applyFilterEdit } from '../filters/filterEdits' -import { arrangeInColumns, contentRows, dropIntoGrid, resizeSection, settleGrid } from '../grid/gridTiles' -import { bottomOf } from '../grid/placeTiles' -import { type PresentationEdit, applyPresentationEdit } from '../presentation/presentationEdits' -import { linkTabSchema } from './dashboardSchema' +import { type FilterEdit, applyFilterEdit } from '../../filters/filterEdits' +import { arrangeInColumns, contentRows, dropIntoGrid, resizeSection, settleGrid } from '../../grid/layout/gridTiles' +import { bottomOf } from '../../grid/layout/placeTiles' +import { type PresentationEdit, applyPresentationEdit } from '../../presentation/presentationEdits' +import { linkTabSchema } from '../document/dashboardSchema' import { type Dashboard, GRID, @@ -17,8 +17,8 @@ import { isSectionWidget, widgetRef, widgetSize, -} from './dashboardTypes' -import { allTiles, changeTileEverywhere, changeTilesWhere, findTile } from './tileTree' +} from '../document/dashboardTypes' +import { allTiles, changeTileEverywhere, changeTilesWhere, findTile } from '../document/tileTree' export type LayoutEdit = /** `resized` names the tile a person resized, so a section keeps the height they chose. */ diff --git a/products/dashboards_v2/frontend/dashboard/dashboardHistory.test.ts b/products/dashboards_v2/frontend/dashboard/edits/dashboardHistory.test.ts similarity index 94% rename from products/dashboards_v2/frontend/dashboard/dashboardHistory.test.ts rename to products/dashboards_v2/frontend/dashboard/edits/dashboardHistory.test.ts index f0247f6fbaf16..8d4b73fbe6b8e 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardHistory.test.ts +++ b/products/dashboards_v2/frontend/dashboard/edits/dashboardHistory.test.ts @@ -1,5 +1,5 @@ +import type { Dashboard } from '../document/dashboardTypes' import { recordEdit, redoEdit, startHistory, undoEdit } from './dashboardHistory' -import type { Dashboard } from './dashboardTypes' const board = (title: string): Dashboard => ({ version: 2, title, tabs: [{ id: 'tab', title: 'Tab', tiles: [] }] }) diff --git a/products/dashboards_v2/frontend/dashboard/dashboardHistory.ts b/products/dashboards_v2/frontend/dashboard/edits/dashboardHistory.ts similarity index 93% rename from products/dashboards_v2/frontend/dashboard/dashboardHistory.ts rename to products/dashboards_v2/frontend/dashboard/edits/dashboardHistory.ts index 224d60b697eb4..cedd3ac9926c8 100644 --- a/products/dashboards_v2/frontend/dashboard/dashboardHistory.ts +++ b/products/dashboards_v2/frontend/dashboard/edits/dashboardHistory.ts @@ -1,9 +1,9 @@ import { objectsEqual } from 'lib/utils/objects' -import type { Dashboard } from './dashboardTypes' +import type { Dashboard } from '../document/dashboardTypes' /** Undo and redo for a dashboard. A host keeps one of these, so every host gets the same undo behavior. */ -export interface DashboardHistory { +export type DashboardHistory = { past: Dashboard[] present: Dashboard future: Dashboard[] diff --git a/products/dashboards_v2/frontend/dashboard/useDashboardHistory.ts b/products/dashboards_v2/frontend/dashboard/edits/useDashboardHistory.ts similarity index 94% rename from products/dashboards_v2/frontend/dashboard/useDashboardHistory.ts rename to products/dashboards_v2/frontend/dashboard/edits/useDashboardHistory.ts index bb8507f462b1d..5ff079586dc15 100644 --- a/products/dashboards_v2/frontend/dashboard/useDashboardHistory.ts +++ b/products/dashboards_v2/frontend/dashboard/edits/useDashboardHistory.ts @@ -1,7 +1,7 @@ import { useCallback, useState } from 'react' +import type { Dashboard } from '../document/dashboardTypes' import { type DashboardHistory, recordEdit, redoEdit, startHistory, undoEdit } from './dashboardHistory' -import type { Dashboard } from './dashboardTypes' /** Undo history for a host that keeps its dashboard in React state rather than in a kea logic. */ export function useDashboardHistory(initial: Dashboard): { diff --git a/products/dashboards_v2/frontend/dashboard/useStableController.ts b/products/dashboards_v2/frontend/dashboard/useStableController.ts new file mode 100644 index 0000000000000..39ed9e167c098 --- /dev/null +++ b/products/dashboards_v2/frontend/dashboard/useStableController.ts @@ -0,0 +1,84 @@ +import { useCallback, useLayoutEffect, useMemo, useRef } from 'react' + +import type { DashboardController, RefreshController } from './dashboardContext' + +/** + * Builds the controller from a host's props, so the host can pass inline event handlers and a new `history` or + * `refresh` object on each render without re-rendering every tile. Functions that decide what renders + * (`disabledReasonFor`, `tileActions`, `dashboardActions`) are used as given, because a new one has to re-render. + */ +export function useStableController(props: DashboardController): DashboardController { + const latest = useRef(props) + useLayoutEffect(() => { + latest.current = props + }) + + const onEdit = useCallback((edit, view) => latest.current.onEdit(edit, view), []) + const onActiveTabChange = useCallback((tabId: string) => latest.current.onActiveTabChange(tabId), []) + + const hasHistory = !!props.history + const canUndo = props.history?.canUndo ?? false + const canRedo = props.history?.canRedo ?? false + const history = useMemo( + () => + hasHistory + ? { + canUndo, + canRedo, + onUndo: () => latest.current.history?.onUndo(), + onRedo: () => latest.current.history?.onRedo(), + } + : undefined, + [hasHistory, canUndo, canRedo] + ) + + const hasRefresh = !!props.refresh + const { initialInterval, refreshing } = props.refresh ?? {} + // Compared by value, so a host can write the intervals inline. + const intervalsKey = props.refresh?.intervals?.join(',') + const refresh = useMemo( + () => + hasRefresh + ? { + intervals: intervalsKey ? intervalsKey.split(',').map(Number) : undefined, + initialInterval, + refreshing, + onRefresh: () => latest.current.refresh?.onRefresh?.(), + } + : undefined, + [hasRefresh, intervalsKey, initialInterval, refreshing] + ) + + const { dashboard, activeTabId, widgets, disabledReasonFor, tileActions, dashboardActions, filters, timeRange } = + props + return useMemo( + () => ({ + dashboard, + activeTabId, + widgets, + disabledReasonFor, + onEdit, + onActiveTabChange, + tileActions, + dashboardActions, + refresh, + filters, + timeRange, + history, + }), + [ + dashboard, + activeTabId, + widgets, + disabledReasonFor, + onEdit, + onActiveTabChange, + tileActions, + dashboardActions, + refresh, + filters, + timeRange, + history, + ] + ) +} diff --git a/products/dashboards_v2/frontend/data/queryBatchLines.ts b/products/dashboards_v2/frontend/data/queryBatchLines.ts index 8ffc71f3da0af..a613235372d04 100644 --- a/products/dashboards_v2/frontend/data/queryBatchLines.ts +++ b/products/dashboards_v2/frontend/data/queryBatchLines.ts @@ -4,7 +4,7 @@ * `products/dashboards/backend/v2/frames.py` (`frame_json`). */ -export interface FrameField { +export type FrameField = { name: string type: 'time' | 'number' | 'string' | 'boolean' | 'other' /** A time field holds epoch milliseconds. A number field holds null for a gap. */ @@ -13,7 +13,7 @@ export interface FrameField { labels?: Record } -export interface Frame { +export type Frame = { name: string | null labels: Record fields: FrameField[] @@ -21,7 +21,7 @@ export interface Frame { hash: string } -export interface QueryBatchLine { +export type QueryBatchLine = { i: number refId?: string error?: string diff --git a/products/dashboards_v2/frontend/data/queryBatchRunner.test.ts b/products/dashboards_v2/frontend/data/queryBatchRunner.test.ts index 15b0f9d1d7172..d15fea2225d82 100644 --- a/products/dashboards_v2/frontend/data/queryBatchRunner.test.ts +++ b/products/dashboards_v2/frontend/data/queryBatchRunner.test.ts @@ -21,7 +21,7 @@ const LATENCY: QueryRequest = { } const DAY_1 = Date.UTC(2026, 10, 1) -interface OpenStream { +type OpenStream = { body: any push: (text: string) => void close: () => void diff --git a/products/dashboards_v2/frontend/data/queryBatchRunner.ts b/products/dashboards_v2/frontend/data/queryBatchRunner.ts index d903f6e273fae..9c18dcf80affe 100644 --- a/products/dashboards_v2/frontend/data/queryBatchRunner.ts +++ b/products/dashboards_v2/frontend/data/queryBatchRunner.ts @@ -3,6 +3,7 @@ import { getCookie } from 'lib/api' import { getDashboardV2QueryBatchCreateUrl } from 'products/dashboards/frontend/generated/api' import type { QueryBatchRequestApi } from 'products/dashboards/frontend/generated/api.schemas' +import type { TimeRange } from '../dashboard/document/dashboardTypes' import type { DataFrame, QueryRequest, QueryResult, RunQuery } from '../widgets/chart/vizTypes' import { type Frame, type QueryBatchLine, readNdjson } from './queryBatchLines' import { QueryBatchTimer, startBoardLoad } from './queryBatchTiming' @@ -18,7 +19,7 @@ const COALESCE_MS = 30 // `_BUSY` in `products/dashboards/backend/v2/query_batch.py`. export const BUSY_ERROR = 'Too many dashboards are loading at once. Try again shortly.' -interface Pending { +type Pending = { request: QueryRequest resolve: (result: QueryResult) => void reject: (error: Error) => void @@ -32,8 +33,12 @@ export interface QueryBatchRunnerOptions { context?: () => Record } +// TODO(2026-11-25): Send no time when the request has none, once the query batch endpoint accepts that. +// The endpoint requires a time range on every query, so a query with no range of its own here gets this one. +const UNTIL_BATCH_ACCEPTS_NO_TIME: TimeRange = { from: 'now-7d', to: 'now' } + function batchTarget(request: QueryRequest, index: number): QueryBatchRequestApi['queries'][number] { - const { query, time, legend } = request + const { query, time = UNTIL_BATCH_ACCEPTS_NO_TIME, legend } = request const refId = String(index) const target: QueryBatchRequestApi['queries'][number]['target'] = query.language === 'hogql' || query.language === 'promql' || query.language === 'logql' diff --git a/products/dashboards_v2/frontend/filters/AddFilterMenu.tsx b/products/dashboards_v2/frontend/filters/bar/AddFilterMenu.tsx similarity index 87% rename from products/dashboards_v2/frontend/filters/AddFilterMenu.tsx rename to products/dashboards_v2/frontend/filters/bar/AddFilterMenu.tsx index 5371d5c5872f6..e3de7c4bf20ea 100644 --- a/products/dashboards_v2/frontend/filters/AddFilterMenu.tsx +++ b/products/dashboards_v2/frontend/filters/bar/AddFilterMenu.tsx @@ -14,27 +14,27 @@ import { PopoverContent, } from '@posthog/quill' -import type { DashboardFilter } from '../dashboard/dashboardTypes' -import type { FilterDefinition } from './filterDefinition' -import { hasFilterOn } from './filterSpec' +import type { SavedFilter } from '../../dashboard/document/dashboardTypes' +import type { FilterDefinition } from '../filterDefinition' +import { hasFilterOn } from '../filterSpec' export function AddFilterMenu({ filters, types, onAdd, }: { - filters: DashboardFilter[] + filters: SavedFilter[] types: FilterDefinition[] - onAdd: (filter: Omit) => void + onAdd: (filter: Omit) => void }): JSX.Element | null { const triggerRef = useRef(null) const [picking, setPicking] = useState(null) - const items = types.flatMap(({ type, addMenuItems }) => addMenuItems.map((item) => ({ type, ...item }))) + const items = types.flatMap(({ type, addFilterOptions }) => addFilterOptions.map((item) => ({ type, ...item }))) const pickers = types.filter((type) => type.Picker && type.pickerLabel) if (items.length === 0 && pickers.length === 0) { return null } - const disabledReason = (filter: Omit): string | undefined => + const disabledReason = (filter: Omit): string | undefined => hasFilterOn(filters, filter, types) ? 'Already added' : undefined const Picker = picking?.Picker return ( diff --git a/products/dashboards_v2/frontend/filters/FilterBar.tsx b/products/dashboards_v2/frontend/filters/bar/FilterBar.tsx similarity index 92% rename from products/dashboards_v2/frontend/filters/FilterBar.tsx rename to products/dashboards_v2/frontend/filters/bar/FilterBar.tsx index 01582af1bb6a6..d37e9d7774192 100644 --- a/products/dashboards_v2/frontend/filters/FilterBar.tsx +++ b/products/dashboards_v2/frontend/filters/bar/FilterBar.tsx @@ -3,18 +3,18 @@ import { useLayoutEffect, useRef, useState } from 'react' import { IconChevronDown, IconFilter } from '@posthog/icons' import { Button, Popover, PopoverContent, PopoverTrigger, Separator, Text } from '@posthog/quill' -import type { DashboardFilter } from '../dashboard/dashboardTypes' +import type { SavedFilter } from '../../dashboard/document/dashboardTypes' +import type { FilterDefinition } from '../filterDefinition' +import { activeFirst, filterValue } from '../filtersContext' import { AddFilterMenu } from './AddFilterMenu' -import type { FilterDefinition } from './filterDefinition' import { FilterPill } from './FilterPill' -import { activeFirst, filterValue } from './filtersContext' -export interface FilterBarProps { - filters: DashboardFilter[] +export type FilterBarProps = { + filters: SavedFilter[] types: FilterDefinition[] values: Record onValueChange: (id: string, value: unknown) => void - onAdd?: (filter: Omit) => void + onAdd?: (filter: Omit) => void onRemove?: (id: string) => void } @@ -53,7 +53,7 @@ export function FilterBar({ return null } - const pill = (filter: DashboardFilter): JSX.Element => ( + const pill = (filter: SavedFilter): JSX.Element => ( 1 ? `${values[0]} +${values.length - 1}` : (values[0] ?? '') } -export interface FilterControlProps { +export type FilterControlProps = { filter: DashboardFilter value: Value | undefined onChange: (value: Value | undefined) => void @@ -17,12 +17,12 @@ export interface FilterControlProps { defaultOpen?: boolean } -export interface FilterDefinition extends FilterSpec { +export type FilterDefinition = FilterSpec & { Control: ComponentType> Picker?: ComponentType> } -export interface FilterPickerProps { +export type FilterPickerProps = { onPick: (filter: Omit, 'id'>) => void onClose: () => void } diff --git a/products/dashboards_v2/frontend/filters/filterEdits.ts b/products/dashboards_v2/frontend/filters/filterEdits.ts index 9c8dff00ae5a9..e6c427a3121bc 100644 --- a/products/dashboards_v2/frontend/filters/filterEdits.ts +++ b/products/dashboards_v2/frontend/filters/filterEdits.ts @@ -1,14 +1,14 @@ -import type { Dashboard, DashboardFilter } from '../dashboard/dashboardTypes' +import type { Dashboard, SavedFilter } from '../dashboard/document/dashboardTypes' /** Edits to which filters a dashboard has. A filter's value is not an edit: each viewer picks their own. */ export type FilterEdit = | { edit: 'setAllowFilters'; allowed: boolean } - | { edit: 'addFilter'; filter: Omit } + | { edit: 'addFilter'; filter: Omit } | { edit: 'removeFilter'; id: string } // Random rather than counted: a viewer's value is kept by id, so a reused id would hand a removed filter's value to // the filter added after it. -function newFilterId(filters: DashboardFilter[]): string { +function newFilterId(filters: SavedFilter[]): string { const taken = new Set(filters.map((filter) => filter.id)) let id: string do { diff --git a/products/dashboards_v2/frontend/filters/filterSpec.ts b/products/dashboards_v2/frontend/filters/filterSpec.ts index 84de7fc2674da..d80cc78d6f172 100644 --- a/products/dashboards_v2/frontend/filters/filterSpec.ts +++ b/products/dashboards_v2/frontend/filters/filterSpec.ts @@ -1,8 +1,8 @@ import type { z } from 'zod' -import type { DashboardFilter } from '../dashboard/dashboardTypes' +import type { DashboardFilter, SavedFilter } from '../dashboard/document/dashboardTypes' -export interface AddFilterMenuItem { +export type AddFilterOption = { label: string create: () => Omit, 'id'> } @@ -11,9 +11,9 @@ export interface AddFilterMenuItem { * Everything about a kind of filter except how its control renders. It is plain data with no React, so code outside * the browser can load it, such as `validateDashboard`. */ -export interface FilterSpec { +export type FilterSpec = { type: string - addMenuItems: AddFilterMenuItem[] + addFilterOptions: AddFilterOption[] pickerLabel?: string configSchema: z.ZodType /** @@ -24,11 +24,11 @@ export interface FilterSpec { } export function hasFilterOn( - filters: Omit[], - filter: Omit, + filters: Omit[], + filter: Omit, types: FilterSpec[] ): boolean { - const field = (candidate: Omit): string => { + const field = (candidate: Omit): string => { const spec = findFilterType(types, candidate.type) return spec?.fieldOf ? spec.fieldOf(candidate.config) : JSON.stringify(candidate.config) } diff --git a/products/dashboards_v2/frontend/filters/filtersContext.ts b/products/dashboards_v2/frontend/filters/filtersContext.ts index e175cd9fd0c20..38059497554ab 100644 --- a/products/dashboards_v2/frontend/filters/filtersContext.ts +++ b/products/dashboards_v2/frontend/filters/filtersContext.ts @@ -1,18 +1,17 @@ import { createContext } from 'react' -import type { DashboardFilter, TimeRange } from '../dashboard/dashboardTypes' +import type { SavedFilter, TimeRange } from '../dashboard/document/dashboardTypes' -export interface AppliedFilter { +export type AppliedFilter = { id: string type: string config: Config value: Value } -export const DEFAULT_TIME_RANGE: TimeRange = { from: 'now-7d', to: 'now' } - -export interface ActiveFilters { - time: TimeRange +export type ActiveFilters = { + /** Overrides each widget's own time range. Left out, every widget keeps its own. */ + time?: TimeRange filters: AppliedFilter[] } @@ -20,7 +19,7 @@ export interface ActiveFilters { * The time range and filters that apply to the widgets inside it. `DashboardView` provides the dashboard's, and a host * that renders a widget on its own can provide its own, so widgets never read the dashboard to get them. */ -export const FiltersContext = createContext({ time: DEFAULT_TIME_RANGE, filters: [] }) +export const FiltersContext = createContext({ filters: [] }) /** A filter's value, read as an own property, so an id such as `constructor` never picks up an inherited one. */ export function filterValue(values: Record, id: string): unknown { @@ -28,7 +27,7 @@ export function filterValue(values: Record, id: string): unknow } /** The filters that have a value, in the dashboard's order. A value left over from a removed filter is dropped. */ -export function appliedFilters(filters: DashboardFilter[], values: Record): AppliedFilter[] { +export function appliedFilters(filters: SavedFilter[], values: Record): AppliedFilter[] { return filters.flatMap(({ id, type, config }) => { const value = filterValue(values, id) return value === undefined ? [] : [{ id, type, config, value }] @@ -36,7 +35,7 @@ export function appliedFilters(filters: DashboardFilter[], values: Record): DashboardFilter[] { +export function activeFirst(filters: SavedFilter[], values: Record): SavedFilter[] { return [...filters].sort( (a, b) => Number(filterValue(values, b.id) !== undefined) - Number(filterValue(values, a.id) !== undefined) ) diff --git a/products/dashboards_v2/frontend/filters/FieldSearch.tsx b/products/dashboards_v2/frontend/filters/pickers/FieldSearch.tsx similarity index 97% rename from products/dashboards_v2/frontend/filters/FieldSearch.tsx rename to products/dashboards_v2/frontend/filters/pickers/FieldSearch.tsx index 28a7aaa7de5e9..6bc83e8567238 100644 --- a/products/dashboards_v2/frontend/filters/FieldSearch.tsx +++ b/products/dashboards_v2/frontend/filters/pickers/FieldSearch.tsx @@ -11,12 +11,12 @@ import { import { type OptionsLoader, useSearchedOptions } from './useSearchedOptions' -export interface FieldOption { +export type FieldOption = { key: string label: string } -export interface FieldSearchProps