Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(dashboards): unify filter and SQL variable changes (#94637)

Matt Puaf88d2e7f1993
diff --git a/.agents/skills/managing-dashboards/SKILL.md b/.agents/skills/managing-dashboards/SKILL.md
index e46e493c5243..3f21e8656519 100644
--- a/.agents/skills/managing-dashboards/SKILL.md
+++ b/.agents/skills/managing-dashboards/SKILL.md
@@ -71,15 +71,16 @@ State these decisions before implementation.
Use this checklist as a design gate. Read the linked reference when an item applies.
-| Area | Check |
-| ---------------------- | ------------------------------------------------------------------------------------------- |
-| Access | [RBAC, sharing, and embeds](references/access-sharing-and-embeds.md) |
-| Filter state | [Filters, variables, and tile overrides](references/filters-variables-and-overrides.md) |
-| Data and scale | [Querying, caching, and scale](references/querying-caching-and-scale.md) |
-| Layout and templates | [Layout, responsive behavior, and templates](references/layout-responsive-and-templates.md) |
-| Backend and operations | [Backend contracts and operations](references/backend-contracts-and-operations.md) |
-| Feature lifecycle | [Feature lifecycle and rollout](references/feature-lifecycle-and-rollout.md) |
-| New state or relation | [Data models and collaboration](references/data-models-and-collaboration.md) |
+| Area | Check |
+| ---------------------- | ----------------------------------------------------------------------------------------------------- |
+| Access | [RBAC, sharing, and embeds](references/access-sharing-and-embeds.md) |
+| Filter state | [Filters, variables, and tile overrides](references/filters-variables-and-overrides.md) |
+| Configuration editing | [Dashboard configuration editing and URL overrides](references/filter-editing-and-temporary-views.md) |
+| Data and scale | [Querying, caching, and scale](references/querying-caching-and-scale.md) |
+| Layout and templates | [Layout, responsive behavior, and templates](references/layout-responsive-and-templates.md) |
+| Backend and operations | [Backend contracts and operations](references/backend-contracts-and-operations.md) |
+| Feature lifecycle | [Feature lifecycle and rollout](references/feature-lifecycle-and-rollout.md) |
+| New state or relation | [Data models and collaboration](references/data-models-and-collaboration.md) |
## 4. Implement across layers
@@ -91,6 +92,8 @@ Use this checklist as a design gate. Read the linked reference when an item appl
6. Keep grid updates stable during drag, resize, and tile refresh. Avoid a full grid relayout for each tile result.
7. Add observability when a change creates a new loading, query, cache, access, or refresh path.
8. For list-only state, render controls only where that state applies.
+9. After a selector rename, search every dashboard consumer and test for the old name. Then run TypeScript.
+10. Keep dashboard mutation actions on the authenticated dashboard placement unless another placement has an explicit contract.
## 5. Test the boundary, not only the happy path
diff --git a/.agents/skills/managing-dashboards/references/filter-editing-and-temporary-views.md b/.agents/skills/managing-dashboards/references/filter-editing-and-temporary-views.md
new file mode 100644
index 000000000000..24c4772d856b
--- /dev/null
+++ b/.agents/skills/managing-dashboards/references/filter-editing-and-temporary-views.md
@@ -0,0 +1,212 @@
+# Dashboard settings editing and URL overrides
+
+Use this reference when a dashboard change affects filters, SQL variables, previews, URL overrides, saving, or layout editing.
+
+## Settings model
+
+Treat dashboard filters and SQL variables as one editable settings object.
+
+```ts
+type DashboardSettings = {
+ filters: DashboardFilter
+ variables: Record<string, HogQLVariable>
+}
+```
+
+Use three explicit sources:
+
+| Source | Contents | Lifetime |
+| -------------------- | --------------------------------------------- | ------------------------------------ |
+| Saved settings | `persisted_filters` and `persisted_variables` | Persists for every applicable viewer |
+| Initial URL override | `query_filters` and `query_variables` | Applies on load and survives reloads |
+| User draft | Current filter and variable edits | Local until save or discard |
+
+Resolve the current settings in this order:
+
+```text
+saved settings
+→ initial URL override
+→ user draft
+```
+
+- Freeze the initial URL override against the URL writes that the filter and variable controls make after the dashboard opens.
+- Browser history is the exception. On a `POP`, rebuild the draft from the saved settings and the popped URL. Read `query_filters` and `query_variables` together. A `POP` that carries neither parameter restores the saved settings.
+- Do not infer settings state from `dashboardMode`, `hasIntermittentFilters`, or `filterEditModeActive`.
+- Do not combine separate temporary-filter and temporary-variable conditions in UI components.
+- Keep embedded context and tile overrides outside this configuration.
+
+## Visible states
+
+Derive exactly one visible state from the effective configuration:
+
+| State | Condition | Required treatment |
+| ---------------- | -------------------------------------------------------------- | ------------------------------------------------------------- |
+| `unsavedChanges` | An initial URL override or user draft changes the saved values | Show one count, one change list, and save or discard actions. |
+| `saved` | The current settings equal the saved dashboard settings | Show no settings status. |
+
+- A filter or SQL-variable edit creates one user draft from the effective configuration.
+- Show initial URL overrides through the same unsaved treatment as user edits.
+- Do not show a separate temporary treatment.
+- The first edit includes the effective override values in the user draft.
+- UI code must consume the single derived visible state.
+- UI code must not reconstruct state from several selector flags.
+- Compare SQL variables by their displayed meaning. Treat absent `isNull` and `isNull: false` as equal.
+- Compare a missing saved override with the variable default. Do not report a default selection as a change.
+- Preserve explicit SQL `null`. Do not convert it to the string `"null"` in settings or change comparison.
+
+## Actions and transitions
+
+Use explicit actions for each boundary:
+
+- `previewDashboardChanges` updates dashboard data only.
+- `saveDashboardChanges` sends one dashboard update with `filters` and `variables`.
+- `discardDashboardChanges` clears the user draft and restores the saved configuration.
+- `saveLayoutChanges` persists layout changes only.
+- `discardLayoutChanges` restores layout changes only.
+
+Save behavior:
+
+1. Persist the final current settings.
+2. Include both `filters` and `variables` in one dashboard update.
+3. Clear `query_filters` and `query_variables`.
+4. Clear the initial URL override and user draft.
+5. Confirm that reload shows the saved settings.
+6. If automatic preview is disabled, refresh all affected tiles after the save succeeds.
+
+Discard behavior:
+
+1. Clear the user draft.
+2. Clear `query_filters` and `query_variables`.
+3. Clear the initial URL override.
+4. Restore the saved configuration.
+5. Never restore the initial temporary view.
+
+- Do not use `saveDashboardFilters` for combined changes.
+- Do not use `saveEditModeChanges` for SQL-variable-only changes.
+- Filter and variable controls always update their URL parameters after the draft exists.
+- Remove a URL variable when the selected value equals its default.
+- Map action payload field names to URL filter field names explicitly. Date actions use camel case. URL filters use snake case.
+- Above the automatic-preview threshold, Preview updates data without clearing or saving the draft. URL overrides persist the draft across reloads.
+- A successful initial load with URL overrides above the automatic-preview threshold is an active preview.
+- Any later filter or variable edit invalidates the prior Preview result and returns the Preview action to its idle state.
+- Disable Previewing while the dashboard data shows the current unsaved settings. Do not use a loading spinner for this state.
+
+## Unified change list
+
+Build one `DashboardSettingsChange[]` for filters and SQL variables.
+
+Each displayed row must include:
+
+- A label.
+- The old saved or default value.
+- The new value.
+- A `new`, `changed`, or `removed` status.
+
+Additional requirements:
+
+- The displayed count must equal the number of displayed rows.
+- Include every filter and variable change when both types exist.
+- Render multi-value changes as individual pills.
+- Use generic configuration copy when both types exist.
+- Make the save target explicit. Saving changes the dashboard default for every viewer.
+- Make the preview target explicit. Preview changes only the current data view.
+
+## Layout independence
+
+- Entering layout mode must preserve the dashboard configuration draft.
+- Saving layout must preserve the dashboard configuration draft.
+- Discarding layout must preserve the dashboard configuration draft.
+- Saving dashboard changes must preserve the layout draft.
+- Discarding dashboard changes must preserve the layout draft.
+- Filter and variable controls remain editable during layout editing.
+- Dashboard settings actions remain available during layout editing.
+
+## Other filter boundaries
+
+- `setExternalFilters` supplies embedded context from the surface that hosts the dashboard. It is not limited to one placement. `DashboardPlacement.Group` and `DashboardPlacement.Builtin` both use it today.
+- Search for every caller of `setExternalFilters` before you change its contract.
+- Embedded context must not enter the user draft, change count, change list, or save payload.
+- `tile.filters_overrides` remains a separate persisted tile action.
+- Shared-token requests ignore URL filter and variable overrides.
+- Do not claim that URL overrides affect data where the request path ignores them.
+- Render save, discard, and Preview only for `DashboardPlacement.Dashboard`.
+- Never render these mutation actions for public, embedded, export, built-in, or product-owned placements.
+- Other placements can render read-only filters or variables only when their contract supports them.
+
+## UI requirements
+
+- Show SQL-variable controls before the advanced-options ellipsis.
+- Keep the status visible at narrow dashboard widths.
+- Move actions into a dropdown at the defined narrow container breakpoint.
+- Change Preview to Previewing while the dashboard data shows the current unsaved settings.
+- Disable Previewing without a spinner.
+- Show save and discard labels that describe dashboard settings changes.
+
+## Required regression checks
+
+Use one parameterized Kea logic scenario suite for configuration transitions:
+
+1. Edit one filter. Save it. Confirm that reload shows the saved filter.
+2. Edit one SQL variable. Save it. Confirm that reload shows the saved variable.
+3. Edit a filter and three SQL variables. Confirm one count, one list, value transitions, and one save.
+4. Open a URL override view. Confirm the unsaved state. Edit a filter. Confirm one combined draft.
+5. Open a URL override view. Confirm the unsaved state. Edit a SQL variable. Confirm one combined draft.
+6. Edit filters and variables from a URL override view. Discard. Confirm that saved state returns.
+7. Edit filters and variables from a URL override view. Save. Confirm that the final state persists.
+8. Above the automatic-preview threshold, preview filters and variables. Confirm that preview changes data only and URL overrides survive reload.
+9. Check the complete layout independence matrix for save and discard actions.
+10. Save without Preview above the threshold. Confirm that all affected tiles refresh with the saved settings.
+11. Edit a SQL variable during or after Preview. Confirm that Preview returns to its idle, enabled state.
+12. Select a SQL variable default with absent and false `isNull`. Confirm no change row and no URL override.
+13. Set every filter type and a SQL variable. Confirm that action fields map to the URL and survive reload.
+
+Use DOM tests only for these visible outcomes:
+
+- URL overrides and user edits show the same unsaved pill.
+- Count matches visible popover rows.
+- Save and discard labels and actions.
+- Narrow action dropdown.
+- SQL-variable controls appear before the advanced-options ellipsis.
+- Save, discard, and Preview never appear outside `DashboardPlacement.Dashboard`.
+
+Do not keep tests that only assert selector flags, action order, a temporary variable, or a dirty filter.
+
+Also check these separate boundaries:
+
+- Embedded contextual filters never enter dashboard configuration changes.
+- Tile overrides never enter dashboard configuration changes.
+- Shared, public, export, feature-flag, DataOps, group, and built-in placements match their override support.
+- Browser history and direct URL edits resolve to the correct effective configuration. Cover a filter-only, a variable-only, and a combined history entry.
+- Search for every removed or renamed selector across dashboard items, menus, panels, exports, and tests.
+- Run TypeScript after selector changes. Do not stop after the logic tests pass.
+- Check the insight-colors modal. Its cancel and save paths must not change the settings draft.
+
+## Manual reproduction
+
+Use one local dashboard with at least two working insight tiles and three SQL variables.
+
+1. Set `dashboard-auto-preview-limit` above the insight-tile count. Edit filters and variables. Confirm immediate preview and one draft.
+2. Set the limit at or below the insight-tile count. Edit filters and variables. Confirm that the URL changes without an automatic preview.
+3. Reload the URL override view. Confirm that the dashboard data uses the overrides and the status shows Previewing.
+4. Select Preview. Confirm that Preview updates data without saving the draft.
+5. Save combined changes. Confirm both URL parameters clear. Reload and confirm the saved values.
+6. Open with both URL override parameters. Make combined edits. Discard and confirm the original saved values return.
+7. Create both dashboard configuration and layout drafts. Run each save and discard action. Confirm that each draft remains independent.
+
+## Storybook coverage
+
+- Keep dashboard stories under `products/dashboards/frontend`, not `scenes`.
+- Keep one main filter-bar story with controls for saved and unsaved state, read-only access, narrow width, filter changes, and URL overrides.
+- Include date, properties, breakdown, interval, test-account, and SQL-variable changes in both change controls.
+- Keep one separate story for the unsaved-changes popover.
+- Do not create a dashboard filter-bar story for embedded context when the embedding surface owns that context.
+
+## Source files
+
+- `frontend/src/scenes/dashboard/DashboardFilters.tsx`
+- `frontend/src/scenes/dashboard/DashboardUnsavedChangesIndicator.tsx`
+- `frontend/src/scenes/dashboard/dashboardChanges.ts`
+- `frontend/src/scenes/dashboard/dashboardLogic.tsx`
+- `frontend/src/scenes/dashboard/DashboardItems.tsx`
+- `frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx`
+- `frontend/src/scenes/dashboard/DashboardScenePanel.tsx`
diff --git a/.agents/skills/managing-dashboards/references/filters-variables-and-overrides.md b/.agents/skills/managing-dashboards/references/filters-variables-and-overrides.md
index 673615e312da..75bb9d29f6d1 100644
--- a/.agents/skills/managing-dashboards/references/filters-variables-and-overrides.md
+++ b/.agents/skills/managing-dashboards/references/filters-variables-and-overrides.md
@@ -13,8 +13,24 @@ Dashboard query behavior can combine several layers of state.
| Tile filter override | Yes | One insight tile |
| Quick filters | Yes, by ID | Dashboard filter controls |
+## Entry sources
+
+| Source | Mechanism | Required boundary |
+| --------------------- | --------------------------------------------- | ------------------------------------------------------------------------- |
+| URL filter override | `query_filters` | Current dashboard view only. It joins the initial configuration override. |
+| URL variable override | `query_variables` | Current dashboard view only. It joins the initial configuration override. |
+| Embedded context | `setExternalFilters` | Current embedded view only. Never persist it as dashboard filters. |
+| Tile override | `tile.filters_overrides` | Persist only on its tile. Never enter dashboard filter state. |
+| Saved dashboard state | `persisted_filters` and `persisted_variables` | Dashboard default for every applicable viewer. |
+
+Check pasted links, direct URL edits, browser history navigation, filter controls, variable controls, and embedded placements. A URL parameter can exist on a route that ignores overrides. In that case, do not show a state treatment that claims the parameter changes data.
+
Before you change one layer, define its precedence with every other affected layer. Do not infer precedence from the UI.
+For dashboard editing, treat saved filters and variables as one settings object. Treat both URL parameters as one initial override. A filter or variable edit creates one user draft. Resolve saved settings, then initial override, then user draft.
+
+Show initial URL overrides through the same unsaved treatment as user edits. Do not create a separate temporary state or treatment.
+
## Required checks
- Use `normalize_dashboard_filters_properties` for persisted dashboard property filters.
@@ -24,6 +40,17 @@ Before you change one layer, define its precedence with every other affected lay
- Preserve tile `filters_overrides` when you duplicate, copy, move, serialize, or create from a template.
- Check tiles that opt out of dashboard filters separately from tiles that add their own filters.
- Apply the same resolved state to dashboard detail, `run_insights`, streaming, export, and the frontend preview.
+- Keep external embedded filters out of the dashboard configuration draft, change details, and save payload.
+- Combine filter and SQL-variable changes in one change list and one count.
+- Save filters and variables through one dashboard update.
+- Clear both URL override parameters on dashboard configuration save or discard.
+- Compare SQL values by value and null meaning. Treat absent `isNull` and `isNull: false` as equal.
+- Remove a no-op URL variable when a person selects its default value.
+- Apply current draft variables to controls, tile requests, insight links, exports, and scene actions.
+- Map camel-case date actions to snake-case URL fields at the router boundary.
+- Invalidate an old Preview state after any later filter or variable edit.
+- Refresh affected tiles after a save when automatic preview did not apply the draft.
+- Render settings mutation actions only on the authenticated dashboard placement.
## Failure cases
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 8ea091f9e896..00b48c69ba31 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5444,6 +5444,14 @@ snapshots:
hash: v1.k794b7964.e0388f165831a8b73632873a43ccc0668057db62a62e84c8bd19ad28d14bb011.c66ZeT4g4B2NMURw6V91iBT-AUnw7Tf6EtiY5Vr_-cY
products-dashboards-dashboard-widgets-widgetcard--locked--light:
hash: v1.k794b7964.5b137c02f2365806484425bc25fe4c896fc99edbac07caff03503ed3222da251._dt53kAV0UsgvHveL2zwjSHjc2D-p2LO9mZunqv7f5c
+ products-dashboards-filter-bar--filter-bar--dark:
+ hash: v1.k794b7964.3e359ae2789f6fe48dc466b11edfe41b10518ae0d3f4312a29ffede40561fec2.R-hbmu9T9335KUf--XuCkZADUv8EQNFm9tVTN5pj3QI
+ products-dashboards-filter-bar--filter-bar--light:
+ hash: v1.k794b7964.a6a8399a1a401981b01e8e557a587bb82fc0989ce02aeae2cbb49a089d7513cf.HHOpDzXqVV3rFxGuB4-puIDQwV16GN6VY7u5pIVUe7k
+ products-dashboards-filter-bar--unsaved-changes-popover--dark:
+ hash: v1.k794b7964.4106fa5842ea42b9e7da0fff67a5e521a482211f16a704e27908ef9b7aaaa990.ALtMI0hIBMTlNfGdQR12at_eXuEDwYMwn7RIb6jZ0RU
+ products-dashboards-filter-bar--unsaved-changes-popover--light:
+ hash: v1.k794b7964.50eb814e6a44f0bb8956a12ad4cd68663b1723b4948389e04e918b8dbaddde23.fdkQTJhzuxWCziSIvvwa-nQc8220y9-AJw9K5g99ct0
products-dashboards-saved-views-manage--default--dark:
hash: v1.k794b7964.5a3fc6cafb3bfa5752b3707e93dd12027d95b7d5db139448c4431e84c64e5af6.uC3oT8cgBWIvwkXeqy_yiNtuoH3JxOhrSxR2bdhxzHw
products-dashboards-saved-views-manage--default--light:
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 002fe5fad613..fd7146a3d1c7 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -87,7 +87,6 @@ export enum DashboardEventSource {
DashboardHeaderSaveDashboard = 'dashboard_header_save_dashboard',
DashboardHeaderDiscardChanges = 'dashboard_header_discard_changes',
DashboardHeaderExitFullscreen = 'dashboard_header_exit_fullscreen',
- DashboardHeaderOverridesBanner = 'dashboard_header_overrides_banner',
Hotkey = 'hotkey',
InputEnter = 'input_enter',
Toast = 'toast',
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index 8cb87533a192..3994255f0016 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -29,7 +29,6 @@ import { teamLogic } from '../teamLogic'
import { AddInsightToDashboardModal } from './addInsightToDashboardModal/AddInsightToDashboardModal'
import { addInsightToDashboardLogic } from './addInsightToDashboardModalLogic'
import { DashboardHeader } from './DashboardHeader'
-import { DashboardOverridesBanner } from './DashboardOverridesBanner'
import { DashboardPublicAccessBanner } from './DashboardPublicAccessBanner'
import { DashboardRetentionBanner } from './DashboardRetentionBanner'
import { dashboardSubscribeNudgeLogic } from './dashboardSubscribeNudgeLogic'
@@ -188,7 +187,6 @@ function DashboardScene({
'-mt-4': placement == DashboardPlacement.ProjectHomepage,
})}
>
- <DashboardOverridesBanner />
<DashboardRetentionBanner />
<SceneStickyBar showBorderBottom={false} className="flex gap-2 space-y-0">
diff --git a/frontend/src/scenes/dashboard/DashboardEditBar.tsx b/frontend/src/scenes/dashboard/DashboardEditBar.tsx
index 395dda38c50f..40602a2e8afd 100644
--- a/frontend/src/scenes/dashboard/DashboardEditBar.tsx
+++ b/frontend/src/scenes/dashboard/DashboardEditBar.tsx
@@ -20,7 +20,7 @@ import { Scene } from 'scenes/sceneTypes'
import { groupsModel } from '~/models/groupsModel'
import { VariablesForDashboard } from '~/queries/nodes/DataVisualization/Components/Variables/Variables'
import { BreakdownFilter, NodeKind } from '~/queries/schema/schema-general'
-import { DashboardMode, InsightLogicProps, IntervalType } from '~/types'
+import { InsightLogicProps, IntervalType } from '~/types'
interface DashboardEditBarProps {
showDateFilter?: boolean
@@ -28,8 +28,8 @@ interface DashboardEditBarProps {
}
export function DashboardIntervalFilter(): JSX.Element {
- const { dashboardMode, effectiveEditBarFilters } = useValues(dashboardLogic)
- const { setInterval, setDashboardMode } = useActions(dashboardLogic)
+ const { dashboardEditing, effectiveEditBarFilters } = useValues(dashboardLogic)
+ const { setInterval, setDashboardEditing } = useActions(dashboardLogic)
return (
<span className="flex items-center gap-2">
@@ -39,8 +39,8 @@ export function DashboardIntervalFilter(): JSX.Element {
value={effectiveEditBarFilters.interval ?? null}
dropdownMatchSelectWidth={false}
onChange={(interval) => {
- if (dashboardMode !== DashboardMode.Edit) {
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
+ if (!dashboardEditing?.filters) {
+ setDashboardEditing({ filters: true, layout: false }, DashboardEventSource.DashboardFilters)
}
setInterval(interval)
}}
@@ -57,8 +57,8 @@ export function DashboardIntervalFilter(): JSX.Element {
}
export function DashboardEditBar({ showDateFilter = true, className }: DashboardEditBarProps): JSX.Element {
- const { dashboard, dashboardMode, hasVariables, effectiveEditBarFilters } = useValues(dashboardLogic)
- const { setDates, setProperties, setBreakdownFilter, setDashboardMode } = useActions(dashboardLogic)
+ const { dashboard, dashboardEditing, hasVariables, effectiveEditBarFilters } = useValues(dashboardLogic)
+ const { setDates, setProperties, setBreakdownFilter, setDashboardEditing } = useActions(dashboardLogic)
const { groupsTaxonomicTypes } = useValues(groupsModel)
const { hasPageview, hasScreen } = getProjectEventExistence()
@@ -82,7 +82,7 @@ export function DashboardEditBar({ showDateFilter = true, className }: Dashboard
className ??
clsx(
'flex gap-2 items-end flex-wrap border',
- dashboardMode === DashboardMode.Edit
+ dashboardEditing?.filters
? '-m-1.5 p-1.5 border-primary border-dashed rounded-lg'
: 'border-transparent'
)
@@ -106,8 +106,11 @@ export function DashboardEditBar({ showDateFilter = true, className }: Dashboard
dateTo={effectiveEditBarFilters.date_to}
explicitDate={effectiveEditBarFilters.explicitDate}
onChange={(from_date, to_date, explicitDate) => {
- if (dashboardMode !== DashboardMode.Edit) {
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
+ if (!dashboardEditing?.filters) {
+ setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
}
setDates(from_date, to_date, explicitDate)
}}
@@ -129,8 +132,8 @@ export function DashboardEditBar({ showDateFilter = true, className }: Dashboard
<div className={clsx('content-end', { 'h-[61px]': hasVariables })}>
<PropertyFilters
onChange={(properties) => {
- if (dashboardMode !== DashboardMode.Edit) {
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
+ if (!dashboardEditing?.filters) {
+ setDashboardEditing({ filters: true, layout: false }, DashboardEventSource.DashboardFilters)
}
setProperties(properties)
}}
@@ -153,8 +156,7 @@ export function DashboardEditBar({ showDateFilter = true, className }: Dashboard
]}
/>
</div>
- {/* Single flex item so the "…" button always wraps together with the breakdown button */}
- <div className={clsx('content-end flex items-end gap-2', { 'h-[61px]': hasVariables })}>
+ <div className={clsx('content-end', { 'h-[61px]': hasVariables })}>
<BindLogic logic={insightLogic} props={insightProps}>
<TaxonomicBreakdownFilter
insightProps={insightProps}
@@ -163,8 +165,11 @@ export function DashboardEditBar({ showDateFilter = true, className }: Dashboard
isFunnels={false}
showLabel={false}
updateBreakdownFilter={(breakdown_filter) => {
- if (dashboardMode !== DashboardMode.Edit) {
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
+ if (!dashboardEditing?.filters) {
+ setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
}
let saved_breakdown_filter: BreakdownFilter | null = breakdown_filter
// taxonomicBreakdownFilterLogic can generate an empty breakdown_filter object
@@ -178,10 +183,12 @@ export function DashboardEditBar({ showDateFilter = true, className }: Dashboard
size="small"
/>
</BindLogic>
- <DashboardEditBarAdvancedFilters />
</div>
<VariablesForDashboard />
+ <div className={clsx('content-end', { 'h-[61px]': hasVariables })}>
+ <DashboardEditBarAdvancedFilters />
+ </div>
</div>
)
}
diff --git a/frontend/src/scenes/dashboard/DashboardEditBarAdvancedFilters.tsx b/frontend/src/scenes/dashboard/DashboardEditBarAdvancedFilters.tsx
index 2c43f773d432..bffa59ef8876 100644
--- a/frontend/src/scenes/dashboard/DashboardEditBarAdvancedFilters.tsx
+++ b/frontend/src/scenes/dashboard/DashboardEditBarAdvancedFilters.tsx
@@ -12,7 +12,7 @@ import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { DashboardMode, DashboardPlacement } from '~/types'
+import { DashboardPlacement } from '~/types'
type TestAccountFilterChoice = 'inherit' | 'filter-out' | 'include'
@@ -34,8 +34,9 @@ const CHOICE_HINTS: Record<TestAccountFilterChoice, string> = {
* breakdown color override.
*/
export function DashboardEditBarAdvancedFilters(): JSX.Element {
- const { dashboard, dashboardMode, placement, canEditDashboard, effectiveEditBarFilters } = useValues(dashboardLogic)
- const { setFilterTestAccounts, setDashboardMode } = useActions(dashboardLogic)
+ const { dashboard, dashboardEditing, placement, canEditDashboard, effectiveEditBarFilters } =
+ useValues(dashboardLogic)
+ const { setFilterTestAccounts, setDashboardEditing } = useActions(dashboardLogic)
const { showInsightColorsModal } = useActions(dashboardInsightColorsModalLogic)
const { currentTeam } = useValues(teamLogic)
const hasDashboardColors = useFeatureFlag('PRODUCT_ANALYTICS_DASHBOARD_COLORS')
@@ -83,8 +84,11 @@ export function DashboardEditBarAdvancedFilters(): JSX.Element {
size="small"
value={choice}
onChange={(next) => {
- if (dashboardMode !== DashboardMode.Edit) {
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
+ if (!dashboardEditing?.filters) {
+ setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
}
setFilterTestAccounts(CHOICE_TO_FILTER[next])
}}
diff --git a/frontend/src/scenes/dashboard/DashboardFilters.tsx b/frontend/src/scenes/dashboard/DashboardFilters.tsx
index 4692e93dccdd..8866a5ae766f 100644
--- a/frontend/src/scenes/dashboard/DashboardFilters.tsx
+++ b/frontend/src/scenes/dashboard/DashboardFilters.tsx
@@ -1,70 +1,30 @@
import clsx from 'clsx'
-import { useActions, useValues } from 'kea'
+import { useValues } from 'kea'
import { IconEllipsis } from '@posthog/icons'
import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
import { urls } from 'scenes/urls'
-import { DashboardMode, DashboardPlacement } from '~/types'
+import { DashboardPlacement } from '~/types'
+
+import { DashboardUnsavedChangesIndicator } from 'products/dashboards/frontend/dashboardSettings/DashboardUnsavedChangesIndicator'
import { DashboardEditBar } from './DashboardEditBar'
-import { DashboardEditSaveCancelButtons } from './DashboardHeaderActions'
import { dashboardLogic } from './dashboardLogic'
import { DashboardReloadAction, LastRefreshText } from './DashboardReloadAction'
-/**
- * Edit-mode actions for the filter bar.
- *
- * One Cancel discards everything. On large dashboards that don't auto-preview, an
- * "Apply filters" button appears so the user can preview pending filter changes before
- * committing — Save applies any still-unapplied filters as part of persisting, so it's
- * always safe to skip Apply and go straight to Save.
- */
-function DashboardEditActions(): JSX.Element | null {
- const { dashboardMode, layoutEditMode, canEditDashboard, showApplyFiltersBanner, loadingPreview } =
- useValues(dashboardLogic)
- const { applyFilters } = useActions(dashboardLogic)
-
- if (dashboardMode !== DashboardMode.Edit || layoutEditMode || !canEditDashboard) {
- return null
- }
-
- return (
- <div className="flex shrink-0 flex-wrap items-center gap-2">
- <DashboardEditSaveCancelButtons
- withShortcuts
- applyFiltersButton={
- showApplyFiltersBanner ? (
- <LemonButton
- data-attr="dashboard-apply-filters"
- type="secondary"
- size="small"
- loading={loadingPreview}
- onClick={applyFilters}
- tooltip="Preview these filters. Large dashboards don't auto-apply — Save will apply and persist them too."
- >
- Apply filters
- </LemonButton>
- ) : null
- }
- />
- </div>
- )
-}
-
interface DashboardFilterBarProps {
backTo?: { url: string; name: string }
}
export function DashboardFilterBar({ backTo }: DashboardFilterBarProps): JSX.Element {
- const { placement, dashboard, dashboardMode, hasVariables } = useValues(dashboardLogic)
-
+ const { placement, dashboard, hasVariables } = useValues(dashboardLogic)
return (
<div className="@container/dashboard-filters flex min-w-0 flex-1 flex-col gap-2">
<div className="flex flex-wrap gap-x-2 gap-y-2 justify-between items-start">
<div className="flex min-w-0 flex-1 flex-col gap-2 @2xl/dashboard-filters:flex-row @2xl/dashboard-filters:justify-between items-start @4xl/dashboard-filters:items-center">
- <div className="flex min-w-0 flex-1 flex-wrap gap-x-2 gap-y-2 items-center">
+ <div className="flex min-w-0 flex-1 flex-wrap gap-4 items-center">
{![
DashboardPlacement.Public,
DashboardPlacement.Export,
@@ -74,7 +34,7 @@ export function DashboardFilterBar({ backTo }: DashboardFilterBarProps): JSX.Ele
DashboardPlacement.Builtin,
].includes(placement) &&
dashboard && <DashboardEditBar />}
- <DashboardEditActions />
+ {placement === DashboardPlacement.Dashboard && <DashboardUnsavedChangesIndicator />}
</div>
</div>
{![DashboardPlacement.Export, DashboardPlacement.Builtin].includes(placement) && (
@@ -90,9 +50,9 @@ export function DashboardFilterBar({ backTo }: DashboardFilterBarProps): JSX.Ele
<div className={`left-item ${placement === DashboardPlacement.Public ? 'text-right' : ''}`}>
{[DashboardPlacement.Public].includes(placement) ? (
<LastRefreshText />
- ) : !(dashboardMode === DashboardMode.Edit) ? (
+ ) : (
<DashboardReloadAction />
- ) : null}
+ )}
</div>
{[
DashboardPlacement.FeatureFlag,
diff --git a/frontend/src/scenes/dashboard/DashboardHeader.test.tsx b/frontend/src/scenes/dashboard/DashboardHeader.test.tsx
index 64029fd949d7..4504c6c87996 100644
--- a/frontend/src/scenes/dashboard/DashboardHeader.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeader.test.tsx
@@ -86,6 +86,7 @@ describe('DashboardHeader', () => {
function renderHeader(opts: {
dashboard?: DashboardType<QueryBasedInsightModel> | null
dashboardMode?: DashboardMode | null
+ dashboardEditing?: { filters: boolean; layout: boolean } | null
dashboardModeSource?: DashboardEventSource
loading?: boolean
spyOnLoadDashboard?: boolean
@@ -93,6 +94,7 @@ describe('DashboardHeader', () => {
const {
dashboard = MOCK_DASHBOARD,
dashboardMode = null,
+ dashboardEditing = null,
dashboardModeSource = DashboardEventSource.Browser,
loading = false,
} = opts
@@ -103,7 +105,9 @@ describe('DashboardHeader', () => {
? jest.spyOn(logic.actions, 'loadDashboard').mockImplementation()
: undefined
- if (dashboardMode) {
+ if (dashboardEditing) {
+ logic.actions.setDashboardEditing(dashboardEditing, dashboardModeSource)
+ } else if (dashboardMode) {
logic.actions.setDashboardMode(dashboardMode, dashboardModeSource)
}
@@ -160,6 +164,7 @@ describe('DashboardHeader', () => {
scenario: 'View mode, can edit',
dashboardMode: null as DashboardMode | null,
canEdit: true,
+ hasTiles: false,
visible: [],
notVisible: [
'dashboard-add-tile',
@@ -173,6 +178,7 @@ describe('DashboardHeader', () => {
scenario: 'View mode, cannot edit',
dashboardMode: null as DashboardMode | null,
canEdit: false,
+ hasTiles: false,
visible: [],
notVisible: [
'dashboard-add-tile',
@@ -184,9 +190,10 @@ describe('DashboardHeader', () => {
},
{
scenario: 'Filter edit mode',
- dashboardMode: DashboardMode.Edit,
+ dashboardEditing: { filters: true, layout: false },
dashboardModeSource: DashboardEventSource.DashboardFilters,
canEdit: true,
+ hasTiles: false,
visible: [],
notVisible: [
'dashboard-add-tile',
@@ -198,11 +205,26 @@ describe('DashboardHeader', () => {
'dashboard-add-graph-header',
],
},
+ {
+ scenario: 'Filter edit mode, cannot edit',
+ dashboardEditing: { filters: true, layout: false },
+ dashboardModeSource: DashboardEventSource.DashboardFilters,
+ canEdit: false,
+ hasTiles: true,
+ visible: [],
+ notVisible: [
+ 'dashboard-edit-mode-button',
+ 'dashboard-edit-mode-discard',
+ 'dashboard-edit-mode-save',
+ 'dashboard-share-button',
+ ],
+ },
{
scenario: 'Layout edit mode',
- dashboardMode: DashboardMode.Edit,
+ dashboardEditing: { filters: true, layout: true },
dashboardModeSource: DashboardEventSource.SceneCommonButtons,
canEdit: true,
+ hasTiles: false,
visible: ['dashboard-edit-mode-discard', 'dashboard-edit-mode-save'],
notVisible: [
'dashboard-add-tile',
@@ -216,16 +238,27 @@ describe('DashboardHeader', () => {
scenario: 'Fullscreen mode',
dashboardMode: DashboardMode.Fullscreen,
canEdit: true,
+ hasTiles: false,
visible: ['dashboard-exit-presentation-mode'],
notVisible: ['dashboard-share-button', 'dashboard-edit-mode-save'],
},
])(
'$scenario shows correct action buttons',
- ({ dashboardMode, dashboardModeSource, canEdit, visible, notVisible }) => {
+ ({ dashboardMode, dashboardEditing, dashboardModeSource, canEdit, hasTiles, visible, notVisible }) => {
const dashboard = makeDashboard({
user_access_level: canEdit ? AccessControlLevel.Editor : AccessControlLevel.Viewer,
+ tiles: hasTiles
+ ? [
+ {
+ id: 1,
+ color: null,
+ layouts: {},
+ insight: { id: 1, short_id: 'test', name: 'Test' } as QueryBasedInsightModel,
+ },
+ ]
+ : [],
})
- const { logic } = renderHeader({ dashboard, dashboardMode, dashboardModeSource })
+ const { logic } = renderHeader({ dashboard, dashboardMode, dashboardEditing, dashboardModeSource })
for (const attr of visible) {
expect(document.querySelector(`[data-attr="${attr}"]`)).toBeInTheDocument()
diff --git a/frontend/src/scenes/dashboard/DashboardHeader.tsx b/frontend/src/scenes/dashboard/DashboardHeader.tsx
index fb979f6a5977..0674cfcfcee1 100644
--- a/frontend/src/scenes/dashboard/DashboardHeader.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeader.tsx
@@ -26,7 +26,7 @@ export function insightIsAddedToDashboard(input: Record<string, unknown> | null,
}
export function DashboardHeader({ loading = false }: { loading?: boolean }): JSX.Element | null {
- const { dashboard, dashboardLoading, dashboardMode, canEditDashboard } = useValues(dashboardLogic)
+ const { dashboard, dashboardLoading, dashboardMode, dashboardEditing, canEditDashboard } = useValues(dashboardLogic)
const { setDashboardMode, loadDashboard } = useActions(dashboardLogic)
const { updateDashboard } = useActions(dashboardsModel)
@@ -51,15 +51,12 @@ export function DashboardHeader({ loading = false }: { loading?: boolean }): JSX
let actions: JSX.Element | undefined
if (dashboard) {
- switch (dashboardMode) {
- case DashboardMode.Edit:
- actions = <EditModeActions />
- break
- case DashboardMode.Fullscreen:
- actions = <FullscreenModeActions />
- break
- default:
- actions = <ViewModeActions />
+ if (dashboardEditing) {
+ actions = <EditModeActions />
+ } else if (dashboardMode === DashboardMode.Fullscreen) {
+ actions = <FullscreenModeActions />
+ } else {
+ actions = <ViewModeActions />
}
}
diff --git a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
index 134035c7ff1f..9128250dfcdd 100644
--- a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
@@ -17,7 +17,7 @@ import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
-import { AccessControlLevel, AccessControlResourceType, DashboardMode } from '~/types'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { DashboardCustomizeMenu } from 'products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu'
@@ -167,15 +167,15 @@ export function DashboardEditSaveCancelButtons({
applyFiltersButton?: JSX.Element | null
}): JSX.Element {
const { dashboardLoading, canEditDashboard } = useValues(dashboardLogic)
- const { setDashboardMode, cancelEditMode } = useActions(dashboardLogic)
+ const { cancelLayoutEdit, saveLayout } = useActions(dashboardLogic)
const cancelButton = (
<LemonButton
data-attr="dashboard-edit-mode-discard"
type="secondary"
- onClick={() => cancelEditMode()}
+ onClick={cancelLayoutEdit}
size="small"
- tooltip="Discard changes and exit edit mode"
+ tooltip="Discard layout changes and exit layout editing"
>
Cancel
</LemonButton>
@@ -185,9 +185,9 @@ export function DashboardEditSaveCancelButtons({
<LemonButton
data-attr="dashboard-edit-mode-save"
type="primary"
- onClick={() => setDashboardMode(null, DashboardEventSource.DashboardHeaderSaveDashboard)}
+ onClick={saveLayout}
size="small"
- tooltip="Save dashboard"
+ tooltip="Save dashboard layout"
tooltipPlacement="bottom"
disabledReason={
dashboardLoading
@@ -197,7 +197,7 @@ export function DashboardEditSaveCancelButtons({
: 'Not privileged to edit this dashboard'
}
>
- Save
+ Save layout
</LemonButton>
)
@@ -226,7 +226,7 @@ export function DashboardEditSaveCancelButtons({
<Shortcut
name="SaveDashboard"
keybind={[keyBinds.edit, keyBinds.save]}
- intent="Save dashboard"
+ intent="Save dashboard layout"
interaction="click"
scope={Scene.Dashboard}
disabled={!canEditDashboard}
@@ -238,15 +238,55 @@ export function DashboardEditSaveCancelButtons({
}
export function EditModeActions(): JSX.Element {
- const { layoutEditMode, tiles, dashboardCustomizeMenuOpen } = useValues(dashboardLogic)
- const { setDashboardCustomizeMenuOpen } = useActions(dashboardLogic)
+ const { canEditDashboard, layoutEditMode, tiles, dashboardCustomizeMenuOpen } = useValues(dashboardLogic)
+ const { setDashboardEditing, setDashboardCustomizeMenuOpen } = useActions(dashboardLogic)
const dashboardCustomizationEnabled = useFeatureFlag('DASHBOARD_CUSTOMIZATION')
return (
<>
<DashboardSubscribeButton />
{layoutEditMode && <DashboardEditSaveCancelButtons />}
- {dashboardCustomizationEnabled && tiles.length > 0 && (
+ {canEditDashboard && !layoutEditMode && tiles.length > 0 && (
+ <Shortcut
+ name="EnterEditMode"
+ scope={Scene.Dashboard}
+ keybind={[keyBinds.edit]}
+ intent="Enter edit mode"
+ interaction="click"
+ >
+ <LemonButton
+ type="secondary"
+ data-attr="dashboard-edit-mode-button"
+ onClick={() =>
+ setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ }
+ size="small"
+ icon={<IconGridMasonry fontSize="16" />}
+ tooltip="Customize dashboard"
+ tooltipPlacement="top"
+ sideAction={
+ dashboardCustomizationEnabled
+ ? {
+ 'data-attr': 'dashboard-edit-layout-customize-dropdown',
+ dropdown: {
+ closeOnClickInside: false,
+ placement: 'bottom-end',
+ overlay: (
+ <LemonMenuOverlay items={[{ label: () => <DashboardCustomizeMenu /> }]} />
+ ),
+ },
+ }
+ : undefined
+ }
+ >
+ Customize
+ </LemonButton>
+ </Shortcut>
+ )}
+ {layoutEditMode && dashboardCustomizationEnabled && tiles.length > 0 && (
<LemonMenu
items={[{ label: () => <DashboardCustomizeMenu /> }]}
closeOnClickInside={false}
@@ -291,7 +331,7 @@ export function FullscreenModeActions(): JSX.Element {
export function ViewModeActions(): JSX.Element {
const { dashboard, canEditDashboard, tiles } = useValues(dashboardLogic)
- const { setDashboardMode } = useActions(dashboardLogic)
+ const { setDashboardEditing } = useActions(dashboardLogic)
const dashboardCustomizationEnabled = useFeatureFlag('DASHBOARD_CUSTOMIZATION')
const { push } = useActions(router)
if (!dashboard) {
@@ -329,7 +369,12 @@ export function ViewModeActions(): JSX.Element {
<LemonButton
type="secondary"
data-attr="dashboard-edit-mode-button"
- onClick={() => setDashboardMode(DashboardMode.Edit, DashboardEventSource.SceneCommonButtons)}
+ onClick={() =>
+ setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ }
size="small"
icon={<IconGridMasonry fontSize="16" />}
tooltip="Customize dashboard"
diff --git a/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx b/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx
index 48828bb6ec2e..42fa36f6df76 100644
--- a/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx
+++ b/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx
@@ -20,7 +20,7 @@ import { dataColorThemesLogic } from 'scenes/settings/environment/dataColorTheme
import { cohortsModel } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { BreakdownFilter } from '~/queries/schema/schema-general'
-import { DashboardMode, DataColorThemeModel } from '~/types'
+import { DataColorThemeModel } from '~/types'
import {
BreakdownColorConfig,
@@ -76,12 +76,12 @@ export function DashboardInsightColorsModal(): JSX.Element {
const {
effectiveBreakdownColors,
dataColorThemeId,
- dashboardMode,
+ dashboardEditing,
dashboardLoading,
canEditDashboard,
hasUnsavedColorChanges,
} = useValues(dashboardLogic)
- const { setBreakdownColorConfig, setDataColorThemeId, setDashboardMode } = useActions(dashboardLogic)
+ const { setBreakdownColorConfig, setDataColorThemeId, setDashboardEditing } = useActions(dashboardLogic)
const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
const { allCohorts } = useValues(cohortsModel)
@@ -89,8 +89,8 @@ export function DashboardInsightColorsModal(): JSX.Element {
const themes = _themes || []
const ensureEditMode = (): void => {
- if (dashboardMode !== DashboardMode.Edit) {
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardInsightColorsModal)
+ if (!dashboardEditing) {
+ setDashboardEditing({ filters: true, layout: false }, DashboardEventSource.DashboardInsightColorsModal)
}
}
@@ -198,7 +198,7 @@ export function DashboardInsightColorsModal(): JSX.Element {
data-attr="dashboard-colors-save"
onClick={() => {
hideInsightColorsModal()
- setDashboardMode(null, DashboardEventSource.DashboardInsightColorsModal)
+ setDashboardEditing(null, DashboardEventSource.DashboardInsightColorsModal)
}}
disabledReason={
dashboardLoading
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index 68a5a9d420e0..d24b492b41b9 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -9,7 +9,7 @@ import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
-import { DashboardMode, DashboardPlacement } from '~/types'
+import { DashboardPlacement } from '~/types'
import { DashboardItems } from './DashboardItems'
@@ -182,11 +182,13 @@ const mockedUseAsyncActions = useAsyncActions as jest.Mock
const mockRemoveTile = jest.fn()
const mockTriggerDashboardRefresh = jest.fn()
const mockInsightCard = jest.fn()
+let canEditDashboard = true
describe('DashboardItems', () => {
beforeEach(() => {
mockInsightCard.mockClear()
jest.clearAllMocks()
+ canEditDashboard = true
mockedUseValues.mockImplementation((logic) => {
if (logic === dashboardLogic) {
@@ -201,7 +203,7 @@ describe('DashboardItems', () => {
layouts: {
sm: [{ i: '1', x: 0, y: 0, w: 6, h: 5 }],
},
- dashboardMode: DashboardMode.Edit,
+ dashboardEditing: { filters: true, layout: true },
layoutEditMode: true,
placement: DashboardPlacement.Dashboard,
isRefreshingQueued: () => false,
@@ -211,10 +213,10 @@ describe('DashboardItems', () => {
itemsLoading: false,
dashboardStreaming: false,
effectiveEditBarFilters: {},
- effectiveDashboardVariableOverrides: {},
+ currentDashboardVariables: {},
temporaryBreakdownColors: [],
dataColorThemeId: null,
- canEditDashboard: true,
+ canEditDashboard,
layoutZoom: 0.75,
}
}
@@ -284,6 +286,22 @@ describe('DashboardItems', () => {
expect(container.firstChild).toMatchSnapshot()
})
+ it('disables layout controls for read-only viewers', () => {
+ canEditDashboard = false
+
+ const { container } = render(<DashboardItems />)
+
+ expect(container.querySelector('[data-attr="react-grid-layout"]')).toHaveAttribute('data-drag-enabled', 'false')
+ expect(container.querySelector('[data-attr="react-grid-layout"]')).toHaveAttribute(
+ 'data-resize-enabled',
+ 'false'
+ )
+ expect(container.querySelector('[data-attr="insight-card"]')).toHaveAttribute(
+ 'data-show-resize-handles',
+ 'false'
+ )
+ })
+
it.each([
['tight', '8,8'],
['condensed', '12,12'],
@@ -295,7 +313,7 @@ describe('DashboardItems', () => {
dashboard: { id: 5, customization: { tile_spacing: tileSpacing } },
tiles: [],
layouts: { sm: [] },
- dashboardMode: DashboardMode.Edit,
+ dashboardEditing: { filters: true, layout: true },
layoutEditMode: true,
placement: DashboardPlacement.Dashboard,
isRefreshingQueued: () => false,
@@ -304,7 +322,7 @@ describe('DashboardItems', () => {
refreshStatus: {},
dashboardStreaming: false,
effectiveEditBarFilters: {},
- effectiveDashboardVariableOverrides: {},
+ currentDashboardVariables: {},
dataColorThemeId: null,
canEditDashboard: true,
layoutZoom: 1,
@@ -330,7 +348,7 @@ describe('DashboardItems', () => {
dashboard: { id: 5, customization: { tile_spacing: 'unknown' } },
tiles: [],
layouts: { sm: [] },
- dashboardMode: DashboardMode.Edit,
+ dashboardEditing: { filters: true, layout: true },
layoutEditMode: true,
placement: DashboardPlacement.Dashboard,
isRefreshingQueued: () => false,
@@ -339,7 +357,7 @@ describe('DashboardItems', () => {
refreshStatus: {},
dashboardStreaming: false,
effectiveEditBarFilters: {},
- effectiveDashboardVariableOverrides: {},
+ currentDashboardVariables: {},
dataColorThemeId: null,
canEditDashboard: true,
layoutZoom: 1,
@@ -379,7 +397,7 @@ describe('DashboardItems', () => {
itemsLoading: false,
dashboardStreaming: false,
effectiveEditBarFilters: {},
- effectiveDashboardVariableOverrides: {},
+ currentDashboardVariables: {},
temporaryBreakdownColors: [],
dataColorThemeId: null,
canEditDashboard: false,
@@ -417,7 +435,7 @@ describe('DashboardItems', () => {
refreshStatus: {},
dashboardStreaming: false,
effectiveEditBarFilters: {},
- effectiveDashboardVariableOverrides: {},
+ currentDashboardVariables: {},
temporaryBreakdownColors: [],
dataColorThemeId: null,
canEditDashboard: true,
@@ -470,7 +488,7 @@ describe('DashboardItems', () => {
refreshStatus: {},
dashboardStreaming: false,
effectiveEditBarFilters: {},
- effectiveDashboardVariableOverrides: {},
+ currentDashboardVariables: {},
temporaryBreakdownColors: [],
dataColorThemeId: null,
canEditDashboard: true,
@@ -527,7 +545,7 @@ describe('DashboardItems', () => {
refreshStatus,
dashboardStreaming: false,
effectiveEditBarFilters: {},
- effectiveDashboardVariableOverrides: {},
+ currentDashboardVariables: {},
temporaryBreakdownColors: [],
dataColorThemeId: null,
canEditDashboard: true,
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 2488e891c549..3498da642eb2 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -32,7 +32,7 @@ import { urls } from 'scenes/urls'
import { getCurrentExporterData, isSharedView } from '~/exporter/exporterViewLogic'
import { insightsModel } from '~/models/insightsModel'
-import { DashboardLayoutSize, DashboardMode, DashboardPlacement, DashboardType } from '~/types'
+import { DashboardLayoutSize, DashboardPlacement, DashboardType } from '~/types'
import { DashboardTextItem } from 'products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem'
import { getDashboardTileSpacingGap } from 'products/dashboards/frontend/dashboardCustomization'
@@ -80,7 +80,6 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
dashboard,
tiles,
layouts,
- dashboardMode,
layoutEditMode,
placement,
isRefreshingQueued,
@@ -90,7 +89,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
dashboardStreaming,
dashboardLoading,
effectiveEditBarFilters,
- effectiveDashboardVariableOverrides,
+ currentDashboardVariables,
effectiveBreakdownColors,
dataColorThemeId,
canEditDashboard,
@@ -115,7 +114,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
moveToDashboard,
copyToDashboard,
setTileOverride,
- setDashboardMode,
+ setDashboardEditing,
} = useActions(dashboardLogic)
const { updateWidgetTile } = useAsyncActions(dashboardLogic)
const { renameInsight } = useActions(insightsModel)
@@ -263,20 +262,20 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
const dragConfig = useMemo(
() => ({
- enabled: layoutEditMode && !isMobileView,
+ enabled: canEditDashboard && layoutEditMode && !isMobileView,
handle: '.CardMeta,.DashboardTileCard__body,.WidgetCard__header,.drag-handle',
cancel: 'a,table,button,input,.Popover',
bounded: true,
}),
- [layoutEditMode, isMobileView]
+ [canEditDashboard, layoutEditMode, isMobileView]
)
const resizeConfig = useMemo(
() => ({
- enabled: layoutEditMode && !isMobileView && !isLayoutZoomToggled,
+ enabled: canEditDashboard && layoutEditMode && !isMobileView && !isLayoutZoomToggled,
handles: ['s', 'e', 'se', 'n', 'w', 'nw', 'ne', 'sw'] as const,
}),
- [layoutEditMode, isMobileView, isLayoutZoomToggled]
+ [canEditDashboard, layoutEditMode, isMobileView, isLayoutZoomToggled]
)
useResizeHandleScrollbarPassThrough(layoutEditMode && !isMobileView)
@@ -285,12 +284,12 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
() =>
canEnterEditModeFromEdge
? (e: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge) => {
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.CardEdgeHover)
+ setDashboardEditing({ filters: true, layout: true }, DashboardEventSource.CardEdgeHover)
// continue the press into a live resize so the user doesn't have to release and grab again
continueResizeGestureInEditMode(e, edge)
}
: undefined,
- [canEnterEditModeFromEdge, setDashboardMode]
+ [canEnterEditModeFromEdge, setDashboardEditing]
)
const onDragHandleMouseDown = useMemo(
@@ -317,12 +316,12 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
}
e.preventDefault()
e.stopPropagation()
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.CardDragHandle)
+ setDashboardEditing({ filters: true, layout: true }, DashboardEventSource.CardDragHandle)
// continue the press into a live drag so the user doesn't have to release and grab again
continueDragGestureInEditMode(e)
}
: undefined,
- [canEnterEditModeFromEdge, setDashboardMode]
+ [canEnterEditModeFromEdge, setDashboardEditing]
)
const requireDashboardId = useCallback(
@@ -584,7 +583,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
loadPriority={smLayout ? smLayout.y * 1000 + smLayout.x : undefined}
isResizing={resizingTileId === tile.id.toString()}
filtersOverride={effectiveEditBarFilters}
- variablesOverride={effectiveDashboardVariableOverrides}
+ variablesOverride={currentDashboardVariables}
// :HACKY: The two props below aren't actually used in the component, but are needed to trigger a re-render
breakdownColorOverride={effectiveBreakdownColors}
dataColorThemeId={dataColorThemeId}
@@ -656,7 +655,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
placement={placement}
dashboardId={dashboard?.id}
canEditDashboard={canEditDashboard}
- isDashboardEditMode={dashboardMode === DashboardMode.Edit}
+ isDashboardEditMode={layoutEditMode}
result={runResult?.result}
error={getDashboardWidgetFetchDisplayError(
runResult?.error ?? refreshState?.error
diff --git a/frontend/src/scenes/dashboard/DashboardOverridesBanner.tsx b/frontend/src/scenes/dashboard/DashboardOverridesBanner.tsx
deleted file mode 100644
index ae5673aae2e0..000000000000
--- a/frontend/src/scenes/dashboard/DashboardOverridesBanner.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
-
-import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
-
-import { DashboardMode } from '~/types'
-
-import { dashboardLogic } from './dashboardLogic'
-
-export const DashboardOverridesBanner = (): JSX.Element | null => {
- const { dashboardMode, hasUrlFilters, cancellingPreview } = useValues(dashboardLogic)
- const { setDashboardMode } = useActions(dashboardLogic)
-
- if (dashboardMode === DashboardMode.Edit || !hasUrlFilters) {
- return null
- }
-
- return (
- <LemonBanner type="info" className="mt-4 mb-2">
- <div className="flex flex-row items-center justify-between gap-2 flex-wrap">
- <span>You are viewing this dashboard with filter overrides.</span>
-
- <div className="flex gap-2">
- <LemonButton
- type="primary"
- onClick={() =>
- setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardHeaderOverridesBanner)
- }
- >
- Edit dashboard
- </LemonButton>
- <LemonButton
- type="secondary"
- onClick={() => setDashboardMode(null, DashboardEventSource.DashboardHeaderOverridesBanner)}
- loading={cancellingPreview}
- >
- Discard overrides
- </LemonButton>
- </div>
- </div>
- </LemonBanner>
- )
-}
diff --git a/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx b/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx
index 346259860978..9aa8d4f1824c 100644
--- a/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx
+++ b/frontend/src/scenes/dashboard/DashboardSceneMenuBar.tsx
@@ -68,13 +68,14 @@ function DashboardSceneMenuBarInner(): JSX.Element | null {
const {
dashboard,
dashboardMode,
+ layoutEditMode,
canEditDashboard,
isSavingTags,
isPinned,
asDashboardTemplate,
canSaveProjectDashboardTemplate,
effectiveEditBarFilters,
- effectiveDashboardVariableOverrides,
+ currentDashboardVariables,
tiles,
apiUrl,
} = useValues(dashboardLogic)
@@ -122,12 +123,11 @@ function DashboardSceneMenuBarInner(): JSX.Element | null {
? 'Template data is not ready yet. Try again in a moment.'
: undefined
- const openInsightsInNewTabsDisabled =
- dashboardMode === DashboardMode.Edit
- ? 'Cannot open insights when editing dashboard'
- : tiles.length === 0
- ? 'Dashboard has no insights'
- : undefined
+ const openInsightsInNewTabsDisabled = layoutEditMode
+ ? 'Cannot open insights when editing dashboard'
+ : tiles.length === 0
+ ? 'Dashboard has no insights'
+ : undefined
const showCreateMenu = canEditDashboard // notebook + subscribe both gated on canEdit
const showEditMenu = true // duplicate always
@@ -188,7 +188,7 @@ function DashboardSceneMenuBarInner(): JSX.Element | null {
const url = urls.insightView(
tile.insight.short_id,
dashboard.id,
- effectiveDashboardVariableOverrides,
+ currentDashboardVariables,
effectiveEditBarFilters,
tile?.filters_overrides
)
@@ -213,7 +213,7 @@ function DashboardSceneMenuBarInner(): JSX.Element | null {
dashboard: dashboard.id,
export_context: {
path: apiUrl(),
- variables_override: effectiveDashboardVariableOverrides,
+ variables_override: currentDashboardVariables,
},
})
}
diff --git a/frontend/src/scenes/dashboard/DashboardScenePanel.tsx b/frontend/src/scenes/dashboard/DashboardScenePanel.tsx
index d70249be72ae..def3d9fd51cf 100644
--- a/frontend/src/scenes/dashboard/DashboardScenePanel.tsx
+++ b/frontend/src/scenes/dashboard/DashboardScenePanel.tsx
@@ -48,7 +48,7 @@ export function DashboardScenePanel(): JSX.Element | null {
isSavingTags,
isPinned,
asDashboardTemplate,
- effectiveDashboardVariableOverrides,
+ currentDashboardVariables,
apiUrl,
tiles,
} = useValues(dashboardLogic)
@@ -144,7 +144,7 @@ export function DashboardScenePanel(): JSX.Element | null {
dashboard: dashboard.id,
context: {
path: apiUrl(),
- variables_override: effectiveDashboardVariableOverrides,
+ variables_override: currentDashboardVariables,
},
dataAttr: `${RESOURCE_TYPE}-export-png`,
},
diff --git a/frontend/src/scenes/dashboard/dashboardFilterEmpty.test.ts b/frontend/src/scenes/dashboard/dashboardFilterEmpty.test.ts
index fa0960e2062d..123449cccbef 100644
--- a/frontend/src/scenes/dashboard/dashboardFilterEmpty.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardFilterEmpty.test.ts
@@ -1,27 +1,25 @@
import { DashboardFilter, TileFilters } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator } from '~/types'
-import { isDashboardFilterEmpty } from './dashboardFilterEmpty'
+import { isDashboardFilterOverrideEmpty } from './dashboardFilterEmpty'
-describe('isDashboardFilterEmpty', () => {
+describe('isDashboardFilterOverrideEmpty', () => {
const emptyCases: Array<[string, DashboardFilter | TileFilters | null | undefined]> = [
['null', null],
['undefined', undefined],
['empty object', {}],
['only explicitDate false', { explicitDate: false }],
- ['null date fields + explicitDate false', { date_from: null, date_to: null, explicitDate: false }],
- ['empty properties array', { properties: [] }],
- ['filterTestAccounts null', { filterTestAccounts: null }],
['ignoreDashboardFilters false', { ignoreDashboardFilters: false }],
]
test.each(emptyCases)('returns true for %s', (_, filter) => {
- expect(isDashboardFilterEmpty(filter)).toBe(true)
+ expect(isDashboardFilterOverrideEmpty(filter)).toBe(true)
})
const nonEmptyCases: Array<[string, DashboardFilter | TileFilters]> = [
['date_from set', { date_from: '-7d' }],
['date_to set', { date_to: '2024-01-01' }],
+ ['date fields explicitly cleared', { date_from: null, date_to: null, explicitDate: false }],
[
'non-empty properties',
{
@@ -35,14 +33,18 @@ describe('isDashboardFilterEmpty', () => {
],
},
],
+ ['properties explicitly cleared', { properties: [] }],
['breakdown_filter set', { breakdown_filter: { breakdown: 'browser' } }],
+ ['breakdown_filter explicitly cleared', { breakdown_filter: null }],
['interval set', { interval: 'week' }],
+ ['interval explicitly cleared', { interval: null }],
['filterTestAccounts forced on', { filterTestAccounts: true }],
['filterTestAccounts forced off', { filterTestAccounts: false }],
+ ['filterTestAccounts explicitly cleared', { filterTestAccounts: null }],
['ignoreDashboardFilters set', { ignoreDashboardFilters: true }],
]
test.each(nonEmptyCases)('returns false for %s', (_, filter) => {
- expect(isDashboardFilterEmpty(filter)).toBe(false)
+ expect(isDashboardFilterOverrideEmpty(filter)).toBe(false)
})
})
diff --git a/frontend/src/scenes/dashboard/dashboardFilterEmpty.ts b/frontend/src/scenes/dashboard/dashboardFilterEmpty.ts
index 0727140986c0..d250c0c9f16a 100644
--- a/frontend/src/scenes/dashboard/dashboardFilterEmpty.ts
+++ b/frontend/src/scenes/dashboard/dashboardFilterEmpty.ts
@@ -1,15 +1,15 @@
import { DashboardFilter, TileFilters } from '~/queries/schema/schema-general'
-/** True when the filter carries no meaningful constraint (dashboard / tile override payloads). */
-export function isDashboardFilterEmpty(filter: DashboardFilter | TileFilters | null | undefined): boolean {
+/** True when the filter does not override a saved dashboard or tile filter. */
+export function isDashboardFilterOverrideEmpty(filter: DashboardFilter | TileFilters | null | undefined): boolean {
return (
!filter ||
- (filter.date_from == null &&
- filter.date_to == null &&
- (filter.properties == null || (Array.isArray(filter.properties) && filter.properties.length === 0)) &&
- filter.breakdown_filter == null &&
- filter.interval == null &&
- filter.filterTestAccounts == null &&
+ (filter.date_from === undefined &&
+ filter.date_to === undefined &&
+ filter.properties === undefined &&
+ filter.breakdown_filter === undefined &&
+ filter.interval === undefined &&
+ filter.filterTestAccounts === undefined &&
!(filter as TileFilters).ignoreDashboardFilters)
)
}
diff --git a/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts b/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts
index eedbd7636f14..50329a742509 100644
--- a/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboardInsightColorsModalLogic.ts
@@ -2,7 +2,7 @@ import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } fro
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
-import { DashboardMode, DashboardTile, QueryBasedInsightModel } from '~/types'
+import { DashboardTile, QueryBasedInsightModel } from '~/types'
import {
BreakdownColorConfig,
@@ -105,7 +105,7 @@ export const dashboardInsightColorsModalLogic = kea<dashboardInsightColorsModalL
? {
colors: mountedDashboardLogic.values.temporaryBreakdownColors,
themeId: mountedDashboardLogic.values.temporaryDataColorThemeId,
- wasInEditMode: mountedDashboardLogic.values.dashboardMode === DashboardMode.Edit,
+ wasInEditMode: mountedDashboardLogic.values.dashboardEditing !== null,
}
: null
)
@@ -119,10 +119,10 @@ export const dashboardInsightColorsModalLogic = kea<dashboardInsightColorsModalL
// Edit mode predates the modal, so filter or layout edits may be pending.
// Revert only the color state and leave the rest of the edit session alone.
mountedDashboardLogic.actions.restoreTemporaryColorState(stateAtOpen.colors, stateAtOpen.themeId)
- } else if (mountedDashboardLogic.values.dashboardMode === DashboardMode.Edit) {
+ } else if (mountedDashboardLogic.values.dashboardEditing !== null) {
// The modal entered edit mode itself, so the color edits are the only unsaved
// changes and a full discard both reverts them and exits edit mode.
- mountedDashboardLogic.actions.setDashboardMode(
+ mountedDashboardLogic.actions.setDashboardEditing(
null,
DashboardEventSource.DashboardHeaderDiscardChanges
)
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index 47a6aab98702..e9f308e95840 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -32,12 +32,13 @@ import { variableDataLogic } from '~/queries/nodes/DataVisualization/Components/
import { HogQLVariable, InsightVizNode, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import {
- DashboardMode,
DashboardPlacement,
DashboardTile,
DashboardType,
InsightColor,
InsightShortId,
+ PropertyFilterType,
+ PropertyOperator,
QueryBasedInsightModel,
} from '~/types'
@@ -502,7 +503,7 @@ describe('dashboardLogic', () => {
jest.spyOn(api, 'update')
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.saveLayoutChanges()
}).toFinishAllListeners()
expect(api.update).not.toHaveBeenCalled()
@@ -525,12 +526,17 @@ describe('dashboardLogic', () => {
await expectLogic(logic, () => {
logic.actions.updateLayouts(modifiedLayouts)
+ logic.actions.setBreakdownColorConfig({
+ breakdownValue: 'x',
+ breakdownType: 'event',
+ colorToken: 'preset-1',
+ })
}).toFinishAllListeners()
jest.spyOn(api, 'update')
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.saveLayoutChanges()
}).toFinishAllListeners()
expect(api.update).toHaveBeenCalledTimes(1)
@@ -540,48 +546,627 @@ describe('dashboardLogic', () => {
tiles: expect.any(Array),
})
)
+ const payload = (api.update as jest.Mock).mock.calls.at(-1)[1]
+ expect(payload).not.toHaveProperty('breakdown_colors')
+ expect(payload).not.toHaveProperty('data_color_theme_id')
+ expect(logic.values.hasUnsavedColorChanges).toBe(true)
+ })
+
+ it('keeps saved settings when an older layout save finishes later', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ const staleLayoutResponse = logic.values.dashboard!
+ let finishLayoutSave: (dashboard: DashboardType<QueryBasedInsightModel>) => void = () => {
+ throw new Error('Layout save resolver is unavailable')
+ }
+ const layoutSave = new Promise<DashboardType<QueryBasedInsightModel>>((resolve) => {
+ finishLayoutSave = resolve
+ })
+ jest.spyOn(api, 'update')
+ .mockReturnValueOnce(layoutSave)
+ .mockImplementationOnce(async () => ({
+ ...logic.values.dashboard!,
+ persisted_filters: { date_from: '-7d' },
+ }))
+
+ const firstTile = logic.values.dashboard!.tiles[0]
+ const modifiedLayouts = {
+ ...logic.values.layouts,
+ sm: logic.values.layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: (layout.x ?? 0) + 1 } : layout
+ ),
+ }
+ logic.actions.updateLayouts(modifiedLayouts)
+ logic.actions.saveLayoutChanges()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ logic.actions.saveDashboardChanges()
+ }).toDispatchActions(['saveDashboardChangesSuccess'])
+
+ finishLayoutSave(staleLayoutResponse)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.dashboard?.persisted_filters).toEqual({ date_from: '-7d' })
})
- it('saving after filter change calls api', async () => {
+ it('saves dashboard settings only when requested', async () => {
await expectLogic(logic).toFinishAllListeners()
+ const successToast = jest.spyOn(lemonToast, 'success')
await expectLogic(logic, () => {
logic.actions.setDates('-7d', null)
}).toFinishAllListeners()
- jest.spyOn(api, 'update')
+ jest.spyOn(api, 'update').mockResolvedValueOnce({
+ ...logic.values.dashboard!,
+ persisted_filters: logic.values.effectiveEditBarFilters,
+ })
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.saveDashboardChanges()
}).toFinishAllListeners()
expect(api.update).toHaveBeenCalledTimes(1)
- expect(api.update).toHaveBeenCalledWith(
- `api/environments/${MOCK_TEAM_ID}/dashboards/5`,
- expect.objectContaining({
- filters: expect.objectContaining({ date_from: '-7d' }),
+ expect(api.update).toHaveBeenCalledWith(`api/environments/${MOCK_TEAM_ID}/dashboards/5`, {
+ filters: expect.objectContaining({ date_from: '-7d' }),
+ variables: {},
+ })
+ expect(logic.values.dashboard?.persisted_filters).toEqual(expect.objectContaining({ date_from: '-7d' }))
+ expect(successToast).toHaveBeenCalledWith('Dashboard changes saved')
+ })
+
+ it('counts each added property filter', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setProperties([
+ {
+ key: 'browser',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'Chrome',
+ },
+ { key: 'os', type: PropertyFilterType.Event, operator: PropertyOperator.Exact, value: 'macOS' },
+ ])
+ }).toFinishAllListeners()
+
+ expect(logic.values.changedFilterCount).toBe(2)
+ })
+
+ it('clears the unsaved state when a filter returns to inherit', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setInterval('week')
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardSettingsState).toBe('unsavedChanges')
+
+ await expectLogic(logic, () => {
+ logic.actions.setInterval(null)
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardSettingsState).toBe('saved')
+ expect(logic.values.dashboardSettingsChanges).toEqual([])
+ })
+
+ it('does not treat embedded context filters as unsaved dashboard filters', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ ;(api.update as jest.Mock).mockClear()
+
+ await expectLogic(logic, () => {
+ logic.actions.setExternalFilters({
+ properties: [
+ {
+ key: '$group_0',
+ type: PropertyFilterType.EventMetadata,
+ operator: PropertyOperator.Exact,
+ value: 'group-1',
+ },
+ ],
})
- )
+ }).toFinishAllListeners()
+
+ expect(logic.values.effectiveEditBarFilters.properties).toEqual([
+ expect.objectContaining({ key: '$group_0', value: 'group-1' }),
+ ])
+ expect(logic.values.filtersDirty).toBe(false)
+ expect(logic.values.filterChanges).toEqual([])
+ expect(logic.values.dashboardSettingsState).toBe('saved')
+
+ await expectLogic(logic, () => {
+ logic.actions.saveDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(api.update).not.toHaveBeenCalled()
+ })
+
+ it('saving a layout change does not persist temporary filters', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ const firstTile = logic.values.dashboard!.tiles[0]
+ const currentLayouts = logic.values.layouts
+ const modifiedLayouts: any = {
+ ...currentLayouts,
+ sm: currentLayouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: (layout.x ?? 0) + 1 } : layout
+ ),
+ }
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ logic.actions.updateLayouts(modifiedLayouts)
+ }).toFinishAllListeners()
+
+ jest.spyOn(api, 'update')
+
+ await expectLogic(logic, () => {
+ logic.actions.saveLayoutChanges()
+ }).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenCalledTimes(1)
+ const payload = (api.update as jest.Mock).mock.calls.at(-1)[1]
+ expect(payload).toEqual(expect.objectContaining({ tiles: expect.any(Array) }))
+ expect(payload).not.toHaveProperty('filters')
+ })
+
+ it('saving a layout change keeps unsaved filters in filter edit mode', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ logic.actions.setDates('-7d', null)
+ logic.actions.saveLayout()
+ }).toFinishAllListeners()
+
+ expect(logic.values.urlFilters).toEqual(expect.objectContaining({ date_from: '-7d' }))
+ expect(logic.values.dashboard?.persisted_filters || {}).toEqual({})
+ expect(logic.values.dashboardEditing).toEqual({ filters: true, layout: false })
+ expect(logic.values.layoutEditMode).toBe(false)
+ expect(logic.values.filtersDirty).toBe(true)
+ })
+
+ it('saving a layout change with no unsaved settings leaves edit mode', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ logic.actions.saveLayout()
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardMode).toBeNull()
+ expect(logic.values.layoutEditMode).toBe(false)
+ expect(logic.values.filterEditModeActive).toBe(false)
+ })
+
+ const filterEditExitCases: [string, () => void][] = [
+ ['saving them', () => logic.actions.saveDashboardChanges()],
+ ['discarding them', () => logic.actions.discardDashboardChanges()],
+ ['undoing them by hand', () => logic.actions.setInterval(null)],
+ ]
+
+ it.each(filterEditExitCases)('leaves filter edit mode after %s', async (_name, resolveChanges) => {
+ await expectLogic(logic).toFinishAllListeners()
+ const update = jest.spyOn(api, 'update').mockResolvedValue({
+ ...logic.values.dashboard!,
+ persisted_filters: { interval: 'week' },
+ })
+
+ try {
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
+ logic.actions.setInterval('week')
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardEditing).toEqual({ filters: true, layout: false })
+
+ await expectLogic(logic, resolveChanges).toFinishAllListeners()
+
+ expect(logic.values.dashboardSettingsState).toBe('saved')
+ expect(logic.values.dashboardMode).toBeNull()
+ } finally {
+ update.mockRestore()
+ }
})
- it('dashboard save after changing global dates runs tile refresh to repopulate insight results missing from PATCH', async () => {
+ it('stays in layout editing when a filter change is saved', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ const update = jest.spyOn(api, 'update').mockResolvedValue({
+ ...logic.values.dashboard!,
+ persisted_filters: { interval: 'week' },
+ })
+
+ try {
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ logic.actions.setInterval('week')
+ logic.actions.saveDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardSettingsState).toBe('saved')
+ expect(logic.values.dashboardEditing).toEqual({ filters: true, layout: true })
+ expect(logic.values.layoutEditMode).toBe(true)
+ } finally {
+ update.mockRestore()
+ }
+ })
+
+ it('keeps layout editing after a filter change', async () => {
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
logic.actions.setDates('-7d', null)
}).toFinishAllListeners()
+ expect(logic.values.dashboardEditing).toEqual({ filters: true, layout: true })
+ expect(logic.values.layoutEditMode).toBe(true)
+ })
+
+ it('cancelling layout editing keeps auto-previewed filter changes', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ }).toFinishAllListeners()
+
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ expect(logic.values.urlFilters).toEqual(expect.objectContaining({ date_from: '-7d' }))
+
+ await expectLogic(logic, () => {
+ logic.actions.cancelLayoutEdit()
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardMode).toBeNull()
+ expect(logic.values.dashboardSettingsDraft?.filters).toEqual(expect.objectContaining({ date_from: '-7d' }))
+ expect(logic.values.filtersDirty).toBe(true)
+ expect(logic.values.dashboardSettingsState).toBe('unsavedChanges')
+ })
+
+ it('cancelling layout editing keeps unapplied filter changes', async () => {
+ const payloadSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(1)
+
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.canAutoPreview).toBe(false)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardSettingsDraft?.filters).toEqual(expect.objectContaining({ date_from: '-7d' }))
+
+ await expectLogic(logic, () => {
+ logic.actions.cancelLayoutEdit()
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardMode).toBeNull()
+ expect(logic.values.dashboardSettingsDraft?.filters).toEqual(expect.objectContaining({ date_from: '-7d' }))
+ expect(logic.values.filtersDirty).toBe(true)
+
+ payloadSpy.mockRestore()
+ })
+
+ it('saving current filters does not refresh tiles again', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.saveDashboardChanges()
+ })
+ .toDispatchActions(['saveDashboardChanges', 'saveDashboardChangesSuccess'])
+ .toFinishAllListeners()
+ })
+
+ it('saving unapplied dashboard settings refreshes tiles above the auto-preview limit', async () => {
+ const payloadSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(1)
+
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.canAutoPreview).toBe(false)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.saveDashboardChanges()
})
- .toDispatchActions(['saveEditModeChanges', 'saveEditModeChangesSuccess', 'refreshDashboardItems'])
+ .toDispatchActions(['saveDashboardChanges', 'saveDashboardChangesSuccess', 'refreshDashboardItems'])
.toFinishAllListeners()
+
+ payloadSpy.mockRestore()
+ })
+
+ it('keeps combined auto-preview filters after a page reload, then clears and saves them', async () => {
+ const sevenTileDashboard = {
+ ...dashboards[5],
+ tiles: Array.from({ length: 7 }, (_, index) => ({
+ ...dashboards[5].tiles[0],
+ id: index + 100,
+ layouts: {},
+ })),
+ }
+ logic.unmount()
+ logic = dashboardLogic({ id: 5, dashboard: sevenTileDashboard })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.canAutoPreview).toBe(true)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.setProperties([
+ {
+ key: 'browser',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'Chrome',
+ },
+ ])
+ }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.setBreakdownFilter({ breakdown: '$browser', breakdown_type: 'event' })
+ }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.setInterval('week')
+ }).toFinishAllListeners()
+
+ const filters = {
+ date_from: '-7d',
+ properties: [
+ {
+ key: 'browser',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'Chrome',
+ },
+ ],
+ breakdown_filter: { breakdown: '$browser', breakdown_type: 'event' },
+ interval: 'week',
+ }
+
+ expect(logic.values.urlFilters).toEqual(expect.objectContaining(filters))
+
+ logic.unmount()
+ logic = dashboardLogic({ id: 5, dashboard: sevenTileDashboard })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.effectiveEditBarFilters).toEqual(expect.objectContaining(filters))
+
+ await expectLogic(logic, () => {
+ logic.actions.discardDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(logic.values.urlFilters).toEqual({})
+ expect(logic.values.filtersDirty).toBe(false)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-1d', null)
+ }).toFinishAllListeners()
+
+ jest.spyOn(api, 'update').mockResolvedValueOnce({
+ ...sevenTileDashboard,
+ persisted_filters: { date_from: '-1d' },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.saveDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboard?.persisted_filters).toEqual({ date_from: '-1d' })
+ expect(logic.values.urlFilters).toEqual({})
+ })
+
+ it('keeps unapplied filters separate from layout cancellation and layout saving', async () => {
+ const autoPreviewLimitSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(8)
+ const nineTileDashboard: DashboardType<QueryBasedInsightModel> = {
+ ...dashboards[5],
+ tiles: Array.from({ length: 9 }, (_, index) => ({
+ ...dashboards[5].tiles[0],
+ id: index + 200,
+ layouts: {
+ sm: { i: String(index + 200), x: index, y: 0, w: 1, h: 1 },
+ xs: { i: String(index + 200), x: 0, y: index, w: 1, h: 1 },
+ },
+ })),
+ }
+ logic.unmount()
+ logic = dashboardLogic({ id: 5, dashboard: nineTileDashboard })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.canAutoPreview).toBe(false)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.setProperties([
+ {
+ key: 'browser',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'Chrome',
+ },
+ ])
+ }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.setBreakdownFilter({ breakdown: '$browser', breakdown_type: 'event' })
+ }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.setInterval('week')
+ logic.actions.setFilterTestAccounts(true)
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardSettingsDraft?.filters).toEqual(
+ expect.objectContaining({
+ date_from: '-7d',
+ properties: [expect.objectContaining({ key: 'browser', value: 'Chrome' })],
+ breakdown_filter: { breakdown: '$browser', breakdown_type: 'event' },
+ interval: 'week',
+ filterTestAccounts: true,
+ })
+ )
+ expect(logic.values.urlFilters).toEqual(
+ expect.objectContaining({
+ date_from: '-7d',
+ properties: [expect.objectContaining({ key: 'browser', value: 'Chrome' })],
+ breakdown_filter: { breakdown: '$browser', breakdown_type: 'event' },
+ interval: 'week',
+ filterTestAccounts: true,
+ })
+ )
+
+ logic.unmount()
+ logic = dashboardLogic({ id: 5, dashboard: nineTileDashboard })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.currentDashboardSettings.filters).toEqual(
+ expect.objectContaining({
+ date_from: '-7d',
+ properties: [expect.objectContaining({ key: 'browser', value: 'Chrome' })],
+ breakdown_filter: { breakdown: '$browser', breakdown_type: 'event' },
+ interval: 'week',
+ filterTestAccounts: true,
+ })
+ )
+ expect(logic.values.previewedDashboardSettings?.filters).toEqual(
+ expect.objectContaining({
+ date_from: '-7d',
+ properties: [expect.objectContaining({ key: 'browser', value: 'Chrome' })],
+ breakdown_filter: { breakdown: '$browser', breakdown_type: 'event' },
+ interval: 'week',
+ filterTestAccounts: true,
+ })
+ )
+ expect(logic.values.loadingPreview).toBe(true)
+
+ await expectLogic(logic, () => {
+ logic.actions.previewDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(logic.values.currentDashboardSettings.filters).toEqual(expect.objectContaining({ date_from: '-7d' }))
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ }).toFinishAllListeners()
+
+ const firstTile = logic.values.dashboard!.tiles[0]
+ const changedLayouts = {
+ ...logic.values.layouts,
+ sm: logic.values.layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: (layout.x ?? 0) + 1 } : layout
+ ),
+ }
+ await expectLogic(logic, () => {
+ logic.actions.updateLayouts(changedLayouts)
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.cancelLayoutEdit()
+ }).toFinishAllListeners()
+
+ expect(logic.values.currentDashboardSettings.filters).toEqual(expect.objectContaining({ date_from: '-7d' }))
+ expect(logic.values.dashboardSettingsState).toBe('unsavedChanges')
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.updateLayouts(changedLayouts)
+ }).toFinishAllListeners()
+
+ ;(api.update as jest.Mock).mockClear()
+ ;(api.update as jest.Mock).mockResolvedValueOnce({
+ ...nineTileDashboard,
+ persisted_filters: logic.values.effectiveEditBarFilters,
+ })
+ await expectLogic(logic, () => {
+ logic.actions.saveDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
+ expect(logic.values.dashboard?.tiles[0].layouts).toEqual(
+ changedLayouts.sm?.[0] ? { sm: changedLayouts.sm[0] } : {}
+ )
+
+ ;(api.update as jest.Mock).mockResolvedValueOnce({
+ ...nineTileDashboard,
+ persisted_filters: { date_from: '-7d' },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.saveLayoutChanges()
+ }).toFinishAllListeners()
+
+ expect(api.update).toHaveBeenLastCalledWith(
+ `api/environments/${MOCK_TEAM_ID}/dashboards/5`,
+ expect.not.objectContaining({ filters: expect.anything() })
+ )
+ expect(logic.values.dashboard?.persisted_filters).toEqual(expect.objectContaining({ date_from: '-7d' }))
+ expect(logic.values.urlFilters).toEqual({})
+ expect(logic.values.dashboardSettingsDraft).toBeNull()
+
+ autoPreviewLimitSpy.mockRestore()
})
it('saving after breakdown color change calls api', async () => {
await expectLogic(logic).toFinishAllListeners()
+ const firstTile = logic.values.dashboard!.tiles[0]
+ const currentLayouts = logic.values.layouts
+ const modifiedLayouts: any = {
+ ...currentLayouts,
+ sm: currentLayouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: (layout.x ?? 0) + 1 } : layout
+ ),
+ }
+
await expectLogic(logic, () => {
+ logic.actions.updateLayouts(modifiedLayouts)
logic.actions.setBreakdownColorConfig({
breakdownValue: 'x',
breakdownType: 'event',
@@ -592,7 +1177,7 @@ describe('dashboardLogic', () => {
jest.spyOn(api, 'update')
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.saveDashboardColorChanges()
}).toFinishAllListeners()
expect(api.update).toHaveBeenCalledTimes(1)
@@ -604,6 +1189,9 @@ describe('dashboardLogic', () => {
]),
})
)
+ const payload = (api.update as jest.Mock).mock.calls.at(-1)[1]
+ expect(payload).not.toHaveProperty('tiles')
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
})
it('discarding edit mode reverts unsaved color edits', async () => {
@@ -625,7 +1213,7 @@ describe('dashboardLogic', () => {
expect(logic.values.hasUnsavedColorChanges).toBe(true)
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
}).toFinishAllListeners()
expect(
@@ -639,7 +1227,10 @@ describe('dashboardLogic', () => {
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardInsightColorsModal)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardInsightColorsModal
+ )
logic.actions.setBreakdownColorConfig({
breakdownValue: 'x',
breakdownType: 'event',
@@ -650,7 +1241,7 @@ describe('dashboardLogic', () => {
jest.spyOn(api, 'update')
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardInsightColorsModal)
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardInsightColorsModal)
})
.toDispatchActions(['saveEditModeChanges', 'saveEditModeChangesSuccess'])
.toFinishAllListeners()
@@ -772,7 +1363,7 @@ describe('dashboardLogic', () => {
jest.spyOn(api, 'update')
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.saveDashboardColorChanges()
}).toFinishAllListeners()
expect(api.update).toHaveBeenCalledWith(
@@ -838,7 +1429,7 @@ describe('dashboardLogic', () => {
jest.spyOn(api, 'update')
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.saveDashboardColorChanges()
}).toFinishAllListeners()
// the entry survives the save instead of being pruned from the partial tile set
@@ -862,7 +1453,7 @@ describe('dashboardLogic', () => {
jest.spyOn(api, 'update')
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.saveDashboardColorChanges()
}).toFinishAllListeners()
expect(api.update).toHaveBeenCalledTimes(1)
@@ -893,7 +1484,7 @@ describe('dashboardLogic', () => {
const successToast = jest.spyOn(lemonToast, 'success')
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.saveLayoutChanges()
}).toFinishAllListeners()
expect(successToast).toHaveBeenCalledWith('Dashboard saved')
@@ -905,7 +1496,7 @@ describe('dashboardLogic', () => {
const successToast = jest.spyOn(lemonToast, 'success')
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.saveLayoutChanges()
}).toFinishAllListeners()
expect(successToast).not.toHaveBeenCalled()
@@ -937,250 +1528,129 @@ describe('dashboardLogic', () => {
const editedTileLayouts = logic.values.dashboard?.tiles.find((t) => t.id === firstTile.id)?.layouts
expect(editedTileLayouts).not.toEqual(originalLayouts)
- await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
- }).toFinishAllListeners()
-
- const restoredTileLayouts = logic.values.dashboard?.tiles.find((t) => t.id === firstTile.id)?.layouts
- expect(restoredTileLayouts).toEqual(originalLayouts)
- })
-
- describe('layoutEditMode', () => {
- it('enters edit mode without layout editing when filters change', async () => {
- await expectLogic(logic).toFinishAllListeners()
-
- await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
- })
- .toFinishAllListeners()
- .toMatchValues({
- dashboardMode: DashboardMode.Edit,
- layoutEditMode: false,
- })
- })
-
- it('enables layout editing for explicit layout edit sources', async () => {
- await expectLogic(logic).toFinishAllListeners()
-
- await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.SceneCommonButtons)
- })
- .toFinishAllListeners()
- .toMatchValues({
- dashboardMode: DashboardMode.Edit,
- layoutEditMode: true,
- })
- })
-
- it('clears layout editing when exiting edit mode', async () => {
- await expectLogic(logic).toFinishAllListeners()
-
- await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.SceneCommonButtons)
- }).toFinishAllListeners()
-
- await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
- })
- .toFinishAllListeners()
- .toMatchValues({
- dashboardMode: null,
- layoutEditMode: false,
- })
- })
-
- it('reports filter changes separately from layout edit mode entry', async () => {
- const reportFiltersChanged = jest.spyOn(eventUsageLogic.actions, 'reportDashboardFiltersChanged')
- const reportLayoutEditEntered = jest.spyOn(
- eventUsageLogic.actions,
- 'reportDashboardLayoutEditModeEntered'
- )
- const reportModeToggled = jest.spyOn(eventUsageLogic.actions, 'reportDashboardModeToggled')
-
- await expectLogic(logic).toFinishAllListeners()
-
- await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
- }).toFinishAllListeners()
-
- expect(reportLayoutEditEntered).not.toHaveBeenCalled()
- expect(reportModeToggled).not.toHaveBeenCalled()
-
- await expectLogic(logic, () => {
- logic.actions.setDates('-7d', null)
- }).toFinishAllListeners()
-
- expect(reportFiltersChanged).toHaveBeenCalledWith(
- expect.objectContaining({ id: 5 }),
- 'date',
- expect.objectContaining({ date_from: '-7d', date_to: null })
- )
-
- reportFiltersChanged.mockClear()
- reportLayoutEditEntered.mockClear()
- reportModeToggled.mockClear()
-
- await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.SceneCommonButtons)
- }).toFinishAllListeners()
-
- expect(reportLayoutEditEntered).toHaveBeenCalledWith(
- expect.objectContaining({ id: 5 }),
- DashboardEventSource.SceneCommonButtons,
- 1
- )
- expect(reportModeToggled).toHaveBeenCalledWith(
- expect.objectContaining({ id: 5 }),
- DashboardMode.Edit,
- DashboardEventSource.SceneCommonButtons,
- 1,
- true
- )
- expect(reportFiltersChanged).not.toHaveBeenCalled()
-
- reportFiltersChanged.mockRestore()
- reportLayoutEditEntered.mockRestore()
- reportModeToggled.mockRestore()
- })
-
- it('restoreUrlStateAtEditModeEntry applies snapshot payload to url', async () => {
- const editedFilters = JSON.stringify({ date_from: '-14d', date_to: null })
- const originalFilters = JSON.stringify({ date_from: '-7d', date_to: null })
-
- logic.unmount()
- router.actions.push('/dashboard/5', {
- [dashboardUtils.SEARCH_PARAM_FILTERS_KEY]: editedFilters,
- })
- logic = dashboardLogic({ id: 5 })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- await expectLogic(logic, () => {
- logic.actions.restoreUrlStateAtEditModeEntry({
- filters: originalFilters,
- variables: undefined,
- })
- }).toFinishAllListeners()
-
- expect(router.values.searchParams[dashboardUtils.SEARCH_PARAM_FILTERS_KEY]).toBe(originalFilters)
- })
-
- it('discarding filter edit passes url snapshot into restore action', async () => {
- const originalFilters = JSON.stringify({ date_from: '-7d', date_to: null })
-
- logic.unmount()
- router.actions.push('/dashboard/5', {
- [dashboardUtils.SEARCH_PARAM_FILTERS_KEY]: originalFilters,
- })
- logic = dashboardLogic({ id: 5 })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ }).toFinishAllListeners()
- expect(logic.values.urlFilters).toEqual(expect.objectContaining({ date_from: '-7d' }))
- expect(logic.values.urlSearchParamsAtEditModeEntry).toBeNull()
+ const restoredTileLayouts = logic.values.dashboard?.tiles.find((t) => t.id === firstTile.id)?.layouts
+ expect(restoredTileLayouts).toEqual(originalLayouts)
+ })
- const restoreSpy = jest.spyOn(logic.actions, 'restoreUrlStateAtEditModeEntry')
+ describe('layoutEditMode', () => {
+ it('enters edit mode without layout editing when filters change', async () => {
+ await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
})
.toFinishAllListeners()
.toMatchValues({
- urlSearchParamsAtEditModeEntry: {
- filters: originalFilters,
- variables: undefined,
- },
+ dashboardEditing: { filters: true, layout: false },
+ layoutEditMode: false,
})
+ })
- await expectLogic(logic, () => {
- logic.actions.setDates('-14d', null)
- }).toFinishAllListeners()
-
- restoreSpy.mockClear()
+ it('enables layout editing for explicit layout edit sources', async () => {
+ await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
- }).toFinishAllListeners()
-
- expect(restoreSpy).toHaveBeenCalledWith({
- filters: originalFilters,
- variables: undefined,
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
})
-
- restoreSpy.mockRestore()
+ .toFinishAllListeners()
+ .toMatchValues({
+ dashboardEditing: { filters: true, layout: true },
+ layoutEditMode: true,
+ })
})
- it('discarding after a previewed filter change reloads tiles', async () => {
+ it('clears layout editing when exiting edit mode', async () => {
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
- logic.actions.setDates('-14d', null)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
}).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
})
- .toDispatchActions([
- // anchor at the discard dispatch, so the refresh matched below is the
- // discard-triggered one and not an earlier (initial load / preview) one
- logic.actionCreators.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges),
- 'refreshDashboardItems',
- ])
.toFinishAllListeners()
+ .toMatchValues({
+ dashboardEditing: null,
+ layoutEditMode: false,
+ })
})
- it('discarding without a previewed filter change does not reload tiles', async () => {
+ it('reports filter changes separately from layout edit mode entry', async () => {
+ const reportFiltersChanged = jest.spyOn(eventUsageLogic.actions, 'reportDashboardFiltersChanged')
+ const reportLayoutEditEntered = jest.spyOn(
+ eventUsageLogic.actions,
+ 'reportDashboardLayoutEditModeEntered'
+ )
+ const reportModeToggled = jest.spyOn(eventUsageLogic.actions, 'reportDashboardModeToggled')
+
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.SceneCommonButtons)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
}).toFinishAllListeners()
+ expect(reportLayoutEditEntered).not.toHaveBeenCalled()
+ expect(reportModeToggled).not.toHaveBeenCalled()
+
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
- })
- .toDispatchActions([
- // anchor at the discard dispatch, so only actions after it are considered
- logic.actionCreators.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges),
- ])
- .toFinishAllListeners()
- .toNotHaveDispatchedActions(['refreshDashboardItems'])
- })
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
- it('discarding an unapplied filter edit above the auto-preview limit does not reload tiles', async () => {
- // The skip-reload check relies on unpreviewed edits never reaching the URL:
- // when the dashboard is over the auto-preview limit, filter edits stay
- // intermittent (no URL write, no refresh) until "Apply filters" is clicked.
- const payloadSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(1)
+ expect(reportFiltersChanged).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 5 }),
+ 'date',
+ expect.objectContaining({ date_from: '-7d', date_to: null })
+ )
- await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.canAutoPreview).toBe(false)
+ reportFiltersChanged.mockClear()
+ reportLayoutEditEntered.mockClear()
+ reportModeToggled.mockClear()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
- logic.actions.setDates('-14d', null)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
}).toFinishAllListeners()
- expect(router.values.searchParams[dashboardUtils.SEARCH_PARAM_FILTERS_KEY]).toBeUndefined()
-
- await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
- })
- .toDispatchActions([
- logic.actionCreators.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges),
- ])
- .toFinishAllListeners()
- .toNotHaveDispatchedActions(['refreshDashboardItems'])
+ expect(reportLayoutEditEntered).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 5 }),
+ DashboardEventSource.SceneCommonButtons,
+ 1
+ )
+ expect(reportModeToggled).not.toHaveBeenCalled()
+ expect(reportFiltersChanged).not.toHaveBeenCalled()
- payloadSpy.mockRestore()
+ reportFiltersChanged.mockRestore()
+ reportLayoutEditEntered.mockRestore()
+ reportModeToggled.mockRestore()
})
- it('filter edit source clears layout edit mode', async () => {
+ it('filter edits preserve layout editing', async () => {
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.SceneCommonButtons)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
})
.toFinishAllListeners()
.toMatchValues({
@@ -1188,11 +1658,14 @@ describe('dashboardLogic', () => {
})
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.DashboardFilters
+ )
})
.toFinishAllListeners()
.toMatchValues({
- layoutEditMode: false,
+ layoutEditMode: true,
})
})
})
@@ -1211,24 +1684,6 @@ describe('dashboardLogic', () => {
await expectLogic(logic).toFinishAllListeners()
}
- // The overrides banner renders off hasUrlFilters. An override that constrains nothing still
- // has keys, so testing for key presence announces overrides on a dashboard that is showing
- // exactly its saved state. A back link from an insight writes the saved filters into the url,
- // which is that same state.
- const activeOverrideCases: [string, Record<string, any>, number, boolean][] = [
- ['a date override is active', { date_from: '-7d', date_to: null }, 5, true],
- ['a property override is active', { properties: PROPERTY_OVERRIDE }, 5, true],
- ['properties cleared to empty is not active', { properties: [] }, 5, false],
- ['a url that repeats the saved filters is not active', { date_from: '-24h' }, 12, false],
- ['a url that changes a saved filter is active', { date_from: '-7d' }, 12, true],
- ]
-
- it.each(activeOverrideCases)('%s', async (_name, urlFilters, dashboardId, expected) => {
- await openWithUrlFilters(urlFilters, dashboardId)
-
- expect(logic.values.hasUrlFilters).toBe(expected)
- })
-
it('drops the url param when the last filter is cleared', async () => {
await openWithUrlFilters({ properties: PROPERTY_OVERRIDE })
expect(router.values.searchParams[dashboardUtils.SEARCH_PARAM_FILTERS_KEY]).not.toBeUndefined()
@@ -1239,6 +1694,74 @@ describe('dashboardLogic', () => {
expect(router.values.searchParams[dashboardUtils.SEARCH_PARAM_FILTERS_KEY]).toBeUndefined()
})
+
+ const historyRefreshCases: [string, Record<string, any>, boolean][] = [
+ [
+ 'refreshes the tiles when browser history changes the filters',
+ { [dashboardUtils.SEARCH_PARAM_FILTERS_KEY]: JSON.stringify({ date_from: '-7d', date_to: null }) },
+ true,
+ ],
+ ['leaves the tiles alone when browser history changes nothing', {}, false],
+ ]
+
+ it.each(historyRefreshCases)('%s', async (_name, searchParams, expectedRefresh) => {
+ await openWithUrlFilters({})
+ const getInsightWithRetrySpy = jest
+ .spyOn(dashboardUtils, 'getInsightWithRetry')
+ .mockImplementation(async (_teamId, insight) => insight)
+
+ try {
+ await expectLogic(logic, () => {
+ router.actions.locationChanged({
+ method: 'POP',
+ pathname: '/dashboard/5',
+ search: '',
+ searchParams,
+ hash: '',
+ hashParams: {},
+ url: '/dashboard/5',
+ })
+ }).toFinishAllListeners()
+
+ if (expectedRefresh) {
+ expect(getInsightWithRetrySpy).toHaveBeenCalled()
+ } else {
+ expect(getInsightWithRetrySpy).not.toHaveBeenCalled()
+ }
+ } finally {
+ getInsightWithRetrySpy.mockRestore()
+ }
+ })
+
+ it('restores filters when browser history changes the URL', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-30d', null)
+ }).toFinishAllListeners()
+
+ const searchParams = {
+ [dashboardUtils.SEARCH_PARAM_FILTERS_KEY]: JSON.stringify({ date_from: '-7d', date_to: null }),
+ }
+ await expectLogic(logic, () => {
+ router.actions.locationChanged({
+ method: 'POP',
+ pathname: '/dashboard/5',
+ search: '',
+ searchParams,
+ hash: '',
+ hashParams: {},
+ url: '/dashboard/5',
+ })
+ }).toFinishAllListeners()
+
+ expect(logic.values.currentDashboardSettings.filters).toEqual(
+ expect.objectContaining({ date_from: '-7d', date_to: null })
+ )
+ expect(logic.values.filtersOverrideForLoad).toEqual(
+ expect.objectContaining({ date_from: '-7d', date_to: null })
+ )
+ })
})
describe('hasUnsavedLayoutChanges selector', () => {
@@ -1285,7 +1808,7 @@ describe('dashboardLogic', () => {
.toMatchValues({ hasUnsavedLayoutChanges: true })
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
})
.toFinishAllListeners()
.toMatchValues({ hasUnsavedLayoutChanges: false })
@@ -1350,7 +1873,7 @@ describe('dashboardLogic', () => {
})
})
- describe('cancelEditMode action', () => {
+ describe('cancelLayoutEdit action', () => {
// The discard prompt renders a real dialog into its own React root, whose async
// updates land outside act(); these tests only assert dispatched actions
let dialogOpenSpy: jest.SpyInstance
@@ -1385,9 +1908,9 @@ describe('dashboardLogic', () => {
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.cancelEditMode()
+ logic.actions.cancelLayoutEdit()
}).toDispatchActions([
- logic.actionCreators.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges),
+ logic.actionCreators.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges),
])
})
@@ -1398,9 +1921,9 @@ describe('dashboardLogic', () => {
await expectLogic(logic, moveFirstTile).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.cancelEditMode()
+ logic.actions.cancelLayoutEdit()
}).toNotHaveDispatchedActions([
- logic.actionCreators.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges),
+ logic.actionCreators.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges),
])
})
@@ -1411,9 +1934,9 @@ describe('dashboardLogic', () => {
await expectLogic(logic, moveFirstTile).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.cancelEditMode()
+ logic.actions.cancelLayoutEdit()
}).toDispatchActions([
- logic.actionCreators.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges),
+ logic.actionCreators.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges),
])
})
})
@@ -1444,7 +1967,10 @@ describe('dashboardLogic', () => {
it('opens the modal without confirming when there are no unsaved layout changes', async () => {
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.SceneCommonButtons)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
}).toFinishAllListeners()
await expectLogic(logic, () => {
@@ -1464,7 +1990,10 @@ describe('dashboardLogic', () => {
confirmSpy.mockReturnValue(accepted)
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.SceneCommonButtons)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
}).toFinishAllListeners()
await expectLogic(logic, moveFirstTile)
.toFinishAllListeners()
@@ -1491,7 +2020,10 @@ describe('dashboardLogic', () => {
await expectLogic(logic, () => {
dashboardInsightColorsModalLogic.actions.showInsightColorsModal(5)
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardInsightColorsModal)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardInsightColorsModal
+ )
logic.actions.setBreakdownColorConfig({
breakdownValue: 'x',
breakdownType: 'event',
@@ -1516,7 +2048,10 @@ describe('dashboardLogic', () => {
await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardFilters)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
logic.actions.setDates('-7d', null)
logic.actions.setBreakdownColorConfig({
breakdownValue: 'x',
@@ -1539,7 +2074,7 @@ describe('dashboardLogic', () => {
}).toFinishAllListeners()
expect(dashboardInsightColorsModalLogic.values.isOpen).toBe(false)
- expect(logic.values.dashboardMode).toBe(DashboardMode.Edit)
+ expect(logic.values.dashboardEditing).toEqual({ filters: true, layout: false })
expect(logic.values.effectiveEditBarFilters.date_from).toBe('-7d')
expect(logic.values.temporaryBreakdownColors).toEqual([
expect.objectContaining({ breakdownValue: 'x', colorToken: 'preset-1' }),
@@ -2240,7 +2775,7 @@ describe('dashboardLogic', () => {
try {
;(api.update as jest.Mock).mockClear()
- // forceRefresh: true so every insight tile hits getInsightWithRetry (applyFilters/preview can skip fresh tiles)
+ // forceRefresh: true so every insight tile hits getInsightWithRetry because preview can skip fresh tiles
const refreshDone = expectLogic(logic, () => {
logic.actions.triggerDashboardRefresh()
}).toFinishAllListeners()
@@ -2263,7 +2798,7 @@ describe('dashboardLogic', () => {
}
logic.actions.updateLayouts(modifiedLayouts)
- logic.actions.saveEditModeChanges()
+ logic.actions.saveLayoutChanges()
// Do not use toFinishAllListeners here: it would wait for refreshDashboardItems too,
// while refresh is intentionally blocked on `barrier`.
@@ -2543,6 +3078,20 @@ describe('dashboardLogic', () => {
})
}
+ const popToSearchParams = async (searchParams: Record<string, string>): Promise<void> => {
+ await expectLogic(logic, () => {
+ router.actions.locationChanged({
+ method: 'POP',
+ pathname: '/dashboard/12',
+ search: '',
+ searchParams,
+ hash: '',
+ hashParams: {},
+ url: '/dashboard/12',
+ })
+ }).toFinishAllListeners()
+ }
+
it.each([
['url override (non-null)', 'url-val', undefined, undefined, 'url-val', false],
['url override (null)', null, undefined, undefined, null, true],
@@ -2576,17 +3125,251 @@ describe('dashboardLogic', () => {
}
)
- it('dashboard save after variable-only edits runs tile refresh to repopulate insight results missing from PATCH', async () => {
+ it('shows and saves a URL variable override as unsaved settings', async () => {
+ await mountDashboardWithVariable({ urlValue: 'url-val' })
+ const update = jest.spyOn(api, 'update').mockResolvedValue({
+ ...logic.values.dashboard!,
+ persisted_variables: {
+ [variableId]: { ...baseVariable, value: 'url-val', isNull: false },
+ },
+ })
+
+ expect(logic.values.urlVariables).toEqual({
+ [variableId]: expect.objectContaining({ code_name: 'organization', value: 'url-val' }),
+ })
+ expect(logic.values.filtersDirty).toBe(false)
+ expect(logic.values.filterChanges).toEqual([])
+ expect(logic.values.dashboardSettingsState).toBe('unsavedChanges')
+
+ await expectLogic(logic, () => {
+ logic.actions.saveDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(update).toHaveBeenCalledWith(expect.any(String), {
+ filters: {},
+ variables: {
+ [variableId]: expect.objectContaining({ value: 'url-val' }),
+ },
+ })
+ expect(router.values.searchParams).toEqual({})
+ expect(logic.values.dashboardSettingsState).toBe('saved')
+ })
+
+ it('shows filter edits as unsaved when a URL variable override exists', async () => {
+ await mountDashboardWithVariable({ urlValue: 'url-val' })
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ expect(logic.values.filtersDirty).toBe(true)
+ expect(logic.values.dashboardSettingsState).toBe('unsavedChanges')
+ })
+
+ it('treats selecting the SQL variable default as saved', async () => {
+ await mountDashboardWithVariable({})
+
+ await expectLogic(logic, () => {
+ logic.actions.overrideVariableValue(variableId, 'Default org', false)
+ }).toFinishAllListeners()
+
+ expect(logic.values.dashboardSettingsState).toBe('saved')
+ expect(logic.values.dashboardSettingsChanges).toEqual([])
+ expect(router.values.searchParams).toEqual({})
+ })
+
+ const historyCases: [string, Record<string, string>, string][] = [
+ [
+ 'restores the override the URL carries',
+ { [dashboardUtils.SEARCH_PARAM_QUERY_VARIABLES_KEY]: JSON.stringify({ organization: 'url-val' }) },
+ 'url-val',
+ ],
+ ['restores the saved value when the URL drops the override', {}, 'persisted'],
+ ]
+
+ it.each(historyCases)('browser history moves SQL variables: %s', async (_name, searchParams, expectedValue) => {
+ await mountDashboardWithVariable({
+ urlValue: 'url-val',
+ dashboardOverride: { value: 'persisted', isNull: false },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.overrideVariableValue(variableId, 'edited', false)
+ }).toFinishAllListeners()
+
+ await popToSearchParams(searchParams)
+
+ expect(logic.values.currentDashboardSettings.variables[variableId]).toEqual(
+ expect.objectContaining({ value: expectedValue })
+ )
+ })
+
+ it('keeps the chosen default in the URL when the dashboard saved another value', async () => {
+ await mountDashboardWithVariable({ dashboardOverride: { value: 'persisted', isNull: false } })
+
+ await expectLogic(logic, () => {
+ logic.actions.overrideVariableValue(variableId, 'Default org', false)
+ }).toFinishAllListeners()
+
+ expect(dashboardUtils.parseURLVariables(router.values.searchParams)).toEqual({
+ organization: 'Default org',
+ })
+ expect(logic.values.dashboardSettingsState).toBe('unsavedChanges')
+ })
+
+ it('discards filter and SQL variable changes and restores the saved settings', async () => {
+ await mountDashboardWithVariable({ urlValue: 'url-val' })
+ router.actions.push('/', {
+ [dashboardUtils.SEARCH_PARAM_FILTERS_KEY]: JSON.stringify({ date_from: '-7d' }),
+ [dashboardUtils.SEARCH_PARAM_QUERY_VARIABLES_KEY]: JSON.stringify({ organization: 'url-val' }),
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-30d', null)
+ logic.actions.overrideVariableValue(variableId, 'edited', false)
+ logic.actions.discardDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(router.values.searchParams).toEqual({})
+ expect(logic.values.currentDashboardSettings).toEqual({ filters: {}, variables: {} })
+ })
+
+ it('saves filter and SQL variable edits in one dashboard update', async () => {
await mountDashboardWithVariable({
urlValue: 'url-override',
dashboardOverride: { value: 'persisted', isNull: false },
})
+ const updatedDashboard = {
+ ...logic.values.dashboard!,
+ persisted_filters: { date_from: '-7d', date_to: null },
+ persisted_variables: {
+ [variableId]: { ...baseVariable, value: 'edited', isNull: false },
+ },
+ }
+ const update = jest.spyOn(api, 'update').mockResolvedValue(updatedDashboard)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ logic.actions.overrideVariableValue(variableId, 'edited', false)
+ logic.actions.saveDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(update).toHaveBeenCalledWith(expect.any(String), {
+ filters: { date_from: '-7d', date_to: null },
+ variables: {
+ [variableId]: expect.objectContaining({ value: 'edited' }),
+ },
+ })
+ expect(router.values.searchParams).toEqual({})
+ expect(logic.values.dashboardSettingsState).toBe('saved')
+ })
+
+ it('keeps edits made while dashboard changes save', async () => {
+ await mountDashboardWithVariable({})
+ let finishSave: (dashboard: DashboardType<QueryBasedInsightModel>) => void = () => {
+ throw new Error('Save resolver is unavailable')
+ }
+ const save = new Promise<DashboardType<QueryBasedInsightModel>>((resolve) => {
+ finishSave = resolve
+ })
+ jest.spyOn(api, 'update').mockReturnValueOnce(save)
+
+ logic.actions.overrideVariableValue(variableId, 'submitted', false)
+ logic.actions.saveDashboardChanges()
+ await expectLogic(logic).toMatchValues({ dashboardFiltersSaving: true })
+
+ logic.actions.overrideVariableValue(variableId, 'newer edit', false)
+ finishSave({
+ ...logic.values.dashboard!,
+ persisted_variables: {
+ [variableId]: { ...baseVariable, value: 'submitted', isNull: false },
+ },
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.dashboardSettingsState).toBe('unsavedChanges')
+ expect(logic.values.currentDashboardSettings.variables[variableId]).toEqual(
+ expect.objectContaining({ value: 'newer edit' })
+ )
+ })
+
+ it('waits for Preview before refreshing SQL variable changes on a large dashboard', async () => {
+ const payloadSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(0)
+ await mountDashboardWithVariable({})
+ const getInsightWithRetrySpy = jest
+ .spyOn(dashboardUtils, 'getInsightWithRetry')
+ .mockImplementation(async (_teamId, insight) => insight)
+
+ await expectLogic(logic, () => {
+ logic.actions.overrideVariableValue(variableId, 'edited', false)
+ }).toFinishAllListeners()
+
+ expect(logic.values.canAutoPreview).toBe(false)
+ expect(getInsightWithRetrySpy).not.toHaveBeenCalled()
+ expect(dashboardUtils.parseURLVariables(router.values.searchParams)).toEqual({ organization: 'edited' })
await expectLogic(logic, () => {
- logic.actions.saveEditModeChanges()
+ logic.actions.previewDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(getInsightWithRetrySpy).toHaveBeenCalledTimes(1)
+ getInsightWithRetrySpy.mockRestore()
+ payloadSpy.mockRestore()
+ })
+
+ it('uses visible SQL variable values when refreshing one tile before Preview', async () => {
+ const payloadSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(0)
+ await mountDashboardWithVariable({})
+ const getInsightWithRetrySpy = jest
+ .spyOn(dashboardUtils, 'getInsightWithRetry')
+ .mockImplementation(async (_teamId, insight) => insight)
+
+ try {
+ await expectLogic(logic, () => {
+ logic.actions.overrideVariableValue(variableId, 'draft value', false)
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.refreshDashboardItem({ tile: logic.values.insightTiles[0] })
+ }).toFinishAllListeners()
+
+ expect(getInsightWithRetrySpy).toHaveBeenCalledTimes(1)
+ expect(getInsightWithRetrySpy.mock.calls[0][7]).toEqual({})
+ } finally {
+ getInsightWithRetrySpy.mockRestore()
+ payloadSpy.mockRestore()
+ }
+ })
+
+ it('makes Preview available when a SQL variable changes during an older preview', async () => {
+ const payloadSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(0)
+ await mountDashboardWithVariable({})
+ let finishPreview: (insight: QueryBasedInsightModel) => void = () => {
+ throw new Error('Preview resolver is unavailable')
+ }
+ const preview = new Promise<QueryBasedInsightModel>((resolve) => {
+ finishPreview = resolve
})
- .toDispatchActions(['saveEditModeChanges', 'saveEditModeChangesSuccess', 'refreshDashboardItems'])
- .toFinishAllListeners()
+ const getInsightWithRetrySpy = jest.spyOn(dashboardUtils, 'getInsightWithRetry').mockReturnValue(preview)
+
+ logic.actions.previewDashboardChanges()
+ await expectLogic(logic).toMatchValues({ loadingPreview: true })
+
+ logic.actions.overrideVariableValue(variableId, 'newer value', false)
+ await expectLogic(logic).toMatchValues({ loadingPreview: false })
+
+ finishPreview(logic.values.tiles[0].insight!)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.previewedDashboardSettings?.variables).toEqual({})
+ expect(logic.values.currentDashboardSettings.variables[variableId]).toEqual(
+ expect.objectContaining({ value: 'newer value' })
+ )
+ getInsightWithRetrySpy.mockRestore()
+ payloadSpy.mockRestore()
})
it('applying a variable value refreshes every tile with the new value attached to the request', async () => {
@@ -2603,6 +3386,7 @@ describe('dashboardLogic', () => {
.toDispatchActions(['overrideVariableValue', 'refreshDashboardItems'])
.toFinishAllListeners()
+ expect(logic.values.effectiveVariablesAndAssociatedInsights[0].variable.value).toBe('applied-value')
expect(getInsightWithRetrySpy).toHaveBeenCalledTimes(1)
const variablesOverride = getInsightWithRetrySpy.mock.calls[0][7]
expect(variablesOverride).toEqual({
@@ -3024,15 +3808,20 @@ describe('dashboardLogic', () => {
await expectLogic(logic, () => {
logic.actions.setLayoutZoom(0.75)
}).toMatchValues({ layoutZoom: 0.75 })
- })
- it('resets layoutZoom to 1 when leaving edit mode', async () => {
await expectLogic(logic, () => {
- logic.actions.setLayoutZoom(0.5)
- }).toMatchValues({ layoutZoom: 0.5 })
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardFilters
+ )
+ }).toMatchValues({ layoutZoom: 0.75 })
await expectLogic(logic, () => {
- logic.actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderSaveDashboard)
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ logic.actions.cancelLayoutEdit()
}).toMatchValues({ layoutZoom: 1 })
})
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index e067a8e28f35..1ce8e26e0402 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -108,6 +108,14 @@ import {
} from '~/types'
import { DashboardGridCompaction } from 'products/dashboards/frontend/dashboardCustomization'
+import {
+ dashboardFiltersEqual,
+ dashboardVariableValuesEqual,
+ getDashboardFilterChanges,
+ getDashboardVariableChanges,
+ type DashboardSettingsChange,
+ type DashboardFilterChange,
+} from 'products/dashboards/frontend/dashboardSettings/dashboardChanges'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { Node } from '../../queries/schema/schema-general'
@@ -133,14 +141,11 @@ import {
SEARCH_PARAM_FILTERS_KEY,
SEARCH_PARAM_QUERY_VARIABLES_KEY,
combineDashboardFilters,
- dashboardFilterOverrideChangesFilters,
- encodeURLFilters,
encodeURLVariables,
getDashboardWidgetType,
getEffectiveDateOverride,
getInsightQueryError,
getInsightWithRetry,
- isLayoutEditEventSource,
isRefreshRejectionStub,
layoutsByTile,
parseURLFilters,
@@ -148,7 +153,6 @@ import {
runWithLimit,
searchParamsWithUrlFilters,
shouldSharedDashboardAutoForceForStaleTime,
- shouldSnapshotUrlAtEditModeEntry,
} from './dashboardUtils'
import { TileFiltersOverride } from './TileFiltersOverride'
import { tileLogic } from './tileLogic'
@@ -194,6 +198,26 @@ export enum RefreshDashboardItemsAction {
// to stop kea typegen getting confused
export type DashboardTileLayoutUpdatePayload = Pick<DashboardTile, 'id' | 'layouts'>
+export interface PendingInsertion {
+ x: number
+ y: number
+ w: number | null
+}
+
+export interface DashboardSettings {
+ filters: DashboardFilter
+ variables: Record<string, HogQLVariable>
+}
+
+export type DashboardSettingsState = 'unsavedChanges' | 'saved'
+
+export interface DashboardEditing {
+ filters: boolean
+ layout: boolean
+}
+
+type DashboardEditSaveScope = 'colors' | 'layout'
+
function parseDashboardTileId(tileId: string | undefined): DashboardTileIdOrNew {
const parsedTileId = Number(tileId)
return Number.isNaN(parsedTileId) ? null : parsedTileId
@@ -271,12 +295,17 @@ export interface dashboardLogicValues {
canRestrictDashboard: boolean
canSaveProjectDashboardTemplate: boolean
cancellingPreview: boolean
+ changedFilterCount: number
columns: number | null
containerWidth: number | null
+ currentDashboardSettings: DashboardSettings
+ currentDashboardVariables: Record<string, HogQLVariable>
currentLayoutSize: 'sm' | 'xs'
dashboard: DashboardType<QueryBasedInsightModel> | null
dashboardCustomizeMenuOpen: boolean
+ dashboardEditing: DashboardEditing | null
dashboardFailedToLoad: boolean
+ dashboardFiltersSaving: boolean
dashboardLayouts: Record<DashboardTile['id'], DashboardTile['layouts']>
dashboardLoadData: {
action: DashboardLoadAction | undefined
@@ -286,15 +315,15 @@ export interface dashboardLogicValues {
}
dashboardLoading: boolean
dashboardMode: DashboardMode | null
+ dashboardSettingsChanges: DashboardSettingsChange[]
+ dashboardSettingsDraft: DashboardSettings | null
+ dashboardSettingsState: DashboardSettingsState
dashboardStreaming: boolean
dashboardTileSpacingSaving: boolean
dashboardWidgetsEnabled: boolean
dataColorTheme: DataColorTheme | null
dataColorThemeId: number | null
effectiveBreakdownColors: BreakdownColorConfig[]
- effectiveDashboardVariableOverrides: {
- [x: string]: HogQLVariable
- }
effectiveEditBarFilters: DashboardFilter
effectiveLastRefresh: Dayjs | null
effectiveRefreshFilters: DashboardFilter
@@ -304,17 +333,18 @@ export interface dashboardLogicValues {
}[]
error404: boolean
externalFilters: DashboardFilter
+ filterChanges: DashboardFilterChange[]
+ filterEditModeActive: boolean
+ filtersDirty: boolean
filtersOverrideForLoad: DashboardFilter
- hasIntermittentFilters: boolean
hasInvalidDashboardId: boolean
hasUnsavedColorChanges: boolean
hasUnsavedLayoutChanges: boolean
- hasUrlFilters: boolean
hasVariables: boolean
highlightedInsightId: any
+ initialDashboardSettingsOverride: DashboardSettings
initialVariablesLoaded: boolean
insightTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[]
- intermittentFilters: DashboardFilter
isPinned: boolean
isRefreshing: (id: string) => boolean
isRefreshingQueued: (id: string) => boolean
@@ -333,7 +363,10 @@ export interface dashboardLogicValues {
nextAllowedDashboardRefresh: Dayjs | null
oldestRefreshed: Dayjs | null
pageVisibility: boolean
+ pendingInsertion: PendingInsertion | null
+ persistableDashboardFilters: DashboardFilter
placement: DashboardPlacement
+ previewedDashboardSettings: DashboardSettings | null
projectTreeRef: ProjectTreeRef
refreshMetrics: {
completed: number
@@ -341,7 +374,9 @@ export interface dashboardLogicValues {
}
refreshStatus: Record<string, RefreshStatus>
refreshTilesTotal: number | null
+ savedDashboardSettings: DashboardSettings
scrollToBottomSignal: number
+ settingsForRefresh: DashboardSettings
shouldReportOnAPILoad: boolean
shouldUseStreaming: boolean
showApplyFiltersBanner: boolean
@@ -368,6 +403,7 @@ export interface dashboardLogicValues {
variables?: unknown
} | null
urlVariables: Record<string, HogQLVariable>
+ variablesDirty: boolean
widgetRefreshStatus: Record<
number,
{
@@ -408,9 +444,6 @@ export interface dashboardLogicActions {
widgetType: string
}[]
}
- applyFilters: () => {
- value: true
- }
applyWidgetIssueMetadataChange: (payload: {
context: WidgetIssueMetadataContext
delta: WidgetIssueMetadataDelta
@@ -425,7 +458,7 @@ export interface dashboardLogicActions {
cancelDashboardRefresh: () => {
value: true
}
- cancelEditMode: () => {
+ cancelLayoutEdit: () => {
value: true
}
changeDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => {
@@ -434,6 +467,12 @@ export interface dashboardLogicActions {
clearAddWidgetSelectedTypes: () => {
value: true
}
+ clearDashboardSettingsUrlOverrides: () => {
+ value: true
+ }
+ clearInitialDashboardSettingsOverride: () => {
+ value: true
+ }
copyToDashboard: (
tile: DashboardTile<QueryBasedInsightModel>,
fromDashboard: number,
@@ -472,6 +511,12 @@ export interface dashboardLogicActions {
dashboardNotFound: () => {
value: true
}
+ discardDashboardChanges: () => {
+ value: true
+ }
+ discardLayoutChanges: () => {
+ value: true
+ }
duplicateTile: (tile: DashboardTile<QueryBasedInsightModel>) => {
tile: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>
}
@@ -607,6 +652,12 @@ export interface dashboardLogicActions {
value: any
variableId: string
}
+ previewDashboardChanges: () => {
+ value: true
+ }
+ previewDashboardChangesFailure: () => {
+ value: true
+ }
receiveTileFromStream: (data: { order: number; tile: any }) => {
order: number
tile: any
@@ -617,9 +668,11 @@ export interface dashboardLogicActions {
refreshDashboardItems: (payload: {
action: DashboardLoadAction | RefreshDashboardItemsAction
forceRefresh?: boolean
+ previewUnsavedFilters?: boolean
}) => {
action: DashboardLoadAction | RefreshDashboardItemsAction
forceRefresh?: boolean | undefined
+ previewUnsavedFilters?: boolean | undefined
}
refreshDashboardWidgets: (payload: { forceRefresh?: boolean; tileIds: number[] }) => {
forceRefresh?: boolean | undefined
@@ -655,7 +708,6 @@ export interface dashboardLogicActions {
requestScrollToBottom: () => {
value: true
}
- resetIntermittentFilters: () => boolean
resetInterval: () => {
value: true
}
@@ -674,16 +726,21 @@ export interface dashboardLogicActions {
themeId: number | null
} | null
}
- restoreUrlStateAtEditModeEntry: (
- snapshot: {
- filters?: unknown
- variables?: unknown
- } | null
+ saveDashboardChanges: () => {
+ value: true
+ }
+ saveDashboardChangesFailure: (error: string) => {
+ error: string
+ }
+ saveDashboardChangesSuccess: (
+ dashboard: DashboardType<QueryBasedInsightModel> | null,
+ settings: DashboardSettings | null
) => {
- snapshot: {
- filters?: unknown
- variables?: unknown
- } | null
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
+ settings: DashboardSettings | null
+ }
+ saveDashboardColorChanges: () => {
+ value: true
}
saveDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => {
layoutCompaction: DashboardGridCompaction
@@ -691,7 +748,9 @@ export interface dashboardLogicActions {
saveDashboardTileSpacing: (tileSpacing: DashboardTileSpacing) => {
tileSpacing: DashboardTileSpacing
}
- saveEditModeChanges: () => boolean
+ saveEditModeChanges: (scope: DashboardEditSaveScope) => {
+ scope: DashboardEditSaveScope
+ }
saveEditModeChangesFailure: (
error: string,
errorObject?: any
@@ -701,10 +760,20 @@ export interface dashboardLogicActions {
}
saveEditModeChangesSuccess: (
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
- payload?: boolean
+ payload?: {
+ scope: DashboardEditSaveScope
+ }
) => {
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
- payload?: boolean
+ payload?: {
+ scope: DashboardEditSaveScope
+ }
+ }
+ saveLayout: () => {
+ value: true
+ }
+ saveLayoutChanges: () => {
+ value: true
}
scheduleRefreshDashboardWidgets: (tileId: number) => {
tileId: number
@@ -734,36 +803,46 @@ export interface dashboardLogicActions {
setDashboardCustomizeMenuOpen: (open: boolean) => {
open: boolean
}
- setDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => {
- layoutCompaction: DashboardGridCompaction
- }
- setDashboardMode: (
- mode: DashboardMode | null,
+ setDashboardEditing: (
+ editing: DashboardEditing | null,
source: DashboardEventSource
) => {
- mode: DashboardMode | null
+ editing: DashboardEditing | null
source: DashboardEventSource
}
- setDashboardModeFailure: (
+ setDashboardEditingFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
- setDashboardModeSuccess: (
+ setDashboardEditingSuccess: (
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
payload?: {
- mode: DashboardMode | null
+ editing: DashboardEditing | null
source: DashboardEventSource
}
) => {
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
payload?: {
- mode: DashboardMode | null
+ editing: DashboardEditing | null
source: DashboardEventSource
}
}
+ setDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => {
+ layoutCompaction: DashboardGridCompaction
+ }
+ setDashboardMode: (
+ mode: DashboardMode | null,
+ source: DashboardEventSource
+ ) => {
+ mode: DashboardMode | null
+ source: DashboardEventSource
+ }
+ setDashboardSettingsDraft: (settings: DashboardSettings | null) => {
+ settings: DashboardSettings | null
+ }
setDashboardStreamFailed: () => {
value: true
}
@@ -777,12 +856,12 @@ export interface dashboardLogicActions {
dataColorThemeId: number | null
}
setDates: (
- date_from: string | null,
- date_to: string | null | undefined,
+ dateFrom: string | null,
+ dateTo: string | null | undefined,
explicitDate?: boolean
) => {
- date_from: string | null
- date_to: string | null | undefined
+ dateFrom: string | null
+ dateTo: string | null | undefined
explicitDate: boolean | undefined
}
setExternalFilters: (filters: DashboardFilter) => {
@@ -791,6 +870,9 @@ export interface dashboardLogicActions {
setFilterTestAccounts: (filterTestAccounts: boolean | null) => {
filterTestAccounts: boolean | null
}
+ setInitialDashboardSettingsOverride: (settings: DashboardSettings) => {
+ settings: DashboardSettings
+ }
setInitialLoadResponseBytes: (responseBytes: number) => {
responseBytes: number
}
@@ -809,6 +891,9 @@ export interface dashboardLogicActions {
setPageVisibility: (visible: boolean) => {
visible: boolean
}
+ setPreviewedDashboardSettings: (settings: DashboardSettings | null) => {
+ settings: DashboardSettings | null
+ }
setProperties: (properties: AnyPropertyFilter[] | null) => {
properties: AnyPropertyFilter[] | null
}
@@ -866,12 +951,6 @@ export interface dashboardLogicActions {
properties: Partial<Pick<DashboardTile<InsightModel>, 'color' | 'show_description'>>
tileId: number
}
- setUrlSearchParamsAtEditModeEntry: (snapshot: { filters?: unknown; variables?: unknown }) => {
- snapshot: {
- filters?: unknown
- variables?: unknown
- }
- }
setWidgetRefreshStatuses: (
tileIds: number[],
loading: boolean,
@@ -1006,23 +1085,59 @@ export interface dashboardLogicMeta {
) => void | Promise<void>
}
__keaTypeGenInternalSelectorTypes: {
+ filterEditModeActive: (dashboardEditing: DashboardEditing | null) => boolean
+ layoutEditMode: (dashboardEditing: DashboardEditing | null) => boolean
shouldUseStreaming: (featureFlags: FeatureFlagsSet) => boolean
canAutoPreview: (insightTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[]) => boolean
- hasIntermittentFilters: (intermittentFilters: DashboardFilter) => boolean
- hasUrlFilters: (
- dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
- externalFilters: DashboardFilter,
- urlFilters: DashboardFilter
- ) => boolean
- showApplyFiltersBanner: (canAutoPreview: boolean, hasIntermittentFilters: boolean) => boolean
+ savedDashboardSettings: (
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null
+ ) => DashboardSettings
+ currentDashboardSettings: (
+ savedDashboardSettings: DashboardSettings,
+ initialDashboardSettingsOverride: DashboardSettings,
+ dashboardSettingsDraft: DashboardSettings | null
+ ) => DashboardSettings
+ settingsForRefresh: (
+ savedDashboardSettings: DashboardSettings,
+ initialDashboardSettingsOverride: DashboardSettings,
+ previewedDashboardSettings: DashboardSettings | null
+ ) => DashboardSettings
+ dashboardSettingsState: (
+ savedDashboardSettings: DashboardSettings,
+ currentDashboardSettings: DashboardSettings,
+ variables: Variable[]
+ ) => DashboardSettingsState
+ showApplyFiltersBanner: (canAutoPreview: boolean, dashboardSettingsState: DashboardSettingsState) => boolean
urlFilters: (searchParams: Record<string, any>) => DashboardFilter
- filtersOverrideForLoad: (externalFilters: DashboardFilter, urlFilters: DashboardFilter) => DashboardFilter
+ filtersOverrideForLoad: (
+ externalFilters: DashboardFilter,
+ currentDashboardSettings: DashboardSettings
+ ) => DashboardFilter
effectiveEditBarFilters: (
- dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
externalFilters: DashboardFilter,
- urlFilters: DashboardFilter,
- intermittentFilters: DashboardFilter
+ currentDashboardSettings: DashboardSettings
) => DashboardFilter
+ persistableDashboardFilters: (currentDashboardSettings: DashboardSettings) => DashboardFilter
+ filtersDirty: (
+ dashboardSettingsState: DashboardSettingsState,
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
+ persistableDashboardFilters: DashboardFilter
+ ) => boolean
+ variablesDirty: (
+ dashboardSettingsState: DashboardSettingsState,
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
+ currentDashboardVariables: Record<string, HogQLVariable>
+ ) => boolean
+ filterChanges: (
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
+ persistableDashboardFilters: DashboardFilter
+ ) => DashboardFilterChange[]
+ changedFilterCount: (filterChanges: DashboardSettingsChange[]) => number
+ dashboardSettingsChanges: (
+ savedDashboardSettings: DashboardSettings,
+ currentDashboardSettings: DashboardSettings,
+ variables: Variable[]
+ ) => DashboardSettingsChange[]
anyInsightExceedsRetention: (
insightTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[],
effectiveEditBarFilters: DashboardFilter,
@@ -1034,16 +1149,10 @@ export interface dashboardLogicMeta {
placement: DashboardPlacement
) => boolean
effectiveRefreshFilters: (
- dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
externalFilters: DashboardFilter,
- urlFilters: DashboardFilter
+ settingsForRefresh: DashboardSettings
) => DashboardFilter
- effectiveDashboardVariableOverrides: (
- dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
- urlVariables: Record<string, HogQLVariable>
- ) => {
- [x: string]: HogQLVariable
- }
+ currentDashboardVariables: (currentDashboardSettings: DashboardSettings) => Record<string, HogQLVariable>
hasUnsavedLayoutChanges: (
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
dashboardLayouts: Record<
@@ -1054,7 +1163,7 @@ export interface dashboardLogicMeta {
effectiveVariablesAndAssociatedInsights: (
dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
variables: Variable[],
- urlVariables: Record<string, HogQLVariable>
+ currentDashboardVariables: Record<string, HogQLVariable>
) => {
insightNames: string[]
variable: Variable
@@ -1200,6 +1309,17 @@ export type dashboardLogicType = MakeLogicType<
dashboardLogicMeta
>
+// Filter edit mode only exists to hold the unsaved-settings controls, so it ends once nothing is
+// unsaved. Layout editing carries its own Save and Cancel, so it keeps the dashboard in edit mode.
+function exitFilterEditModeWhenSaved(
+ values: dashboardLogicType['values'],
+ actions: dashboardLogicType['actions']
+): void {
+ if (values.dashboardSettingsState === 'saved' && values.dashboardEditing?.filters && !values.layoutEditMode) {
+ actions.setDashboardEditing(null, DashboardEventSource.DashboardFilters)
+ }
+}
+
export const dashboardLogic = kea<dashboardLogicType>([
path(['scenes', 'dashboard', 'dashboardLogic']),
connect(() => ({
@@ -1262,6 +1382,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
refreshDashboardItems: (payload: {
action: RefreshDashboardItemsAction | DashboardLoadAction
forceRefresh?: boolean
+ previewUnsavedFilters?: boolean
}) => payload,
refreshDashboardWidgets: (payload: { tileIds: number[]; forceRefresh?: boolean }) => payload,
/** Debounced run_widgets refresh for a single tile (tile filters). */
@@ -1313,9 +1434,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
/*
* Dashboard filters & variables.
*/
- setDates: (date_from: string | null, date_to: string | null | undefined, explicitDate?: boolean) => ({
- date_from,
- date_to,
+ setDates: (dateFrom: string | null, dateTo: string | null | undefined, explicitDate?: boolean) => ({
+ dateFrom,
+ dateTo,
explicitDate,
}),
setProperties: (properties: AnyPropertyFilter[] | null) => ({ properties }),
@@ -1323,14 +1444,26 @@ export const dashboardLogic = kea<dashboardLogicType>([
setInterval: (interval: IntervalType | null) => ({ interval }),
setFilterTestAccounts: (filterTestAccounts: boolean | null) => ({ filterTestAccounts }),
setExternalFilters: (filters: DashboardFilter) => ({ filters }),
- saveEditModeChanges: () => true,
+ setDashboardSettingsDraft: (settings: DashboardSettings | null) => ({ settings }),
+ setPreviewedDashboardSettings: (settings: DashboardSettings | null) => ({ settings }),
+ setInitialDashboardSettingsOverride: (settings: DashboardSettings) => ({ settings }),
+ clearInitialDashboardSettingsOverride: true,
+ clearDashboardSettingsUrlOverrides: true,
+ previewDashboardChanges: true,
+ previewDashboardChangesFailure: true,
+ saveDashboardChanges: true,
+ saveDashboardChangesSuccess: (
+ dashboard: DashboardType<QueryBasedInsightModel> | null,
+ settings: DashboardSettings | null
+ ) => ({ dashboard, settings }),
+ saveDashboardChangesFailure: (error: string) => ({ error }),
+ discardDashboardChanges: true,
+ saveDashboardColorChanges: true,
+ saveLayoutChanges: true,
+ discardLayoutChanges: true,
+ saveEditModeChanges: (scope: DashboardEditSaveScope) => ({ scope }),
+ saveLayout: true,
resetUrlFilters: () => true,
- resetIntermittentFilters: () => true,
- restoreUrlStateAtEditModeEntry: (snapshot: { filters?: unknown; variables?: unknown } | null) => ({
- snapshot,
- }),
- setUrlSearchParamsAtEditModeEntry: (snapshot: { filters?: unknown; variables?: unknown }) => ({ snapshot }),
- applyFilters: true,
resetUrlVariables: true,
setInitialVariablesLoaded: (initialVariablesLoaded: boolean) => ({ initialVariablesLoaded }),
updateDashboardLastRefresh: (lastDashboardRefresh: Dayjs) => ({ lastDashboardRefresh }),
@@ -1356,8 +1489,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
setSubscriptionMode: (enabled: boolean, id?: number | 'new') => ({ enabled, id }),
/** Set the dashboard mode, see DashboardMode for details. */
setDashboardMode: (mode: DashboardMode | null, source: DashboardEventSource) => ({ mode, source }),
+ setDashboardEditing: (editing: DashboardEditing | null, source: DashboardEventSource) => ({ editing, source }),
/** Exit edit mode, prompting to confirm if there are unsaved changes. */
- cancelEditMode: true,
+ cancelLayoutEdit: true,
/** Make it easier to handle organizing the layout when theres lots of tiles by zooming out */
setLayoutZoom: (layoutZoom: number) => ({ layoutZoom }),
/** Optimistic pin/unpin toggle. */
@@ -1446,7 +1580,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
await breakpoint(200)
try {
- const apiUrl = values.apiUrl('force_cache', values.filtersOverrideForLoad, values.urlVariables)
+ const apiUrl = values.apiUrl(
+ 'force_cache',
+ values.filtersOverrideForLoad,
+ values.currentDashboardVariables
+ )
const dashboardResponse: Response = await api.getResponse(apiUrl)
const dashboard: DashboardType<InsightModel> | null = await getJSONOrNull(dashboardResponse)
@@ -1470,7 +1608,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
loadDashboardStreaming: async ({ action }, breakpoint) => {
actions.loadingDashboardItemsStarted(action)
await breakpoint(200)
- actions.resetIntermittentFilters()
let metadataReceived = false
const disposeStream = await api.dashboards.streamTiles(
@@ -1478,7 +1615,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
{
layoutSize: values.currentLayoutSize,
filtersOverride: values.filtersOverrideForLoad,
- variablesOverride: values.urlVariables,
+ variablesOverride: values.currentDashboardVariables,
},
// onMessage callback - handles both metadata and tiles
(data) => {
@@ -1515,7 +1652,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
// Return null - metadata will update the dashboard
return null
},
- saveEditModeChanges: async (_, breakpoint) => {
+ saveEditModeChanges: async ({ scope }, breakpoint) => {
cache.dashboardChangesPersisted = false
try {
// Only persist sm layouts; xs layouts are derived on the fly
@@ -1529,16 +1666,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
return null
}
- const persistedFilters = currentDashboard.persisted_filters || {}
- const persistedVariables = currentDashboard.persisted_variables || {}
const persistedBreakdownColors = currentDashboard.breakdown_colors || []
const persistedThemeId = currentDashboard.data_color_theme_id ?? null
- const filtersChanged = !equal(persistedFilters, values.effectiveEditBarFilters || {})
- const variablesChanged = !equal(
- persistedVariables,
- values.effectiveDashboardVariableOverrides || {}
- )
// While tiles are still loading, or an errored/aborted tile is missing its
// results, the visible breakdown values are incomplete, so fresh auto
// assignments and stale-entry pruning would both act on partial data.
@@ -1559,35 +1689,39 @@ export const dashboardLogic = kea<dashboardLogicType>([
return !equal(originalLayouts || {}, updatedLayouts || {})
})
- if (
- !filtersChanged &&
- !variablesChanged &&
- !breakdownColorsChanged &&
- !themeChanged &&
- !layoutsChanged
- ) {
- actions.resetUrlFilters()
- actions.resetUrlVariables()
+ const colorsChanged = breakdownColorsChanged || themeChanged
+ const hasChanges = scope === 'colors' ? colorsChanged : layoutsChanged
+ if (!hasChanges) {
return currentDashboard
}
breakpoint()
- // Dashboard filters or variables changed—each tile must reload so charts match the
- // settings you just saved (same flow as Apply filters).
- const shouldRefreshTilesAfterSave = filtersChanged || variablesChanged
-
- const updatedDashboard: DashboardType<InsightModel> = await api.update(
+ const payload =
+ scope === 'colors'
+ ? {
+ breakdown_colors: breakdownColorsToSave,
+ data_color_theme_id: values.dataColorThemeId,
+ }
+ : {
+ tiles: layoutsToUpdate,
+ }
+ const persistedDashboard: DashboardType<InsightModel> = await api.update(
`api/environments/${values.currentTeamId}/dashboards/${props.id}`,
- {
- filters: values.effectiveEditBarFilters,
- variables: values.effectiveDashboardVariableOverrides,
- breakdown_colors: breakdownColorsToSave,
- data_color_theme_id: values.dataColorThemeId,
- tiles: layoutsToUpdate,
- }
+ payload
)
- if (breakdownColorsChanged) {
+ const latestDashboard = values.dashboard ?? currentDashboard
+ const updatedDashboard =
+ scope === 'colors'
+ ? { ...persistedDashboard, tiles: latestDashboard.tiles }
+ : {
+ ...persistedDashboard,
+ breakdown_colors: latestDashboard.breakdown_colors,
+ data_color_theme_id: latestDashboard.data_color_theme_id,
+ }
+ updatedDashboard.persisted_filters = latestDashboard.persisted_filters
+ updatedDashboard.persisted_variables = latestDashboard.persisted_variables
+ if (scope === 'colors' && breakdownColorsChanged) {
eventUsageLogic.actions.reportDashboardBreakdownColorsSaved(
values.dashboard,
breakdownColorsToSave.filter((c) => c.source !== 'auto').length,
@@ -1595,17 +1729,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
Array.from(new Set(breakdownColorsToSave.map((c) => String(c.breakdownType))))
)
}
- if (themeChanged) {
+ if (scope === 'colors' && themeChanged) {
eventUsageLogic.actions.reportDashboardColorThemeSet(
values.dashboard,
values.dataColorThemeId
)
}
- actions.resetUrlFilters()
- actions.resetUrlVariables()
- if (shouldRefreshTilesAfterSave) {
- cache.shouldRefreshTilesAfterSave = true
- }
cache.dashboardChangesPersisted = true
return getQueryBasedDashboard(updatedDashboard, 'dashboard_scene')
} catch (e) {
@@ -1635,9 +1764,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
} as DashboardType<QueryBasedInsightModel>
}
},
- setDashboardMode: async ({ mode, source }) => {
+ setDashboardEditing: async ({ editing, source }) => {
if (
- mode === null &&
+ editing === null &&
source === DashboardEventSource.DashboardHeaderDiscardChanges &&
values.dashboard?.tiles
) {
@@ -1828,6 +1957,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
loadDashboardFailure: () => false,
},
],
+ dashboardFiltersSaving: [
+ false,
+ {
+ saveDashboardChanges: () => true,
+ saveDashboardChangesSuccess: () => false,
+ saveDashboardChangesFailure: () => false,
+ },
+ ],
dashboardStreaming: [
false,
{
@@ -1850,9 +1987,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
setBreakdownFilter: () => false,
setInterval: () => false,
setFilterTestAccounts: () => false,
+ overrideVariableValue: () => false,
loadDashboardSuccess: () => false,
loadDashboardFailure: () => false,
- applyFilters: () => true,
+ previewDashboardChanges: () => true,
+ previewDashboardChangesFailure: () => false,
+ setPreviewedDashboardSettings: (_, { settings }) => settings !== null,
},
],
cancellingPreview: [
@@ -1902,7 +2042,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
{
loadDashboardSuccess: (_, { dashboard }) => tileLayoutsFromDashboard(dashboard),
loadDashboardMetadataSuccess: (_, { dashboard }) => tileLayoutsFromDashboard(dashboard),
- saveEditModeChangesSuccess: (_, { dashboard }) => tileLayoutsFromDashboard(dashboard),
+ saveEditModeChangesSuccess: (state, { dashboard, payload }) =>
+ payload?.scope === 'layout' ? tileLayoutsFromDashboard(dashboard) : state,
receiveTileFromStream: (state, { tile }) => ({
...state,
[tile.id]: tile.layouts,
@@ -1922,7 +2063,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
// Cleared on discard only. After a successful save the edits match what's persisted,
// and a failed save (which also fires saveEditModeChangesSuccess) must keep them.
- setDashboardMode: (state, { source }) =>
+ setDashboardEditing: (state, { source }) =>
source === DashboardEventSource.DashboardHeaderDiscardChanges ? [] : state,
restoreTemporaryColorState: (_, { colors }) => colors,
},
@@ -1932,7 +2073,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
null as { themeId: number | null } | null,
{
setDataColorThemeId: (_, { dataColorThemeId }) => ({ themeId: dataColorThemeId || null }),
- setDashboardMode: (state, { source }) =>
+ setDashboardEditing: (state, { source }) =>
source === DashboardEventSource.DashboardHeaderDiscardChanges ? null : state,
restoreTemporaryColorState: (_, { themeId }) => themeId,
},
@@ -2054,6 +2195,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
[dashboardsModel.actionTypes.updateDashboardSuccess]: (state, { dashboard }) => {
return state && dashboard && state.id === dashboard.id ? dashboard : state
},
+ saveDashboardChangesSuccess: (state, { dashboard }) =>
+ state && dashboard
+ ? {
+ ...state,
+ persisted_filters: dashboard.persisted_filters,
+ persisted_variables: dashboard.persisted_variables,
+ }
+ : state,
[insightsModel.actionTypes.renameInsightSuccess]: (
state,
{ item }
@@ -2206,18 +2355,10 @@ export const dashboardLogic = kea<dashboardLogicType>([
setDashboardMode: (_, { mode }) => mode,
},
],
- layoutEditMode: [
- false,
+ dashboardEditing: [
+ null as DashboardEditing | null,
{
- setDashboardMode: (_, { mode, source }) => {
- if (mode !== DashboardMode.Edit) {
- return false
- }
- if (isLayoutEditEventSource(source)) {
- return true
- }
- return false
- },
+ setDashboardEditing: (_, { editing }) => editing,
},
],
dashboardCustomizeMenuOpen: [
@@ -2241,6 +2382,13 @@ export const dashboardLogic = kea<dashboardLogicType>([
saveEditModeChangesSuccess: () => null,
},
],
+ pendingInsertion: [
+ null as PendingInsertion | null,
+ {
+ setPendingInsertion: (_, { pendingInsertion }) => pendingInsertion,
+ setDashboardEditing: (state, { editing }) => (editing != null ? null : state),
+ },
+ ],
loadLayoutFromServerOnPreview: [
false,
{
@@ -2375,50 +2523,37 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
],
- intermittentFilters: [
+ dashboardSettingsDraft: [
+ null as DashboardSettings | null,
{
- date_from: undefined,
- date_to: undefined,
- properties: undefined,
- breakdown_filter: undefined,
- explicitDate: undefined,
- interval: undefined,
- filterTestAccounts: undefined,
- } as DashboardFilter,
+ setDashboardSettingsDraft: (_, { settings }) => settings,
+ saveDashboardChangesSuccess: (state, { settings }) => {
+ if (!state || !settings || equal(state, settings)) {
+ return null
+ }
+ return state
+ },
+ discardDashboardChanges: () => null,
+ },
+ ],
+ previewedDashboardSettings: [
+ null as DashboardSettings | null,
{
- setDates: (state, { date_from, date_to, explicitDate }) => ({
- ...state,
- date_from,
- date_to,
- explicitDate,
- }),
- setProperties: (state, { properties }) => ({
- ...state,
- properties,
- }),
- setBreakdownFilter: (state, { breakdown_filter }) => ({
- ...state,
- breakdown_filter,
- }),
- setInterval: (state, { interval }) => ({
- ...state,
- interval,
- }),
- setFilterTestAccounts: (state, { filterTestAccounts }) => ({
- ...state,
- filterTestAccounts,
- }),
- resetIntermittentFilters: () => ({
- date_from: undefined,
- date_to: undefined,
- properties: undefined,
- breakdown_filter: undefined,
- explicitDate: undefined,
- interval: undefined,
- filterTestAccounts: undefined,
- }),
+ setPreviewedDashboardSettings: (_, { settings }) => settings,
+ saveDashboardChangesSuccess: () => null,
+ },
+ ],
+ initialDashboardSettingsOverride: [
+ {
+ filters: parseURLFilters(router.values.searchParams),
+ variables: {},
+ } as DashboardSettings,
+ {
+ setInitialDashboardSettingsOverride: (_, { settings }) => settings,
+ clearInitialDashboardSettingsOverride: () => ({ filters: {}, variables: {} }),
},
],
+
isSavingTags: [
false,
{
@@ -2529,6 +2664,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
],
})),
selectors(() => ({
+ filterEditModeActive: [
+ (s) => [s.dashboardEditing],
+ (dashboardEditing: DashboardEditing | null): boolean => dashboardEditing?.filters === true,
+ ],
+ layoutEditMode: [
+ (s) => [s.dashboardEditing],
+ (dashboardEditing: DashboardEditing | null): boolean => dashboardEditing?.layout === true,
+ ],
shouldUseStreaming: [
(s) => [s.featureFlags],
(featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean => {
@@ -2551,54 +2694,138 @@ export const dashboardLogic = kea<dashboardLogicType>([
return insightTiles.length < limit
},
],
- hasIntermittentFilters: [
- (s) => [s.intermittentFilters],
- (intermittentFilters: DashboardFilter) =>
- Object.values(intermittentFilters).some((filter) => filter !== undefined),
+ savedDashboardSettings: [
+ (s) => [s.dashboard],
+ (dashboard: DashboardType<QueryBasedInsightModel> | null): DashboardSettings => ({
+ filters: dashboard?.persisted_filters || {},
+ variables: dashboard?.persisted_variables || {},
+ }),
],
- // An override that constrains nothing still has keys — clearing the last property filter leaves
- // `{"properties":[]}` in the URL. Counting keys reads that as an active override, so the dashboard
- // announces overrides while showing exactly its saved state.
- hasUrlFilters: [
- (s) => [s.dashboard, s.externalFilters, s.urlFilters],
+ currentDashboardSettings: [
+ (s) => [s.savedDashboardSettings, s.initialDashboardSettingsOverride, s.dashboardSettingsDraft],
(
- dashboard: DashboardType<QueryBasedInsightModel> | null,
- externalFilters: DashboardFilter,
- urlFilters: DashboardFilter
- ) =>
- dashboardFilterOverrideChangesFilters(
- urlFilters,
- combineDashboardFilters(dashboard?.persisted_filters || {}, externalFilters)
- ),
+ saved: DashboardSettings,
+ initialOverride: DashboardSettings,
+ draft: DashboardSettings | null
+ ): DashboardSettings =>
+ draft || {
+ filters: combineDashboardFilters(saved.filters, initialOverride.filters),
+ variables: { ...saved.variables, ...initialOverride.variables },
+ },
+ ],
+ settingsForRefresh: [
+ (s) => [s.savedDashboardSettings, s.initialDashboardSettingsOverride, s.previewedDashboardSettings],
+ (
+ saved: DashboardSettings,
+ initialOverride: DashboardSettings,
+ previewed: DashboardSettings | null
+ ): DashboardSettings =>
+ previewed || {
+ filters: combineDashboardFilters(saved.filters, initialOverride.filters),
+ variables: { ...saved.variables, ...initialOverride.variables },
+ },
+ ],
+ dashboardSettingsState: [
+ (s) => [s.savedDashboardSettings, s.currentDashboardSettings, s.variables],
+ (saved: DashboardSettings, current: DashboardSettings, variables: Variable[]): DashboardSettingsState => {
+ const variableDefaults = Object.fromEntries(
+ variables.map((variable) => [
+ variable.id,
+ { value: variable.default_value, isNull: variable.isNull },
+ ])
+ )
+ const variableIds = new Set([...Object.keys(saved.variables), ...Object.keys(current.variables)])
+ const variablesChanged = Array.from(variableIds).some(
+ (variableId) =>
+ !dashboardVariableValuesEqual(
+ saved.variables[variableId] ?? variableDefaults[variableId],
+ current.variables[variableId] ?? variableDefaults[variableId]
+ )
+ )
+
+ if (!dashboardFiltersEqual(saved.filters, current.filters) || variablesChanged) {
+ return 'unsavedChanges'
+ }
+ return 'saved'
+ },
],
showApplyFiltersBanner: [
- (s) => [s.canAutoPreview, s.hasIntermittentFilters],
- (canAutoPreview: boolean, hasIntermittentFilters: boolean) => !canAutoPreview && hasIntermittentFilters,
+ (s) => [s.canAutoPreview, s.dashboardSettingsState],
+ (canAutoPreview: boolean, state: DashboardSettingsState) => !canAutoPreview && state === 'unsavedChanges',
],
urlFilters: [
() => [router.selectors.searchParams],
(searchParams: Record<string, any>) => parseURLFilters(searchParams),
],
filtersOverrideForLoad: [
- (s) => [s.externalFilters, s.urlFilters],
- (externalFilters: DashboardFilter, urlFilters: DashboardFilter) =>
- combineDashboardFilters(externalFilters, urlFilters),
+ (s) => [s.externalFilters, s.currentDashboardSettings],
+ (externalFilters: DashboardFilter, settings: DashboardSettings) =>
+ combineDashboardFilters(externalFilters, settings.filters),
],
effectiveEditBarFilters: [
- (s) => [s.dashboard, s.externalFilters, s.urlFilters, s.intermittentFilters],
+ (s) => [s.externalFilters, s.currentDashboardSettings],
+ (externalFilters: DashboardFilter, settings: DashboardSettings) => {
+ const effectiveEditBarFilters = combineDashboardFilters(settings.filters, externalFilters)
+ return effectiveEditBarFilters
+ },
+ ],
+ persistableDashboardFilters: [
+ (s) => [s.currentDashboardSettings],
+ (settings: DashboardSettings) => settings.filters,
+ ],
+ filtersDirty: [
+ (s) => [s.dashboardSettingsState, s.dashboard, s.persistableDashboardFilters],
+ (
+ state: DashboardSettingsState,
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
+ persistableDashboardFilters: DashboardFilter
+ ): boolean =>
+ state === 'unsavedChanges' && !equal(dashboard?.persisted_filters || {}, persistableDashboardFilters),
+ ],
+ variablesDirty: [
+ (s) => [s.dashboardSettingsState, s.dashboard, s.currentDashboardVariables],
+ (
+ state: DashboardSettingsState,
+ dashboard: DashboardType<QueryBasedInsightModel<Node<Record<string, any>>>> | null,
+ variables: {
+ [x: string]: HogQLVariable
+ }
+ ): boolean => state === 'unsavedChanges' && !equal(dashboard?.persisted_variables || {}, variables),
+ ],
+ filterChanges: [
+ (s) => [s.dashboard, s.persistableDashboardFilters],
(
dashboard: DashboardType<QueryBasedInsightModel> | null,
- externalFilters: DashboardFilter,
- urlFilters: DashboardFilter,
- intermittentFilters: DashboardFilter
- ) => {
- const effectiveEditBarFilters = combineDashboardFilters(
- dashboard?.persisted_filters || {},
- externalFilters,
- urlFilters,
- intermittentFilters
+ persistableDashboardFilters: DashboardFilter
+ ): DashboardFilterChange[] =>
+ getDashboardFilterChanges(dashboard?.persisted_filters || {}, persistableDashboardFilters),
+ ],
+ changedFilterCount: [
+ (s) => [s.filterChanges],
+ (filterChanges: DashboardFilterChange[]): number => filterChanges.length,
+ ],
+ dashboardSettingsChanges: [
+ (s) => [s.savedDashboardSettings, s.currentDashboardSettings, s.variables],
+ (
+ saved: DashboardSettings,
+ current: DashboardSettings,
+ variables: Variable[]
+ ): DashboardSettingsChange[] => {
+ const defaults = Object.fromEntries(
+ variables.map((variable) => [
+ variable.id,
+ {
+ code_name: variable.code_name,
+ variableId: variable.id,
+ value: variable.default_value,
+ isNull: variable.isNull,
+ },
+ ])
)
- return effectiveEditBarFilters
+ return [
+ ...getDashboardFilterChanges(saved.filters, current.filters),
+ ...getDashboardVariableChanges(saved.variables, current.variables, defaults),
+ ]
},
],
// Does any tile on this dashboard reach past the team's events retention window? Runs the same date
@@ -2633,21 +2860,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
placement !== DashboardPlacement.Export,
],
effectiveRefreshFilters: [
- (s) => [s.dashboard, s.externalFilters, s.urlFilters],
- (
- dashboard: DashboardType<QueryBasedInsightModel> | null,
- externalFilters: DashboardFilter,
- urlFilters: DashboardFilter
- ): DashboardFilter => {
- return combineDashboardFilters(dashboard?.persisted_filters || {}, externalFilters, urlFilters)
+ (s) => [s.externalFilters, s.settingsForRefresh],
+ (externalFilters: DashboardFilter, settings: DashboardSettings): DashboardFilter => {
+ return combineDashboardFilters(settings.filters, externalFilters)
},
],
- effectiveDashboardVariableOverrides: [
- (s) => [s.dashboard, s.urlVariables],
- (dashboard: DashboardType<QueryBasedInsightModel> | null, urlVariables: Record<string, HogQLVariable>) => ({
- ...dashboard?.persisted_variables,
- ...urlVariables,
- }),
+ currentDashboardVariables: [
+ (s) => [s.currentDashboardSettings],
+ (settings: DashboardSettings) => settings.variables,
],
hasUnsavedLayoutChanges: [
(s) => [s.dashboard, s.dashboardLayouts],
@@ -2666,11 +2886,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
],
effectiveVariablesAndAssociatedInsights: [
- (s) => [s.dashboard, s.variables, s.urlVariables],
+ (s) => [s.dashboard, s.variables, s.currentDashboardVariables],
(
dashboard: DashboardType,
variables: Variable[],
- urlVariables: Record<string, HogQLVariable>
+ dashboardVariables: Record<string, HogQLVariable>
): { variable: Variable; insightNames: string[] }[] => {
const dataVizNodes = (dashboard?.tiles ?? [])
.map((n) => ({ query: n.insight?.query, title: n.insight?.name }))
@@ -2691,14 +2911,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
const effectiveVariables = uniqueVariables
.map((v) => {
const variable = variables.find((n) => n.id === v.variableId)
- const urlVariable = urlVariables[v.variableId]
-
if (!variable) {
return null
}
- const dashboardVariable = dashboard.persisted_variables?.[v.variableId]
- const variableSources = [urlVariable, dashboardVariable, v]
+ const dashboardVariable = dashboardVariables[v.variableId]
+ const variableSources = [dashboardVariable, v]
const valueSource = variableSources.find((source) =>
source ? Object.prototype.hasOwnProperty.call(source, 'value') : false
)
@@ -3845,7 +4063,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
}
// Cache values before the long-running await — the logic may unmount
- const { currentTeamId, effectiveRefreshFilters, urlFilters, urlVariables } = values
+ const { currentTeamId, effectiveRefreshFilters, settingsForRefresh, urlFilters } = values
+ const urlVariables = settingsForRefresh.variables
actions.setRefreshStatus(insight.short_id, true, true)
@@ -3892,11 +4111,16 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.setRefreshError(insight.short_id, e)
}
},
- refreshDashboardItems: async ({ action, forceRefresh }, breakpoint) => {
+ refreshDashboardItems: async ({ action, forceRefresh, previewUnsavedFilters }, breakpoint) => {
const dashboardRefreshStartTime = performance.now()
+ const settingsToRefresh = previewUnsavedFilters
+ ? values.currentDashboardSettings
+ : values.settingsForRefresh
const isInitialLoad =
action === DashboardLoadAction.InitialLoad || action === DashboardLoadAction.InitialLoadWithVariables
const isInitialLoadOrUpdate = isInitialLoad || action === DashboardLoadAction.Update
+ const initialUrlOverridesArePreviewed =
+ isInitialLoad && !values.canAutoPreview && values.dashboardSettingsState === 'unsavedChanges'
const dashboardId: number = props.id
const allInsightTiles = values.insightTiles || []
@@ -3936,7 +4160,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
)
await breakpoint()
- actions.resetIntermittentFilters()
actions.abortAnyRunningQuery()
cache.abortController = new AbortController()
@@ -3945,14 +4168,9 @@ export const dashboardLogic = kea<dashboardLogicType>([
// Cache values used during and after the long-running fetch, since the logic
// may be unmounted by the time the awaits complete (kea's no-arg breakpoint()
// only cancels on newer invocations, not on unmount).
- const {
- currentTeamId,
- effectiveRefreshFilters,
- urlFilters,
- urlVariables,
- dashboardLoadData,
- lastDashboardRefresh,
- } = values
+ const { currentTeamId, externalFilters, urlFilters, dashboardLoadData, lastDashboardRefresh } = values
+ const effectiveRefreshFilters = combineDashboardFilters(externalFilters, settingsToRefresh.filters)
+ const urlVariables = settingsToRefresh.variables
const fetchSyncInsightFunctions = sortedTilesToRefresh.map((tile) => async () => {
const insight = tile.insight
@@ -4060,6 +4278,15 @@ export const dashboardLogic = kea<dashboardLogicType>([
refreshDurationMs: Math.floor(performance.now() - dashboardRefreshStartTime),
}
)
+
+ if (
+ (previewUnsavedFilters || initialUrlOverridesArePreviewed) &&
+ (tilesErroredCount > 0 || tilesAbortedCount > 0)
+ ) {
+ actions.previewDashboardChangesFailure()
+ } else if (previewUnsavedFilters || initialUrlOverridesArePreviewed) {
+ actions.setPreviewedDashboardSettings(settingsToRefresh)
+ }
}
if (
@@ -4178,22 +4405,71 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.addWidgetTileFinished()
}
},
- saveEditModeChanges: () => {
- if (
- values.dashboard?.persisted_filters?.date_from !== values.effectiveEditBarFilters.date_from ||
- values.dashboard?.persisted_filters?.date_to !== values.effectiveEditBarFilters.date_to
- ) {
- eventUsageLogic.actions.reportDashboardDateRangeChanged(
- values.dashboard,
- values.effectiveEditBarFilters.date_from,
- values.effectiveEditBarFilters.date_to
- )
+ saveDashboardChanges: async () => {
+ if (!values.dashboard || values.dashboardSettingsState !== 'unsavedChanges') {
+ actions.saveDashboardChangesSuccess(null, null)
+ return
}
- if (
- JSON.stringify(values.dashboard?.persisted_filters?.properties) !==
- JSON.stringify(values.effectiveEditBarFilters.properties)
- ) {
- eventUsageLogic.actions.reportDashboardPropertiesChanged(values.dashboard)
+
+ const settings = values.currentDashboardSettings
+ try {
+ const dashboard = await api.update(`api/environments/${values.currentTeamId}/dashboards/${props.id}`, {
+ filters: settings.filters,
+ variables: settings.variables,
+ })
+ actions.saveDashboardChangesSuccess(getQueryBasedDashboard(dashboard), settings)
+ actions.clearDashboardSettingsUrlOverrides()
+ actions.clearInitialDashboardSettingsOverride()
+ if (!values.previewedDashboardSettings) {
+ actions.refreshDashboardItems({
+ action: RefreshDashboardItemsAction.Preview,
+ forceRefresh: false,
+ })
+ }
+ lemonToast.success('Dashboard changes saved')
+ } catch (error) {
+ actions.saveDashboardChangesFailure(String(error))
+ lemonToast.error('Could not save dashboard changes: ' + String(error))
+ }
+ },
+ discardDashboardChanges: () => {
+ actions.clearDashboardSettingsUrlOverrides()
+ actions.clearInitialDashboardSettingsOverride()
+ actions.setPreviewedDashboardSettings(null)
+ actions.refreshDashboardItems({
+ action: RefreshDashboardItemsAction.Preview,
+ forceRefresh: false,
+ })
+ exitFilterEditModeWhenSaved(values, actions)
+ },
+ saveDashboardChangesSuccess: () => {
+ exitFilterEditModeWhenSaved(values, actions)
+ },
+ setDashboardSettingsDraft: () => {
+ exitFilterEditModeWhenSaved(values, actions)
+ },
+ saveLayoutChanges: () => {
+ actions.saveEditModeChanges('layout')
+ actions.setLayoutZoom(1)
+ if (values.dashboardSettingsState === 'unsavedChanges') {
+ actions.setDashboardEditing({ filters: true, layout: false }, DashboardEventSource.DashboardFilters)
+ } else if (values.dashboardEditing !== null) {
+ actions.setDashboardEditing(null, DashboardEventSource.DashboardFilters)
+ }
+ },
+ saveDashboardColorChanges: () => {
+ actions.saveEditModeChanges('colors')
+ },
+ discardLayoutChanges: () => {
+ actions.cancelLayoutEdit()
+ },
+ saveLayout: () => {
+ actions.saveEditModeChanges('layout')
+ actions.setLayoutZoom(1)
+ if (values.dashboardSettingsState === 'unsavedChanges') {
+ actions.setDashboardEditing({ filters: true, layout: false }, DashboardEventSource.DashboardFilters)
+ } else if (values.dashboardEditing !== null) {
+ actions.setDashboardEditing(null, DashboardEventSource.DashboardFilters)
}
},
saveEditModeChangesSuccess: ({ dashboard }) => {
@@ -4212,11 +4488,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.refreshDashboardItems({
action: RefreshDashboardItemsAction.Preview,
forceRefresh: false,
+ previewUnsavedFilters: true,
})
}
},
openAddInsightModal: () => {
- if (values.dashboardMode === DashboardMode.Edit && values.hasUnsavedLayoutChanges) {
+ if (values.dashboardEditing?.layout && values.hasUnsavedLayoutChanges) {
if (
!window.confirm(
'Discard unsaved layout changes?\nAdding an insight reloads the dashboard and discards them.'
@@ -4224,13 +4501,16 @@ export const dashboardLogic = kea<dashboardLogicType>([
) {
return
}
- actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ actions.setLayoutZoom(1)
+ actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
}
addInsightToDashboardLogic.actions.showAddInsightToDashboardModal()
},
- cancelEditMode: () => {
- const discard = (): void =>
- actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ cancelLayoutEdit: () => {
+ const discard = (): void => {
+ actions.setLayoutZoom(1)
+ actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ }
const promptEnabled = !!values.featureFlags[FEATURE_FLAGS.DASHBOARD_LAYOUT_DISCARD_PROMPT]
if (!promptEnabled || !(values.hasUnsavedLayoutChanges || values.hasUnsavedColorChanges)) {
discard()
@@ -4288,103 +4568,40 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
})
},
- setDashboardMode: async ({ mode, source }) => {
- if (
- mode === DashboardMode.Edit &&
- values.urlSearchParamsAtEditModeEntry === null &&
- shouldSnapshotUrlAtEditModeEntry(source)
- ) {
- const encodedFilters = encodeURLFilters(values.urlFilters)
- actions.setUrlSearchParamsAtEditModeEntry({
- filters: encodedFilters[SEARCH_PARAM_FILTERS_KEY],
- variables: router.values.searchParams[SEARCH_PARAM_QUERY_VARIABLES_KEY],
- })
- }
-
- if (
- mode === DashboardMode.Edit &&
- source !== DashboardEventSource.DashboardHeaderDiscardChanges &&
- isLayoutEditEventSource(source)
- ) {
+ setDashboardEditing: async ({ editing, source }) => {
+ if (editing?.layout && source !== DashboardEventSource.DashboardHeaderDiscardChanges) {
clearDOMTextSelection()
lemonToast.info('Now editing the dashboard – press E or click Save to persist changes')
- } else if (source === DashboardEventSource.DashboardHeaderDiscardChanges) {
- // reset filters to that before previewing
- actions.resetIntermittentFilters()
-
- // Previews route filters/variables through the URL before refreshing, so tile data
- // always matches the current URL state. Restoring the snapshot therefore only
- // requires a reload when it actually changes that state — if no preview ran during
- // this edit session, the data on screen is already correct.
- const snapshot = values.urlSearchParamsAtEditModeEntry
- const urlStateChangedSinceEditModeEntry =
- !equal(values.urlFilters, parseURLFilters({ [SEARCH_PARAM_FILTERS_KEY]: snapshot?.filters })) ||
- !equal(
- parseURLVariables(router.values.searchParams),
- parseURLVariables({ [SEARCH_PARAM_QUERY_VARIABLES_KEY]: snapshot?.variables })
- )
- actions.restoreUrlStateAtEditModeEntry(snapshot)
-
- if (urlStateChangedSinceEditModeEntry) {
- // reset tile data by reloading dashboard
- actions.refreshDashboardItems({
- action: RefreshDashboardItemsAction.Preview,
- forceRefresh: false,
- })
- }
-
- // also reset layout to that we stored in dashboardLayouts
- // this is done in the reducer for dashboard
- } else if (mode === null && source === DashboardEventSource.DashboardHeaderOverridesBanner) {
- // discard overrides when opening a dashboard from a link with overrides
-
- // remove overrides from url
- actions.resetUrlFilters()
- actions.resetUrlVariables()
-
- // reset tile data by reloading dashboard
- actions.refreshDashboardItems({
- action: RefreshDashboardItemsAction.Refresh,
- forceRefresh: false,
- })
} else if (
- mode === null &&
+ editing === null &&
(source === DashboardEventSource.DashboardHeaderSaveDashboard ||
source === DashboardEventSource.SceneCommonButtons ||
source === DashboardEventSource.DashboardInsightColorsModal)
) {
- // save edit mode changes when exiting via Save button, E key/Edit layout button,
- // or the colors modal's Save button
- // Pending name/description are included in the saveEditModeChanges PATCH
- // to avoid a race between two concurrent PATCHes to the same endpoint.
- actions.saveEditModeChanges()
- }
-
- if (mode || source) {
- const isFilterOnlyEditEntry =
- mode === DashboardMode.Edit && source !== null && !isLayoutEditEventSource(source)
-
- if (mode === DashboardMode.Edit && source !== null && isLayoutEditEventSource(source)) {
- eventUsageLogic.actions.reportDashboardLayoutEditModeEntered(
- values.dashboard,
- source,
- values.layoutEditMode ? values.layoutZoom : null
- )
- }
-
- if (!isFilterOnlyEditEntry) {
- eventUsageLogic.actions.reportDashboardModeToggled(
- values.dashboard,
- mode,
- source,
- values.layoutEditMode ? values.layoutZoom : null,
- values.layoutEditMode
- )
+ if (source === DashboardEventSource.DashboardInsightColorsModal) {
+ actions.saveDashboardColorChanges()
+ } else {
+ actions.saveLayoutChanges()
}
}
- if (mode !== DashboardMode.Edit) {
- actions.setLayoutZoom(1)
+ if (editing?.layout) {
+ eventUsageLogic.actions.reportDashboardLayoutEditModeEntered(
+ values.dashboard,
+ source,
+ values.layoutEditMode ? values.layoutZoom : null
+ )
+ }
+ },
+ setDashboardMode: async ({ mode, source }) => {
+ if (mode || source) {
+ eventUsageLogic.actions.reportDashboardModeToggled(
+ values.dashboard,
+ mode,
+ source,
+ values.layoutEditMode ? values.layoutZoom : null,
+ values.layoutEditMode
+ )
}
},
setAutoRefresh: () => {
@@ -4495,13 +4712,18 @@ export const dashboardLogic = kea<dashboardLogicType>([
insights_fetched_cached: 0,
})
},
- applyFilters: () => {
+ previewDashboardChanges: () => {
actions.refreshDashboardItems({
action: RefreshDashboardItemsAction.Preview,
forceRefresh: false,
+ previewUnsavedFilters: true,
})
},
setProperties: ({ properties }) => {
+ actions.setDashboardSettingsDraft({
+ ...values.currentDashboardSettings,
+ filters: { ...values.currentDashboardSettings.filters, properties },
+ })
eventUsageLogic.actions.reportDashboardFiltersChanged(values.dashboard, 'properties', {
property_count: properties?.length ?? 0,
})
@@ -4510,23 +4732,38 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.refreshDashboardItems({
action: RefreshDashboardItemsAction.Preview,
forceRefresh: false,
+ previewUnsavedFilters: true,
})
}
},
- setDates: ({ date_from, date_to }) => {
+ setDates: ({ dateFrom, dateTo, explicitDate }) => {
+ actions.setDashboardSettingsDraft({
+ ...values.currentDashboardSettings,
+ filters: {
+ ...values.currentDashboardSettings.filters,
+ date_from: dateFrom,
+ date_to: dateTo,
+ explicitDate,
+ },
+ })
eventUsageLogic.actions.reportDashboardFiltersChanged(values.dashboard, 'date', {
- date_from,
- date_to: date_to ?? null,
+ date_from: dateFrom,
+ date_to: dateTo ?? null,
})
if (values.canAutoPreview) {
actions.refreshDashboardItems({
action: RefreshDashboardItemsAction.Preview,
forceRefresh: false,
+ previewUnsavedFilters: true,
})
}
},
setBreakdownFilter: ({ breakdown_filter }) => {
+ actions.setDashboardSettingsDraft({
+ ...values.currentDashboardSettings,
+ filters: { ...values.currentDashboardSettings.filters, breakdown_filter },
+ })
eventUsageLogic.actions.reportDashboardFiltersChanged(values.dashboard, 'breakdown', {
breakdown_type: breakdown_filter?.breakdown_type ?? null,
})
@@ -4535,10 +4772,15 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.refreshDashboardItems({
action: RefreshDashboardItemsAction.Preview,
forceRefresh: false,
+ previewUnsavedFilters: true,
})
}
},
setInterval: ({ interval }) => {
+ actions.setDashboardSettingsDraft({
+ ...values.currentDashboardSettings,
+ filters: { ...values.currentDashboardSettings.filters, interval },
+ })
eventUsageLogic.actions.reportDashboardFiltersChanged(values.dashboard, 'interval', {
interval,
})
@@ -4547,10 +4789,15 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.refreshDashboardItems({
action: RefreshDashboardItemsAction.Preview,
forceRefresh: false,
+ previewUnsavedFilters: true,
})
}
},
setFilterTestAccounts: ({ filterTestAccounts }) => {
+ actions.setDashboardSettingsDraft({
+ ...values.currentDashboardSettings,
+ filters: { ...values.currentDashboardSettings.filters, filterTestAccounts },
+ })
eventUsageLogic.actions.reportDashboardFiltersChanged(values.dashboard, 'test_accounts', {
filter_test_accounts: filterTestAccounts,
})
@@ -4559,6 +4806,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.refreshDashboardItems({
action: RefreshDashboardItemsAction.Preview,
forceRefresh: false,
+ previewUnsavedFilters: true,
})
}
},
@@ -4570,20 +4818,70 @@ export const dashboardLogic = kea<dashboardLogicType>([
})
}
},
- overrideVariableValue: ({ variableId }) => {
+ overrideVariableValue: ({ variableId, value, isNull }) => {
eventUsageLogic.actions.reportDashboardFiltersChanged(values.dashboard, 'variable', {
variable_id: variableId,
})
- actions.refreshDashboardItems({
- action: RefreshDashboardItemsAction.Preview,
- forceRefresh: false,
- })
- if (values.dashboardMode !== DashboardMode.Edit) {
- actions.setDashboardMode(DashboardMode.Edit, DashboardEventSource.DashboardVariableOverride)
+ const variableDefinition = values.variables.find((candidate) => candidate.id === variableId)
+ if (variableDefinition) {
+ const variable = { code_name: variableDefinition.code_name, variableId, value, isNull }
+ const variables = { ...values.currentDashboardSettings.variables }
+ if (
+ dashboardVariableValuesEqual(variable, {
+ value: variableDefinition.default_value,
+ isNull: variableDefinition.isNull,
+ })
+ ) {
+ delete variables[variableId]
+ } else {
+ variables[variableId] = variable
+ }
+ actions.setDashboardSettingsDraft({
+ ...values.currentDashboardSettings,
+ variables,
+ })
+ }
+
+ if (values.canAutoPreview) {
+ actions.refreshDashboardItems({
+ action: RefreshDashboardItemsAction.Preview,
+ forceRefresh: false,
+ previewUnsavedFilters: true,
+ })
+ }
+ if (values.dashboardSettingsState === 'unsavedChanges' && !values.dashboardEditing?.filters) {
+ actions.setDashboardEditing(
+ { filters: true, layout: false },
+ DashboardEventSource.DashboardVariableOverride
+ )
}
},
- [variableDataLogic.actionTypes.loadVariablesSuccess]: () => {
+ [variableDataLogic.actionTypes.loadVariablesSuccess]: ({ variables }) => {
+ const urlVariableValues = parseURLVariables(router.values.searchParams)
+ const initialVariables = Object.fromEntries(
+ variables.flatMap((variable: Variable) => {
+ if (!(variable.code_name in urlVariableValues)) {
+ return []
+ }
+ const value = urlVariableValues[variable.code_name]
+ return [
+ [
+ variable.id,
+ {
+ code_name: variable.code_name,
+ variableId: variable.id,
+ value,
+ isNull: value === null,
+ },
+ ],
+ ]
+ })
+ )
+ actions.setInitialDashboardSettingsOverride({
+ ...values.initialDashboardSettingsOverride,
+ variables: initialVariables,
+ })
// Only run this handler once on startup
// This ensures variables are loaded before the dashboard is loaded and insights are refreshed
if (values.initialVariablesLoaded) {
@@ -4661,7 +4959,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
beforeUnload(({ values, actions }) => ({
enabled: (newLocation?: CombinedLocation) => {
- if (values.dashboardMode !== DashboardMode.Edit || !values.hasUnsavedLayoutChanges) {
+ if (!values.dashboardEditing?.layout || !values.hasUnsavedLayoutChanges) {
return false
}
// Ignore in-page navigations such as opening a side panel
@@ -4672,32 +4970,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
message: 'Leave dashboard?\nChanges you made to the layout will be discarded.',
onConfirm: () => {
- actions.setDashboardMode(null, DashboardEventSource.DashboardHeaderDiscardChanges)
+ actions.setDashboardEditing(null, DashboardEventSource.DashboardHeaderDiscardChanges)
},
})),
actionToUrl(({ values }) => ({
- applyFilters: () => {
- const { currentLocation } = router.values
-
- const urlFilters = parseURLFilters(currentLocation.searchParams)
- const newUrlFilters: DashboardFilter = combineDashboardFilters(urlFilters, values.intermittentFilters)
-
- return [
- currentLocation.pathname,
- searchParamsWithUrlFilters(
- currentLocation.searchParams,
- newUrlFilters,
- combineDashboardFilters(values.dashboard?.persisted_filters || {}, values.externalFilters)
- ),
- currentLocation.hashParams,
- ]
- },
setProperties: ({ properties }) => {
- if (!values.canAutoPreview) {
- return
- }
-
const { currentLocation } = router.values
const urlFilters = parseURLFilters(currentLocation.searchParams)
@@ -4716,19 +4994,15 @@ export const dashboardLogic = kea<dashboardLogicType>([
currentLocation.hashParams,
]
},
- setDates: ({ date_from, date_to, explicit_date }) => {
- if (!values.canAutoPreview) {
- return
- }
-
+ setDates: ({ dateFrom, dateTo, explicitDate }) => {
const { currentLocation } = router.values
const urlFilters = parseURLFilters(currentLocation.searchParams)
const newUrlFilters: DashboardFilter = {
...urlFilters,
- date_from,
- date_to,
- explicitDate: explicit_date ?? values.intermittentFilters.explicitDate,
+ date_from: dateFrom,
+ date_to: dateTo,
+ explicitDate,
}
return [
@@ -4742,10 +5016,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
]
},
setBreakdownFilter: ({ breakdown_filter }) => {
- if (!values.canAutoPreview) {
- return
- }
-
const { currentLocation } = router.values
const urlFilters = parseURLFilters(currentLocation.searchParams)
@@ -4765,10 +5035,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
]
},
setInterval: ({ interval }) => {
- if (!values.canAutoPreview) {
- return
- }
-
const { currentLocation } = router.values
const urlFilters = parseURLFilters(currentLocation.searchParams)
@@ -4788,10 +5054,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
]
},
setFilterTestAccounts: ({ filterTestAccounts }) => {
- if (!values.canAutoPreview) {
- return
- }
-
const { currentLocation } = router.values
const urlFilters = parseURLFilters(currentLocation.searchParams)
@@ -4810,7 +5072,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
currentLocation.hashParams,
]
},
- overrideVariableValue: ({ variableId, value }) => {
+ overrideVariableValue: ({ variableId, value, isNull }) => {
const { currentLocation } = router.values
const currentVariable = values.variables.find((variable: Variable) => variable.id === variableId)
@@ -4819,15 +5081,24 @@ export const dashboardLogic = kea<dashboardLogicType>([
return [currentLocation.pathname, currentLocation.searchParams, currentLocation.hashParams]
}
- const urlVariables = parseURLVariables(currentLocation.searchParams)
- const newUrlVariables: Record<string, string> = {
- ...urlVariables,
- [currentVariable.code_name]: value,
+ const newUrlVariables = { ...parseURLVariables(currentLocation.searchParams) }
+ // An absent URL entry means "use the saved value", so the entry can only be dropped when
+ // the choice matches what the dashboard saved. A dashboard without a saved value shows the
+ // project default, which keeps the URL clean for the common case.
+ const savedValue = values.savedDashboardSettings.variables[variableId] ?? {
+ value: currentVariable.default_value,
+ isNull: currentVariable.isNull,
+ }
+ if (dashboardVariableValuesEqual({ value, isNull }, savedValue)) {
+ delete newUrlVariables[currentVariable.code_name]
+ } else {
+ newUrlVariables[currentVariable.code_name] = value
}
const newSearchParams = {
...currentLocation.searchParams,
}
+ delete newSearchParams[SEARCH_PARAM_QUERY_VARIABLES_KEY]
return [
currentLocation.pathname,
@@ -4847,24 +5118,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
delete newSearchParams[SEARCH_PARAM_FILTERS_KEY]
return [currentLocation.pathname, newSearchParams, currentLocation.hashParams]
},
- restoreUrlStateAtEditModeEntry: ({ snapshot }) => {
- try {
- const { currentLocation } = router.values
- const newSearchParams = { ...currentLocation.searchParams }
- delete newSearchParams[SEARCH_PARAM_FILTERS_KEY]
- delete newSearchParams[SEARCH_PARAM_QUERY_VARIABLES_KEY]
-
- if (snapshot?.filters !== undefined) {
- newSearchParams[SEARCH_PARAM_FILTERS_KEY] = snapshot.filters
- }
- if (snapshot?.variables !== undefined) {
- newSearchParams[SEARCH_PARAM_QUERY_VARIABLES_KEY] = snapshot.variables
- }
-
- return [currentLocation.pathname, newSearchParams, currentLocation.hashParams]
- } catch {
- return undefined
- }
+ clearDashboardSettingsUrlOverrides: () => {
+ const { currentLocation } = router.values
+ const newSearchParams = { ...currentLocation.searchParams }
+ delete newSearchParams[SEARCH_PARAM_FILTERS_KEY]
+ delete newSearchParams[SEARCH_PARAM_QUERY_VARIABLES_KEY]
+ return [currentLocation.pathname, newSearchParams, currentLocation.hashParams]
},
})),
@@ -4879,12 +5138,44 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.setTextTileId(null)
actions.setButtonTileId(null)
actions.setDashboardMode(null, DashboardEventSource.Browser)
+ actions.setDashboardEditing(null, DashboardEventSource.Browser)
},
- '/dashboard/:id': (_params, searchParams) => {
+ '/dashboard/:id': (_params, searchParams, _hashParams, { method }) => {
actions.setSubscriptionMode(false, undefined)
actions.setTextTileId(null)
actions.setButtonTileId(null)
+ if (method === 'POP' && values.dashboard) {
+ const current = values.currentDashboardSettings
+ const settings: DashboardSettings = {
+ filters: combineDashboardFilters(
+ values.savedDashboardSettings.filters,
+ parseURLFilters(searchParams)
+ ),
+ // Browser history carries SQL variables as well as filters. Until the variable
+ // definitions load there is nothing to map the URL values onto, so the current
+ // values stay.
+ variables: values.initialVariablesLoaded
+ ? { ...values.savedDashboardSettings.variables, ...values.urlVariables }
+ : current.variables,
+ }
+
+ // Back and Forward also arrive from routes that leave the settings alone, such as the
+ // sharing page. Rebuilding the settings there would re-query every tile and cancel a
+ // refresh in flight for values the dashboard already holds.
+ if (
+ !dashboardFiltersEqual(current.filters, settings.filters) ||
+ !equal(current.variables, settings.variables)
+ ) {
+ actions.setDashboardSettingsDraft(settings)
+ if (values.canAutoPreview) {
+ actions.refreshDashboardItems({
+ action: RefreshDashboardItemsAction.Preview,
+ forceRefresh: false,
+ })
+ }
+ }
+ }
if (values.dashboardMode === DashboardMode.Sharing) {
actions.setDashboardMode(null, DashboardEventSource.Browser)
}
@@ -4909,6 +5200,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
'/dashboard/:id/tiles/:tileId': ({ tileId }) => {
actions.setSubscriptionMode(false, undefined)
actions.setDashboardMode(null, DashboardEventSource.Browser)
+ actions.setDashboardEditing(null, DashboardEventSource.Browser)
const parsedTileId = parseDashboardTileId(tileId)
actions.setTextTileId(parsedTileId)
actions.setButtonTileId(parsedTileId)
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index ff35190c1bcc..e1e61e65d7fa 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -408,8 +408,8 @@ export async function getInsightWithRetry(
return null
}
-export const parseURLVariables = (searchParams: Record<string, any>): Record<string, Partial<HogQLVariable>> => {
- const variables: Record<string, Partial<HogQLVariable>> = {}
+export const parseURLVariables = (searchParams: Record<string, any>): Record<string, HogQLVariable['value']> => {
+ const variables: Record<string, HogQLVariable['value']> = {}
const raw = searchParams[SEARCH_PARAM_QUERY_VARIABLES_KEY]
if (raw) {
@@ -426,7 +426,7 @@ export const parseURLVariables = (searchParams: Record<string, any>): Record<str
return variables
}
-export const encodeURLVariables = (variables: Record<string, any>): Record<string, string> => {
+export const encodeURLVariables = (variables: Record<string, HogQLVariable['value']>): Record<string, string> => {
const encodedVariables: Record<string, string> = {}
if (Object.keys(variables).length > 0) {
@@ -562,14 +562,3 @@ const LAYOUT_EDIT_EVENT_SOURCES = new Set<DashboardEventSource>([
export function isLayoutEditEventSource(source: DashboardEventSource | null): boolean {
return source !== null && LAYOUT_EDIT_EVENT_SOURCES.has(source)
}
-
-export function shouldSnapshotUrlAtEditModeEntry(source: DashboardEventSource | null): boolean {
- return (
- source !== null &&
- (isLayoutEditEventSource(source) ||
- source === DashboardEventSource.DashboardFilters ||
- source === DashboardEventSource.DashboardVariableOverride ||
- source === DashboardEventSource.DashboardInsightColorsModal ||
- source === DashboardEventSource.DashboardHeaderOverridesBanner)
- )
-}
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
index df115bcc6d42..f66404d5e7b1 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
@@ -24,13 +24,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { dashboardsModel, nameCompareFunction } from '~/models/dashboardsModel'
-import {
- AccessControlLevel,
- AccessControlResourceType,
- DashboardBasicType,
- DashboardMode,
- DashboardType,
-} from '~/types'
+import { AccessControlLevel, AccessControlResourceType, DashboardBasicType, DashboardType } from '~/types'
import { UNFILED_DASHBOARDS_FOLDER } from '../dashboardConstants'
import { DASHBOARD_CANNOT_EDIT_MESSAGE } from '../DashboardHeader'
@@ -255,8 +249,8 @@ export function DashboardsTable({
to={urls.dashboard(id)}
onClick={() => {
dashboardLogic({ id }).mount()
- dashboardLogic({ id }).actions.setDashboardMode(
- DashboardMode.Edit,
+ dashboardLogic({ id }).actions.setDashboardEditing(
+ { filters: true, layout: true },
DashboardEventSource.DashboardsList
)
}}
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index 0e15272d17f3..a1522f9e5d97 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -30,7 +30,7 @@ import { deleteInsightWithUndo } from 'lib/utils/deleteWithUndo'
import { InsightEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { isEmptyObject, isObject } from 'lib/utils/guards'
import { objectsEqual } from 'lib/utils/objects'
-import { isDashboardFilterEmpty } from 'scenes/dashboard/dashboardFilterEmpty'
+import { isDashboardFilterOverrideEmpty } from 'scenes/dashboard/dashboardFilterEmpty'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
@@ -539,9 +539,9 @@ export function insightOverridesPresent(
tileFiltersOverride?: TileFilters | null
): boolean {
return (
- !isDashboardFilterEmpty(filtersOverride) ||
+ !isDashboardFilterOverrideEmpty(filtersOverride) ||
(isObject(variablesOverride) && !isEmptyObject(variablesOverride)) ||
- !isDashboardFilterEmpty(tileFiltersOverride)
+ !isDashboardFilterOverrideEmpty(tileFiltersOverride)
)
}
diff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsx
index 2773dc732681..a53943416512 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.tsx
+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx
@@ -20,7 +20,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { InsightEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { isEmptyObject, isObject } from 'lib/utils/guards'
-import { isDashboardFilterEmpty } from 'scenes/dashboard/dashboardFilterEmpty'
+import { isDashboardFilterOverrideEmpty } from 'scenes/dashboard/dashboardFilterEmpty'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import {
SEARCH_PARAM_FILTERS_KEY,
@@ -682,9 +682,9 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
variablesOverride: Record<string, HogQLVariable> | null,
tileFiltersOverride: TileFilters | null
) =>
- !isDashboardFilterEmpty(filtersOverride) ||
+ !isDashboardFilterOverrideEmpty(filtersOverride) ||
(isObject(variablesOverride) && !isEmptyObject(variablesOverride)) ||
- !isDashboardFilterEmpty(tileFiltersOverride),
+ !isDashboardFilterOverrideEmpty(tileFiltersOverride),
],
}),
sharedListeners(({ actions, values }) => ({
@@ -894,9 +894,9 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
itemId,
alert_id,
// Only pass filters/variables if overrides exist
- filtersOverride && isDashboardFilterEmpty(filtersOverride) ? undefined : filtersOverride,
+ filtersOverride && isDashboardFilterOverrideEmpty(filtersOverride) ? undefined : filtersOverride,
variablesOverride && !isEmptyObject(variablesOverride) ? variablesOverride : undefined,
- tileFiltersOverride && isDashboardFilterEmpty(tileFiltersOverride)
+ tileFiltersOverride && isDashboardFilterOverrideEmpty(tileFiltersOverride)
? undefined
: tileFiltersOverride,
dashboard,
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 015a182f7ac5..050d98b2ef3a 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4764,7 +4764,6 @@ export enum DashboardPlacement {
// Default mode is null
export enum DashboardMode {
- Edit = 'edit', // When the dashboard is being edited
Fullscreen = 'fullscreen', // When the dashboard is on full screen (presentation) mode
Sharing = 'sharing', // When the sharing configuration is opened
}
diff --git a/playwright/e2e/product-analytics/dashboards.spec.ts b/playwright/e2e/product-analytics/dashboards.spec.ts
index 5af895389a1e..35ea51eccab5 100644
--- a/playwright/e2e/product-analytics/dashboards.spec.ts
+++ b/playwright/e2e/product-analytics/dashboards.spec.ts
@@ -467,7 +467,6 @@ test.describe('Dashboard link variable and filter overrides', () => {
await expect(dashboard.insightCards).toBeVisible()
await expect(dashboard.variableButtons.first()).toContainText(String(urlOverride))
await expect(dashboard.dateFilter).toContainText('Last 7 days')
- await expect(dashboard.overridesBanner).toBeVisible()
})
})
diff --git a/playwright/page-models/dashboardPage.ts b/playwright/page-models/dashboardPage.ts
index af513f0e38ad..fc5b353f6341 100644
--- a/playwright/page-models/dashboardPage.ts
+++ b/playwright/page-models/dashboardPage.ts
@@ -12,7 +12,6 @@ export class DashboardPage {
readonly insightCards: Locator
readonly textCards: Locator
readonly dateFilter: Locator
- readonly overridesBanner: Locator
readonly variableButtons: Locator
constructor(page: Page) {
@@ -23,7 +22,6 @@ export class DashboardPage {
this.insightCards = page.locator('.InsightCard')
this.textCards = page.getByTestId('text-card')
this.dateFilter = page.getByTestId('date-filter')
- this.overridesBanner = page.getByText('You are viewing this dashboard with filter overrides.')
this.variableButtons = page.locator('.DataVizVariable_Button')
}
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
index 1056c49bebba..ea14d5b5acef 100644
--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
@@ -8237,148 +8237,6 @@
5 /* ... */))
'''
# ---
-# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.176
- '''
- SELECT "posthog_taggeditem"."id",
- "posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_tag"."id",
- "posthog_tag"."name",
- "posthog_tag"."team_id"
- FROM "posthog_taggeditem"
- INNER JOIN "posthog_tag" ON ("posthog_taggeditem"."tag_id" = "posthog_tag"."id")
- WHERE "posthog_taggeditem"."insight_id" IN (1,
- 2,
- 3,
- 4,
- 5 /* ... */)
- '''
-# ---
-# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.177
- '''
- SELECT "posthog_alertconfiguration"."created_by_id",
- "posthog_alertconfiguration"."created_at",
- "posthog_alertconfiguration"."id",
- "posthog_alertconfiguration"."team_id",
- "posthog_alertconfiguration"."insight_id",
- "posthog_alertconfiguration"."name",
- "posthog_alertconfiguration"."config",
- "posthog_alertconfiguration"."calculation_interval",
- "posthog_alertconfiguration"."threshold_id",
- "posthog_alertconfiguration"."condition",
- "posthog_alertconfiguration"."detector_config",
- "posthog_alertconfiguration"."state",
- "posthog_alertconfiguration"."enabled",
- "posthog_alertconfiguration"."last_notified_at",
- "posthog_alertconfiguration"."last_checked_at",
- "posthog_alertconfiguration"."next_check_at",
- "posthog_alertconfiguration"."snoozed_until",
- "posthog_alertconfiguration"."skip_weekend",
- "posthog_alertconfiguration"."schedule_restriction",
- "posthog_alertconfiguration"."investigation_agent_enabled",
- "posthog_alertconfiguration"."investigation_gates_notifications",
- "posthog_alertconfiguration"."investigation_inconclusive_action",
- "posthog_user"."id",
- "posthog_user"."password",
- "posthog_user"."last_login",
- "posthog_user"."first_name",
- "posthog_user"."last_name",
- "posthog_user"."is_staff",
- "posthog_user"."date_joined",
- "posthog_user"."uuid",
- "posthog_user"."current_organization_id",
- "posthog_user"."current_team_id",
- "posthog_user"."email",
- "posthog_user"."pending_email",
- "posthog_user"."distinct_id",
- "posthog_user"."is_email_verified",
- "posthog_user"."credentials_reviewed_at",
- "posthog_user"."requested_password_reset_at",
- "posthog_user"."requested_2fa_reset_at",
- "posthog_user"."has_seen_product_intro_for",
- "posthog_user"."strapi_id",
- "posthog_user"."is_active",
- "posthog_user"."role_at_organization",
- "posthog_user"."theme_mode",
- "posthog_user"."partial_notification_settings",
- "posthog_user"."anonymize_data",
- "posthog_user"."allow_impersonation",
- "posthog_user"."toolbar_mode",
- "posthog_user"."hedgehog_config",
- "posthog_user"."allow_sidebar_suggestions",
- "posthog_user"."shortcut_position",
- "posthog_user"."passkeys_enabled_for_2fa",
- "posthog_user"."hide_mcp_hints",
- "posthog_user"."ui_configuration",
- "posthog_user"."onboarding_skipped_at",
- "posthog_user"."onboarding_skipped_reason",
- "posthog_user"."onboarding_skipped_organization_id",
- "posthog_user"."onboarding_delegated_to_invite_id",
- "posthog_user"."onboarding_delegated_to_organization_id",
- "posthog_user"."onboarding_delegation_accepted_at",
- "posthog_user"."events_column_config",
- "posthog_user"."email_opt_in",
- "posthog_threshold"."created_by_id",
- "posthog_threshold"."created_at",
- "posthog_threshold"."id",
- "posthog_threshold"."team_id",
- "posthog_threshold"."insight_id",
- "posthog_threshold"."name",
- "posthog_threshold"."configuration"
- FROM "posthog_alertconfiguration"
- LEFT OUTER JOIN "posthog_user" ON ("posthog_alertconfiguration"."created_by_id" = "posthog_user"."id")
- LEFT OUTER JOIN "posthog_threshold" ON ("posthog_alertconfiguration"."threshold_id" = "posthog_threshold"."id")
- WHERE "posthog_alertconfiguration"."insight_id" IN (1,
- 2,
- 3,
- 4,
- 5 /* ... */)
- '''
-# ---
-# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.178
- '''
- SELECT "posthog_dashboard"."id",
- "posthog_dashboard"."name",
- "posthog_dashboard"."description",
- "posthog_dashboard"."team_id",
- "posthog_dashboard"."pinned",
- "posthog_dashboard"."created_at",
- "posthog_dashboard"."created_by_id",
- "posthog_dashboard"."deleted",
- "posthog_dashboard"."last_accessed_at",
- "posthog_dashboard"."last_refresh",
- "posthog_dashboard"."filters",
- "posthog_dashboard"."variables",
- "posthog_dashboard"."breakdown_colors",
- "posthog_dashboard"."data_color_theme_id",
- "posthog_dashboard"."creation_mode",
- "posthog_dashboard"."restriction_level",
- "posthog_dashboard"."quick_filter_ids",
- "posthog_dashboard"."customization",
- "posthog_dashboard"."deprecated_tags",
- "posthog_dashboard"."tags",
- "posthog_dashboard"."share_token",
- "posthog_dashboard"."is_shared"
- FROM "posthog_dashboard"
- WHERE (NOT ("posthog_dashboard"."deleted")
- AND "posthog_dashboard"."id" IN (1,
- 2,
- 3,
- 4,
- 5 /* ... */))
- '''
-# ---
# name: TestDashboard.test_loading_individual_dashboard_does_not_prefetch_all_possible_tiles.18
'''
SELECT "posthog_insightvariable"."id",
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 42cd84e9d4d0..5b2842fccf06 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -853,6 +853,19 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
dashboard.refresh_from_db()
self.assertEqual(dashboard.filters, {})
+ def test_can_clear_dashboard_filters(self) -> None:
+ dashboard = Dashboard.objects.create(
+ team=self.team,
+ name="dashboard",
+ created_by=self.user,
+ filters={"date_from": "-7d"},
+ )
+
+ self.dashboard_api.update_dashboard(dashboard.pk, {"filters": {}})
+
+ dashboard.refresh_from_db()
+ self.assertEqual(dashboard.filters, {})
+
def test_cannot_update_dashboard_with_invalid_variables(self):
dashboard = Dashboard.objects.create(
team=self.team,
@@ -860,11 +873,12 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
created_by=self.user,
variables={"existing": "value"},
)
- self.dashboard_api.update_dashboard(
+ _, response = self.dashboard_api.update_dashboard(
dashboard.pk,
{"variables": ["not", "a", "dict"]},
expected_status=status.HTTP_400_BAD_REQUEST,
)
+ self.assertEqual(response["detail"], "Variables must be a dictionary")
dashboard.refresh_from_db()
self.assertEqual(dashboard.variables, {"existing": "value"})
@@ -3215,6 +3229,29 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
assert value["variableId"] == str(variable.id)
assert value["value"] == "some override value"
+ def test_clearing_the_last_dashboard_variable_persists(self):
+ variable = InsightVariable.objects.create(
+ team=self.team, name="Test 1", code_name="test_1", default_value="some_default_value", type="String"
+ )
+ dashboard = Dashboard.objects.create(
+ team=self.team,
+ name="dashboard 1",
+ created_by=self.user,
+ variables={
+ str(variable.id): {
+ "code_name": variable.code_name,
+ "variableId": str(variable.id),
+ "value": "some override value",
+ }
+ },
+ )
+
+ _, response_data = self.dashboard_api.update_dashboard(dashboard.pk, {"variables": {}})
+
+ assert response_data["persisted_variables"] is None
+ dashboard.refresh_from_db()
+ assert dashboard.variables == {}
+
def test_dashboard_variables_stale(self):
# if a variable is deleted/updated, the dashboard should not show the stale variable
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index bb81d73446f0..5f7508b03257 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -1888,13 +1888,14 @@ class DashboardSerializer(DashboardMetadataSerializer):
)
request_filters = initial_data.get("filters")
- if request_filters:
+ if request_filters is not None:
instance.filters = self._validated_filters(request_filters)
request_variables = initial_data.get("variables")
- if request_variables:
+ # An empty dict is a real value here: it clears the last remaining variable override.
+ if request_variables is not None:
if not isinstance(request_variables, dict):
- raise serializers.ValidationError("Filters must be a dictionary")
+ raise serializers.ValidationError("Variables must be a dictionary")
instance.variables = request_variables
instance = super().update(instance, validated_data)
diff --git a/products/dashboards/frontend/DashboardFilters.stories.tsx b/products/dashboards/frontend/DashboardFilters.stories.tsx
new file mode 100644
index 000000000000..51b19a7aa441
--- /dev/null
+++ b/products/dashboards/frontend/DashboardFilters.stories.tsx
@@ -0,0 +1,275 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { waitFor } from '@testing-library/react'
+import { BindLogic } from 'kea'
+import { router } from 'kea-router'
+
+import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
+import { DashboardFilterBar } from 'scenes/dashboard/DashboardFilters'
+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import { encodeURLFilters, encodeURLVariables } from 'scenes/dashboard/dashboardUtils'
+
+import { mswDecorator } from '~/mocks/browser'
+import { variableDataLogic } from '~/queries/nodes/DataVisualization/Components/Variables/variableDataLogic'
+import { NodeKind, type DashboardFilter } from '~/queries/schema/schema-general'
+import {
+ AccessControlLevel,
+ DashboardType,
+ PropertyFilterType,
+ PropertyOperator,
+ QueryBasedInsightModel,
+} from '~/types'
+
+type FilterBarState = 'saved' | 'unsaved'
+type DashboardFilterKind = 'date' | 'properties' | 'breakdown' | 'interval' | 'testAccounts'
+type DashboardChangeKind = DashboardFilterKind | 'sqlVariables'
+
+const dashboardFilterKinds: DashboardFilterKind[] = ['date', 'properties', 'breakdown', 'interval', 'testAccounts']
+const dashboardChangeKinds: DashboardChangeKind[] = [...dashboardFilterKinds, 'sqlVariables']
+const dashboardChangeKindLabels: Record<DashboardChangeKind, string> = {
+ date: 'Date',
+ properties: 'Properties',
+ breakdown: 'Breakdown',
+ interval: 'Interval',
+ testAccounts: 'Test accounts',
+ sqlVariables: 'SQL variables',
+}
+
+interface DashboardFilterBarStoryProps {
+ state: FilterBarState
+ readOnly: boolean
+ filterChanges: DashboardChangeKind[]
+ urlOverrideFilters: DashboardChangeKind[]
+ narrow: boolean
+}
+
+const DASHBOARD_ID = 955
+
+const dashboard: DashboardType<QueryBasedInsightModel> = {
+ id: DASHBOARD_ID,
+ name: 'Dashboard filter states',
+ description: '',
+ pinned: false,
+ tiles: [],
+ tags: [],
+ created_at: '2020-01-01T00:00:00Z',
+ created_by: null,
+ last_accessed_at: '2020-01-01T00:00:00Z',
+ is_shared: false,
+ deleted: false,
+ creation_mode: 'default',
+ user_access_level: AccessControlLevel.Editor,
+ filters: {},
+ variables: {},
+}
+
+const SQL_VARIABLE_ID = 'organization'
+const SQL_VARIABLE_DEFAULT = 'Default organization'
+const SQL_VARIABLE_OVERRIDE = 'Example organization'
+
+const sqlVariablesDashboard: DashboardType<QueryBasedInsightModel> = {
+ ...dashboard,
+ tiles: [
+ {
+ id: 1,
+ layouts: {},
+ color: null,
+ insight: {
+ id: 1,
+ short_id: 'sql-variables',
+ name: 'SQL variable preview',
+ query: {
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: 'select {variables.organization}',
+ variables: { [SQL_VARIABLE_ID]: { variableId: SQL_VARIABLE_ID, code_name: SQL_VARIABLE_ID } },
+ },
+ chartSettings: {},
+ tableSettings: {},
+ },
+ } as unknown as QueryBasedInsightModel,
+ },
+ ],
+ persisted_variables: {
+ [SQL_VARIABLE_ID]: {
+ code_name: SQL_VARIABLE_ID,
+ variableId: SQL_VARIABLE_ID,
+ value: SQL_VARIABLE_DEFAULT,
+ isNull: false,
+ },
+ },
+}
+
+function dashboardFilters(filterKinds: DashboardChangeKind[]): DashboardFilter {
+ return {
+ ...(filterKinds.includes('date') ? { date_from: '-7d' } : {}),
+ ...(filterKinds.includes('properties')
+ ? {
+ properties: [
+ {
+ key: 'browser',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'Chrome',
+ },
+ ],
+ }
+ : {}),
+ ...(filterKinds.includes('breakdown')
+ ? { breakdown_filter: { breakdown: '$browser', breakdown_type: 'event' } }
+ : {}),
+ ...(filterKinds.includes('interval') ? { interval: 'week' } : {}),
+ ...(filterKinds.includes('testAccounts') ? { filterTestAccounts: true } : {}),
+ }
+}
+
+function applyUnsavedFilters(logic: ReturnType<typeof dashboardLogic.build>, filterKinds: DashboardChangeKind[]): void {
+ const filters = dashboardFilters(filterKinds)
+
+ logic.actions.setDashboardEditing({ filters: true, layout: false }, DashboardEventSource.DashboardFilters)
+ if (filters.date_from) {
+ logic.actions.setDates(filters.date_from, null)
+ }
+ if (filters.properties) {
+ logic.actions.setProperties(filters.properties)
+ }
+ if (filters.breakdown_filter) {
+ logic.actions.setBreakdownFilter(filters.breakdown_filter)
+ }
+ if (filters.interval) {
+ logic.actions.setInterval(filters.interval)
+ }
+ if (filters.filterTestAccounts) {
+ logic.actions.setFilterTestAccounts(filters.filterTestAccounts)
+ }
+ if (filterKinds.includes('sqlVariables')) {
+ logic.actions.overrideVariableValue(SQL_VARIABLE_ID, SQL_VARIABLE_OVERRIDE, false)
+ }
+}
+
+function DashboardFilterBarStory({
+ state,
+ readOnly,
+ filterChanges,
+ urlOverrideFilters,
+ narrow,
+}: DashboardFilterBarStoryProps): JSX.Element {
+ const hasSqlVariables =
+ (state !== 'saved' && filterChanges.includes('sqlVariables')) || urlOverrideFilters.includes('sqlVariables')
+ const storyDashboard = {
+ ...(hasSqlVariables ? sqlVariablesDashboard : dashboard),
+ user_access_level: readOnly ? AccessControlLevel.Viewer : AccessControlLevel.Editor,
+ }
+
+ router.actions.push(`/dashboard/${DASHBOARD_ID}`, {
+ ...encodeURLFilters(dashboardFilters(urlOverrideFilters)),
+ ...encodeURLVariables(
+ urlOverrideFilters.includes('sqlVariables') ? { organization: SQL_VARIABLE_OVERRIDE } : {}
+ ),
+ })
+
+ const logic = dashboardLogic({ id: DASHBOARD_ID, dashboard: storyDashboard })
+ logic.mount()
+ logic.actions.setDashboardSettingsDraft(null)
+
+ if (hasSqlVariables) {
+ variableDataLogic.mount()
+ variableDataLogic.actions.loadVariablesSuccess([
+ {
+ id: SQL_VARIABLE_ID,
+ name: 'Organization',
+ code_name: SQL_VARIABLE_ID,
+ type: 'String',
+ default_value: SQL_VARIABLE_DEFAULT,
+ },
+ ])
+ }
+
+ if (state !== 'saved') {
+ applyUnsavedFilters(logic, filterChanges)
+ }
+
+ return (
+ <div className={`p-4 ${narrow ? 'w-96' : 'max-w-5xl'}`}>
+ <BindLogic logic={dashboardLogic} props={{ id: DASHBOARD_ID, dashboard: storyDashboard }}>
+ <DashboardFilterBar />
+ </BindLogic>
+ </div>
+ )
+}
+
+const meta: Meta<DashboardFilterBarStoryProps> = {
+ component: DashboardFilterBarStory,
+ title: 'Products/Dashboards/Filter bar',
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/events/values': { results: [] },
+ '/api/environments/:team_id/persons/properties': [],
+ '/api/environments/:team_id/insight_variables/': {
+ results: [
+ {
+ id: SQL_VARIABLE_ID,
+ name: 'Organization',
+ code_name: SQL_VARIABLE_ID,
+ type: 'String',
+ default_value: SQL_VARIABLE_DEFAULT,
+ },
+ ],
+ },
+ },
+ post: {
+ '/api/environments/:team_id/query/': () => [200, { results: [] }],
+ },
+ }),
+ ],
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ },
+ argTypes: {
+ state: { control: 'inline-radio', options: ['saved', 'unsaved'] satisfies FilterBarState[] },
+ readOnly: { control: 'boolean' },
+ filterChanges: {
+ control: { type: 'check', labels: dashboardChangeKindLabels },
+ options: dashboardChangeKinds,
+ name: 'Unsaved filter changes',
+ },
+ urlOverrideFilters: {
+ control: { type: 'check', labels: dashboardChangeKindLabels },
+ options: dashboardChangeKinds,
+ name: 'URL override filters',
+ },
+ narrow: { control: 'boolean' },
+ },
+ args: {
+ state: 'unsaved',
+ readOnly: false,
+ filterChanges: dashboardChangeKinds,
+ urlOverrideFilters: [],
+ narrow: false,
+ },
+}
+
+export default meta
+
+type Story = StoryObj<DashboardFilterBarStoryProps>
+
+export const FilterBar: Story = {}
+
+export const UnsavedChangesPopover: Story = {
+ args: {
+ state: 'unsaved',
+ filterChanges: dashboardFilterKinds,
+ },
+ play: async () => {
+ const trigger = await waitFor(() => {
+ const element = document.querySelector<HTMLElement>('[aria-label="Show 5 unsaved filters"]')
+ if (!element) {
+ throw new Error('Unsaved changes trigger not found')
+ }
+ return element
+ })
+ trigger.click()
+ },
+}
diff --git a/products/dashboards/frontend/dashboardSettings/DashboardFilters.test.tsx b/products/dashboards/frontend/dashboardSettings/DashboardFilters.test.tsx
new file mode 100644
index 000000000000..1e906d80b2c8
--- /dev/null
+++ b/products/dashboards/frontend/dashboardSettings/DashboardFilters.test.tsx
@@ -0,0 +1,357 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { BindLogic } from 'kea'
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import * as featureFlagLib from 'lib/logic/featureFlagLogic'
+import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
+import { DashboardFilterBar } from 'scenes/dashboard/DashboardFilters'
+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import * as dashboardUtils from 'scenes/dashboard/dashboardUtils'
+import { SEARCH_PARAM_FILTERS_KEY } from 'scenes/dashboard/dashboardUtils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { AccessControlLevel, DashboardPlacement, DashboardType, QueryBasedInsightModel } from '~/types'
+
+const MOCK_DASHBOARD: DashboardType<QueryBasedInsightModel> = {
+ id: 5,
+ name: 'Test Dashboard',
+ description: 'A test dashboard',
+ pinned: false,
+ tiles: [],
+ tags: [],
+ created_at: '2020-01-01T00:00:00Z',
+ created_by: {
+ id: 1,
+ first_name: 'Test',
+ last_name: 'User',
+ email: '[email protected]',
+ uuid: 'abc',
+ distinct_id: 'test-distinct-id',
+ },
+ last_accessed_at: '2020-01-01T00:00:00Z',
+ is_shared: false,
+ deleted: false,
+ creation_mode: 'default',
+ user_access_level: AccessControlLevel.Editor,
+ filters: {},
+ variables: {},
+}
+
+beforeAll(() => {
+ const root = document.createElement('div')
+ root.id = 'root'
+ document.body.appendChild(root)
+})
+
+describe('DashboardFilterBar', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ sessionStorage.clear()
+ useMocks({
+ get: {
+ '/api/environments/:team_id/events/values': { results: [] },
+ '/api/environments/:team_id/persons/properties': [],
+ },
+ post: {
+ '/api/environments/:team_id/query/': () => [200, { results: [] }],
+ },
+ })
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ function renderFilterBar(
+ dashboardModeSource: DashboardEventSource,
+ dashboard: DashboardType<QueryBasedInsightModel> = MOCK_DASHBOARD,
+ placement: DashboardPlacement = DashboardPlacement.Dashboard
+ ): ReturnType<typeof dashboardLogic.build> {
+ const logic = dashboardLogic({ id: dashboard.id, dashboard, placement })
+ logic.mount()
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: dashboardModeSource === DashboardEventSource.SceneCommonButtons },
+ dashboardModeSource
+ )
+
+ render(
+ <BindLogic logic={dashboardLogic} props={{ id: dashboard.id, dashboard, placement }}>
+ <DashboardFilterBar />
+ </BindLogic>
+ )
+
+ return logic
+ }
+
+ it('shows editable filter controls while editing the layout', () => {
+ const logic = renderFilterBar(DashboardEventSource.SceneCommonButtons)
+
+ expect(document.querySelector('[data-attr="date-filter"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="date-filter"]')).toHaveAttribute('aria-disabled', 'false')
+ expect(document.querySelector('[data-attr="dashboard-advanced-filters"]')).toHaveAttribute(
+ 'aria-disabled',
+ 'false'
+ )
+
+ logic.unmount()
+ })
+
+ it('marks unsaved filters with inline save actions', async () => {
+ const logic = renderFilterBar(DashboardEventSource.DashboardFilters)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ expect(document.querySelector('[data-attr="dashboard-filters-unsaved"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-save-filters"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-edit-mode-discard"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-items-action-refresh"]')).toBeInTheDocument()
+ expect(screen.getByLabelText('Show 1 unsaved filter')).toBeInTheDocument()
+
+ logic.unmount()
+ })
+
+ it('keeps Preview and Discard available, but hides Save filters, for viewers', async () => {
+ const payloadSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(0)
+ const viewerDashboard: DashboardType<QueryBasedInsightModel> = {
+ ...MOCK_DASHBOARD,
+ user_access_level: AccessControlLevel.Viewer,
+ tiles: [
+ {
+ id: 1,
+ color: null,
+ layouts: {},
+ insight: { id: 1, short_id: 'viewer', name: 'Viewer' } as QueryBasedInsightModel,
+ },
+ ],
+ }
+ const logic = renderFilterBar(DashboardEventSource.DashboardFilters, viewerDashboard)
+
+ try {
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ expect(document.querySelector('[data-attr="dashboard-edit-mode-discard"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-save-filters"]')).not.toBeInTheDocument()
+ } finally {
+ payloadSpy.mockRestore()
+ logic.unmount()
+ }
+ })
+
+ it('keeps Preview disabled until the dashboard settings change', async () => {
+ const payloadSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(0)
+ let finishPreview: (insight: QueryBasedInsightModel) => void = () => {
+ throw new Error('Preview resolver is unavailable')
+ }
+ const preview = new Promise<QueryBasedInsightModel>((resolve) => {
+ finishPreview = resolve
+ })
+ const getInsightSpy = jest
+ .spyOn(dashboardUtils, 'getInsightWithRetry')
+ .mockImplementation(async (_teamId, insight) => insight)
+ const previewDashboard: DashboardType<QueryBasedInsightModel> = {
+ ...MOCK_DASHBOARD,
+ tiles: [
+ {
+ id: 1,
+ color: null,
+ layouts: {},
+ insight: { id: 1, short_id: 'preview', name: 'Preview' } as QueryBasedInsightModel,
+ },
+ ],
+ }
+ const logic = renderFilterBar(DashboardEventSource.DashboardFilters, previewDashboard)
+ await expectLogic(logic).toFinishAllListeners()
+ getInsightSpy.mockReturnValue(preview)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toHaveTextContent('Preview')
+
+ logic.actions.previewDashboardChanges()
+
+ await waitFor(() => {
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toHaveTextContent('Previewing')
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toHaveAttribute(
+ 'aria-disabled',
+ 'true'
+ )
+ })
+
+ finishPreview(previewDashboard.tiles[0].insight!)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toHaveTextContent('Previewing')
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toHaveAttribute('aria-disabled', 'true')
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-30d', null)
+ }).toFinishAllListeners()
+
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toHaveTextContent('Preview')
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toHaveAttribute(
+ 'aria-disabled',
+ 'false'
+ )
+
+ getInsightSpy.mockRestore()
+ payloadSpy.mockRestore()
+ logic.unmount()
+ })
+
+ it('makes Preview available after a preview request fails', async () => {
+ const payloadSpy = jest.spyOn(featureFlagLib, 'getFeatureFlagPayload').mockReturnValue(0)
+ const getInsightSpy = jest
+ .spyOn(dashboardUtils, 'getInsightWithRetry')
+ .mockRejectedValue(new Error('Preview request failed'))
+ const previewDashboard: DashboardType<QueryBasedInsightModel> = {
+ ...MOCK_DASHBOARD,
+ tiles: [
+ {
+ id: 1,
+ color: null,
+ layouts: {},
+ insight: { id: 1, short_id: 'preview', name: 'Preview' } as QueryBasedInsightModel,
+ },
+ ],
+ }
+ const logic = renderFilterBar(DashboardEventSource.DashboardFilters, previewDashboard)
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.previewDashboardChanges()
+ }).toFinishAllListeners()
+
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toHaveTextContent('Preview')
+ expect(document.querySelector('[data-attr="dashboard-apply-filters"]')).toHaveAttribute(
+ 'aria-disabled',
+ 'false'
+ )
+
+ getInsightSpy.mockRestore()
+ payloadSpy.mockRestore()
+ logic.unmount()
+ })
+
+ it('shows a separate save action for unsaved filters while editing the layout', async () => {
+ const logic = renderFilterBar(DashboardEventSource.SceneCommonButtons)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ expect(document.querySelector('[data-attr="dashboard-filters-unsaved"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-save-filters"]')).toBeInTheDocument()
+
+ logic.unmount()
+ })
+
+ it('keeps unsaved filter actions visible after cancelling layout editing', async () => {
+ const logic = renderFilterBar(DashboardEventSource.SceneCommonButtons)
+
+ await expectLogic(logic, () => {
+ logic.actions.setDates('-7d', null)
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.cancelLayoutEdit()
+ }).toFinishAllListeners()
+
+ expect(document.querySelector('[data-attr="dashboard-filters-unsaved"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-save-filters"]')).toBeInTheDocument()
+
+ logic.unmount()
+ })
+
+ it('keeps edited URL overrides as unsaved after cancelling layout editing', async () => {
+ router.actions.push('/', {
+ [SEARCH_PARAM_FILTERS_KEY]: JSON.stringify({ date_from: '-7d' }),
+ })
+ const logic = dashboardLogic({ id: MOCK_DASHBOARD.id, dashboard: MOCK_DASHBOARD })
+ logic.mount()
+
+ render(
+ <BindLogic logic={dashboardLogic} props={{ id: MOCK_DASHBOARD.id, dashboard: MOCK_DASHBOARD }}>
+ <DashboardFilterBar />
+ </BindLogic>
+ )
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing({ filters: true, layout: false }, DashboardEventSource.DashboardFilters)
+ logic.actions.setDates('-30d', null)
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setDashboardEditing({ filters: true, layout: true }, DashboardEventSource.SceneCommonButtons)
+ logic.actions.cancelLayoutEdit()
+ }).toFinishAllListeners()
+
+ expect(document.querySelector('[data-attr="dashboard-filters-unsaved"]')).toBeInTheDocument()
+
+ logic.unmount()
+ })
+
+ it('shows URL overrides as unsaved changes', async () => {
+ router.actions.push('/', {
+ [SEARCH_PARAM_FILTERS_KEY]: JSON.stringify({ date_from: '-7d' }),
+ })
+ const logic = dashboardLogic({ id: MOCK_DASHBOARD.id, dashboard: MOCK_DASHBOARD })
+ logic.mount()
+ logic.actions.setDashboardEditing(null, DashboardEventSource.DashboardFilters)
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ render(
+ <BindLogic logic={dashboardLogic} props={{ id: MOCK_DASHBOARD.id, dashboard: MOCK_DASHBOARD }}>
+ <DashboardFilterBar />
+ </BindLogic>
+ )
+
+ expect(document.querySelector('[data-attr="dashboard-filters-unsaved"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-save-filters"]')).toBeInTheDocument()
+
+ logic.unmount()
+ })
+
+ it('lets a dashboard viewer identify and discard URL overrides', async () => {
+ router.actions.push('/', {
+ [SEARCH_PARAM_FILTERS_KEY]: JSON.stringify({ date_from: '-7d' }),
+ })
+ const viewerDashboard = { ...MOCK_DASHBOARD, user_access_level: AccessControlLevel.Viewer }
+ const logic = renderFilterBar(DashboardEventSource.DashboardFilters, viewerDashboard)
+
+ expect(document.querySelector('[data-attr="dashboard-filters-unsaved"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-edit-mode-discard"]')).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-save-filters"]')).not.toBeInTheDocument()
+
+ logic.unmount()
+ })
+
+ it.each(Object.values(DashboardPlacement).filter((placement) => placement !== DashboardPlacement.Dashboard))(
+ 'does not show dashboard setting actions in the %s placement',
+ async (placement) => {
+ router.actions.push('/', {
+ [SEARCH_PARAM_FILTERS_KEY]: JSON.stringify({ date_from: '-7d' }),
+ })
+ const logic = renderFilterBar(DashboardEventSource.DashboardFilters, MOCK_DASHBOARD, placement)
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(document.querySelector('[data-attr="dashboard-filters-unsaved"]')).not.toBeInTheDocument()
+ logic.unmount()
+ }
+ )
+})
diff --git a/products/dashboards/frontend/dashboardSettings/DashboardSettingsChangesTooltip.tsx b/products/dashboards/frontend/dashboardSettings/DashboardSettingsChangesTooltip.tsx
new file mode 100644
index 000000000000..41139c4b6970
--- /dev/null
+++ b/products/dashboards/frontend/dashboardSettings/DashboardSettingsChangesTooltip.tsx
@@ -0,0 +1,104 @@
+import type { ReactNode } from 'react'
+
+import { IconCalendar, IconClock, IconFilter, IconPeople, IconSort } from '@posthog/icons'
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { InsightDetailSectionDisplay } from 'lib/components/Cards/InsightCard/InsightDetails'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
+import type { DashboardFilterChange } from './dashboardChanges'
+
+interface DashboardSettingsChangesTooltipProps {
+ changes: DashboardFilterChange[]
+ children: ReactNode
+ title?: string
+}
+
+function getChangeIcon(label: DashboardFilterChange['label']): JSX.Element {
+ if (label === 'Date range') {
+ return <IconCalendar />
+ }
+ if (label === 'Grouped by') {
+ return <IconClock />
+ }
+ if (label === 'Breakdown by') {
+ return <IconSort />
+ }
+ if (label === 'Test accounts') {
+ return <IconPeople />
+ }
+ return <IconFilter />
+}
+
+function ChangeValue({ value }: { value: string[] }): JSX.Element {
+ if (value.length === 0) {
+ return <span>Default</span>
+ }
+
+ if (value.length === 1) {
+ return <span className="break-all">{value[0]}</span>
+ }
+
+ return (
+ <span className="flex flex-wrap gap-1">
+ {value.map((item) => (
+ <LemonTag key={item} type="muted" size="small">
+ {item}
+ </LemonTag>
+ ))}
+ </span>
+ )
+}
+
+function renderChangeValue(change: DashboardFilterChange): JSX.Element {
+ return (
+ <div className="flex flex-wrap items-center gap-1 break-words">
+ <span className="min-w-0 text-muted-alt">
+ <ChangeValue value={change.previousValue} />
+ </span>
+ <span aria-hidden="true">→</span>
+ <span className="sr-only">changed to</span>
+ <span className="font-medium">
+ <ChangeValue value={change.value} />
+ </span>
+ </div>
+ )
+}
+
+export function DashboardSettingsChangesTooltip({
+ changes,
+ children,
+ title = 'Filter changes',
+}: DashboardSettingsChangesTooltipProps): JSX.Element {
+ if (!changes.length) {
+ return <>{children}</>
+ }
+
+ return (
+ <Tooltip
+ placement="bottom-start"
+ className="border border-primary bg-surface-primary p-4 text-primary"
+ containerClassName="[--color-bg-surface-tooltip:var(--color-bg-surface-primary)]"
+ interactive
+ openOnClick
+ title={
+ <div className="max-w-sm">
+ <div className="mb-2 font-semibold">{title}</div>
+ <div className="InsightDetails space-y-2">
+ {changes.map((change, index) => (
+ <InsightDetailSectionDisplay
+ key={`${change.label}-${index}`}
+ icon={getChangeIcon(change.label)}
+ label={change.label}
+ >
+ {renderChangeValue(change)}
+ </InsightDetailSectionDisplay>
+ ))}
+ </div>
+ </div>
+ }
+ >
+ {children}
+ </Tooltip>
+ )
+}
diff --git a/products/dashboards/frontend/dashboardSettings/DashboardUnsavedChangesIndicator.tsx b/products/dashboards/frontend/dashboardSettings/DashboardUnsavedChangesIndicator.tsx
new file mode 100644
index 000000000000..4b02bd2ea192
--- /dev/null
+++ b/products/dashboards/frontend/dashboardSettings/DashboardUnsavedChangesIndicator.tsx
@@ -0,0 +1,134 @@
+import { useActions, useValues } from 'kea'
+import { Fragment } from 'react'
+
+import { IconInfo } from '@posthog/icons'
+import { LemonButton, LemonMenu } from '@posthog/lemon-ui'
+
+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+
+import { DashboardSettingsChangesTooltip } from './DashboardSettingsChangesTooltip'
+
+export function DashboardUnsavedChangesIndicator(): JSX.Element | null {
+ const {
+ dashboardSettingsState,
+ layoutEditMode,
+ canEditDashboard,
+ dashboardSettingsChanges,
+ dashboardFiltersSaving,
+ showApplyFiltersBanner,
+ loadingPreview,
+ } = useValues(dashboardLogic)
+ const { previewDashboardChanges, discardDashboardChanges, saveDashboardChanges } = useActions(dashboardLogic)
+
+ if (dashboardSettingsState !== 'unsavedChanges') {
+ return null
+ }
+
+ const changedCount = dashboardSettingsChanges.length
+ const changeSummary = `${changedCount} unsaved ${changedCount === 1 ? 'filter' : 'filters'}`
+ const discardDataAttr = layoutEditMode ? 'dashboard-discard-filters' : 'dashboard-edit-mode-discard'
+ const actions = [
+ {
+ key: 'discard',
+ label: 'Discard',
+ dataAttr: discardDataAttr,
+ disabledReason: dashboardFiltersSaving ? 'Dashboard filters are saving' : undefined,
+ tooltip: 'Restore the settings saved to this dashboard.',
+ onClick: discardDashboardChanges,
+ loading: false,
+ },
+ ...(showApplyFiltersBanner
+ ? [
+ {
+ key: 'preview',
+ label: loadingPreview ? 'Previewing' : 'Preview',
+ dataAttr: 'dashboard-apply-filters',
+ disabledReason: loadingPreview ? 'Previewing unsaved filters' : undefined,
+ tooltip: 'Update the dashboard data with these unsaved filters. This does not save them.',
+ onClick: previewDashboardChanges,
+ loading: false,
+ },
+ ]
+ : []),
+ ...(canEditDashboard
+ ? [
+ {
+ key: 'save',
+ label: 'Save filters',
+ dataAttr: 'dashboard-save-filters',
+ disabledReason: undefined,
+ tooltip: 'Save these changes as the dashboard default.',
+ onClick: saveDashboardChanges,
+ loading: dashboardFiltersSaving,
+ },
+ ]
+ : []),
+ ]
+
+ return (
+ <span
+ data-attr="dashboard-filters-unsaved"
+ className="flex max-w-full items-center gap-1.5 rounded-full border border-warning bg-warning-highlight py-0.5 pl-2.5 pr-1 text-xs font-semibold text-warning"
+ >
+ <DashboardSettingsChangesTooltip changes={dashboardSettingsChanges} title="Unsaved changes">
+ <LemonButton
+ type="tertiary"
+ size="small"
+ noPadding
+ className="text-inherit"
+ aria-label={`Show ${changeSummary}`}
+ >
+ <span className="flex items-center gap-1.5">
+ <span className="h-2 w-2 animate-pulse motion-reduce:animate-none rounded-full bg-warning" />
+ <span className="@max-lg/dashboard-filters:hidden whitespace-nowrap">{changeSummary}</span>
+ <span className="@min-lg/dashboard-filters:hidden whitespace-nowrap">
+ {`${changedCount} unsaved`}
+ </span>
+ <IconInfo className="text-sm" />
+ </span>
+ </LemonButton>
+ </DashboardSettingsChangesTooltip>
+ <span className="flex items-center gap-1.5 @max-lg/dashboard-filters:hidden">
+ <span className="h-4 border-l border-warning" />
+ <span className="flex items-center gap-1.5">
+ {actions.map((action, index) => (
+ <Fragment key={action.key}>
+ {index > 0 && <span className="h-4 border-l border-warning" />}
+ <LemonButton
+ data-attr={action.dataAttr}
+ type="tertiary"
+ size="small"
+ disabledReason={action.disabledReason}
+ tooltip={action.tooltip}
+ onClick={action.onClick}
+ loading={action.loading}
+ >
+ {action.label}
+ </LemonButton>
+ </Fragment>
+ ))}
+ </span>
+ </span>
+ <LemonMenu
+ items={actions.map((action) => ({
+ key: action.key,
+ label: action.label,
+ 'data-attr': action.dataAttr,
+ disabledReason: action.disabledReason,
+ tooltip: action.tooltip,
+ onClick: action.onClick,
+ }))}
+ placement="bottom-end"
+ >
+ <LemonButton
+ className="@min-lg/dashboard-filters:hidden"
+ type="tertiary"
+ size="small"
+ loading={dashboardFiltersSaving}
+ >
+ Actions
+ </LemonButton>
+ </LemonMenu>
+ </span>
+ )
+}
diff --git a/products/dashboards/frontend/dashboardSettings/dashboardChanges.test.ts b/products/dashboards/frontend/dashboardSettings/dashboardChanges.test.ts
new file mode 100644
index 000000000000..35c277d75044
--- /dev/null
+++ b/products/dashboards/frontend/dashboardSettings/dashboardChanges.test.ts
@@ -0,0 +1,291 @@
+import type { HogQLVariable } from '~/queries/schema/schema-general'
+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import {
+ dashboardFiltersEqual,
+ dashboardVariableValuesEqual,
+ getDashboardFilterChanges,
+ getDashboardVariableChanges,
+} from './dashboardChanges'
+
+describe('getDashboardFilterChanges', () => {
+ it('lists new, changed, and removed property filters with their values', () => {
+ expect(
+ getDashboardFilterChanges(
+ {
+ properties: [
+ {
+ key: 'browser',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'Chrome',
+ },
+ {
+ key: 'os',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'macOS',
+ },
+ ],
+ },
+ {
+ properties: [
+ {
+ key: 'browser',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'Firefox',
+ },
+ {
+ key: 'country',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'Canada',
+ },
+ ],
+ }
+ )
+ ).toEqual([
+ {
+ label: 'Property filter',
+ previousValue: ['browser = Chrome (event property)'],
+ value: ['browser = Firefox (event property)'],
+ status: 'changed',
+ },
+ {
+ label: 'Property filter',
+ previousValue: [],
+ value: ['country = Canada (event property)'],
+ status: 'new',
+ },
+ { label: 'Property filter', previousValue: ['os = macOS (event property)'], value: [], status: 'removed' },
+ ])
+ })
+
+ it('names the taxonomy of a property filter so a scope switch does not read as a no-op', () => {
+ const eventPlan: AnyPropertyFilter = {
+ key: 'plan',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'pro',
+ }
+ const personPlan: AnyPropertyFilter = { ...eventPlan, type: PropertyFilterType.Person }
+
+ expect(getDashboardFilterChanges({ properties: [eventPlan] }, { properties: [personPlan] })).toEqual([
+ {
+ label: 'Property filter',
+ previousValue: [],
+ value: ['plan = pro (person property)'],
+ status: 'new',
+ },
+ {
+ label: 'Property filter',
+ previousValue: ['plan = pro (event property)'],
+ value: [],
+ status: 'removed',
+ },
+ ])
+ })
+
+ it('groups date changes into one change', () => {
+ expect(getDashboardFilterChanges({}, { date_from: '-1d' })).toEqual([
+ { label: 'Date range', previousValue: [], value: ['Last 1 day'], status: 'new' },
+ ])
+ })
+
+ it.each([
+ ['interval', { interval: null }],
+ ['test accounts', { filterTestAccounts: null }],
+ ['breakdown', { breakdown_filter: null }],
+ ])('reports no change when %s returns to inherit', (_name, reverted) => {
+ expect(getDashboardFilterChanges({}, reverted)).toEqual([])
+ })
+
+ it('still reports a change when a saved setting returns to inherit', () => {
+ expect(getDashboardFilterChanges({ interval: 'week' }, { interval: null })).toEqual([
+ { label: 'Grouped by', previousValue: ['Week'], value: [], status: 'removed' },
+ ])
+ })
+
+ it('marks the exact time range mode on each side of a date change', () => {
+ expect(
+ getDashboardFilterChanges(
+ { date_from: '-7d', explicitDate: true },
+ { date_from: '-7d', explicitDate: false }
+ )
+ ).toEqual([
+ {
+ label: 'Date range',
+ previousValue: ['Last 7 days (exact time range)'],
+ value: ['Last 7 days'],
+ status: 'changed',
+ },
+ ])
+ })
+
+ it('shows the exact time range mode when no date range is set', () => {
+ expect(getDashboardFilterChanges({}, { explicitDate: true })).toEqual([
+ { label: 'Date range', previousValue: [], value: ['All time (exact time range)'], status: 'new' },
+ ])
+ })
+
+ it.each([
+ ['excludes test accounts when the filter is turned on', true, 'Excluded'],
+ ['includes test accounts when the filter is turned off', false, 'Included'],
+ ])('%s', (_name, filterTestAccounts, expectedValue) => {
+ expect(getDashboardFilterChanges({}, { filterTestAccounts })).toEqual([
+ { label: 'Test accounts', previousValue: [], value: [expectedValue], status: 'new' },
+ ])
+ })
+
+ it('lists a switch from excluded to included test accounts', () => {
+ expect(getDashboardFilterChanges({ filterTestAccounts: true }, { filterTestAccounts: false })).toEqual([
+ { label: 'Test accounts', previousValue: ['Excluded'], value: ['Included'], status: 'changed' },
+ ])
+ })
+
+ it('names the taxonomy of a breakdown so a switch between two of them reads as a change', () => {
+ expect(
+ getDashboardFilterChanges(
+ { breakdown_filter: { breakdown: '$browser', breakdown_type: 'event' } },
+ { breakdown_filter: { breakdown: '$browser', breakdown_type: 'person' } }
+ )
+ ).toEqual([
+ {
+ label: 'Breakdown by',
+ previousValue: ['$browser (event property)'],
+ value: ['$browser (person property)'],
+ status: 'changed',
+ },
+ ])
+ })
+
+ it('names the taxonomy of each breakdown in a multiple breakdown', () => {
+ expect(
+ getDashboardFilterChanges(
+ {},
+ {
+ breakdown_filter: {
+ breakdowns: [
+ { property: '$browser', type: 'event' },
+ { property: '$geoip_country_code', type: 'person' },
+ ],
+ },
+ }
+ )
+ ).toEqual([
+ {
+ label: 'Breakdown by',
+ previousValue: [],
+ value: ['$browser (event property)', '$geoip_country_code (person property)'],
+ status: 'new',
+ },
+ ])
+ })
+
+ it('lists an explicit property-filter clear', () => {
+ expect(getDashboardFilterChanges({}, { properties: [] })).toEqual([
+ { label: 'Property filters', previousValue: [], value: ['No property filters'], status: 'new' },
+ ])
+ })
+})
+
+describe('dashboardFiltersEqual', () => {
+ it.each([
+ ['a null interval against an absent one', {}, { interval: null }],
+ ['a null test account override against an absent one', {}, { filterTestAccounts: null }],
+ ['a null end date against an absent one', { date_from: '-7d' }, { date_from: '-7d', date_to: null }],
+ ])('treats %s as unchanged', (_name, saved, current) => {
+ expect(dashboardFiltersEqual(saved, current)).toBe(true)
+ })
+
+ it('treats a reordered property list as unchanged, so the change list matches', () => {
+ const browser: AnyPropertyFilter = {
+ key: 'browser',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'Chrome',
+ }
+ const os: AnyPropertyFilter = {
+ key: 'os',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: 'macOS',
+ }
+
+ expect(dashboardFiltersEqual({ properties: [browser, os] }, { properties: [os, browser] })).toBe(true)
+ expect(getDashboardFilterChanges({ properties: [browser, os] }, { properties: [os, browser] })).toEqual([])
+ })
+
+ it.each([
+ ['a forced interval', {}, { interval: 'week' as const }],
+ ['a forced test account override', {}, { filterTestAccounts: false }],
+ ['a cleared property list', {}, { properties: [] }],
+ ])('treats %s as changed', (_name, saved, current) => {
+ expect(dashboardFiltersEqual(saved, current)).toBe(false)
+ })
+})
+
+describe('getDashboardVariableChanges', () => {
+ const variable = (variableId: string, value: string | null, isNull = false): HogQLVariable => ({
+ code_name: variableId,
+ variableId,
+ value,
+ isNull,
+ })
+
+ it('lists each SQL variable change against its saved or default value', () => {
+ expect(
+ getDashboardVariableChanges(
+ { saved: variable('saved', 'before') },
+ {
+ saved: variable('saved', 'after'),
+ first: variable('first', 'one'),
+ second: variable('second', 'two'),
+ },
+ {
+ first: variable('first', 'default one'),
+ second: variable('second', 'default two'),
+ }
+ )
+ ).toEqual([
+ { label: 'saved', previousValue: ['before'], value: ['after'], status: 'changed' },
+ { label: 'first', previousValue: ['default one'], value: ['one'], status: 'changed' },
+ { label: 'second', previousValue: ['default two'], value: ['two'], status: 'changed' },
+ ])
+ })
+
+ it('treats an omitted isNull value as false', () => {
+ expect(dashboardVariableValuesEqual({ value: 'value' }, { value: 'value', isNull: false })).toBe(true)
+ expect(
+ getDashboardVariableChanges(
+ { variable: { code_name: 'variable', variableId: 'variable', value: 'value' } },
+ { variable: variable('variable', 'value') },
+ {}
+ )
+ ).toEqual([])
+ })
+
+ it('reports SQL null as a distinct variable value', () => {
+ expect(dashboardVariableValuesEqual({ value: null, isNull: true }, { value: null, isNull: false })).toBe(false)
+ expect(
+ getDashboardVariableChanges(
+ { variable: variable('variable', null) },
+ { variable: variable('variable', null, true) },
+ {}
+ )
+ ).toEqual([{ label: 'variable', previousValue: [], value: ['null'], status: 'changed' }])
+ })
+
+ it('reports removing a saved variable override when its default differs', () => {
+ expect(
+ getDashboardVariableChanges(
+ { variable: variable('variable', 'saved override') },
+ {},
+ { variable: variable('variable', 'default value') }
+ )
+ ).toEqual([
+ { label: 'variable', previousValue: ['saved override'], value: ['default value'], status: 'changed' },
+ ])
+ })
+})
diff --git a/products/dashboards/frontend/dashboardSettings/dashboardChanges.ts b/products/dashboards/frontend/dashboardSettings/dashboardChanges.ts
new file mode 100644
index 000000000000..962451109aa2
--- /dev/null
+++ b/products/dashboards/frontend/dashboardSettings/dashboardChanges.ts
@@ -0,0 +1,314 @@
+import { deepEqual as equal } from 'fast-equals'
+
+import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'
+import { dateFilterToText } from 'lib/utils/dateFilters'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
+
+import type { DashboardFilter, HogQLVariable, MultipleBreakdownType } from '~/queries/schema/schema-general'
+import { type AnyPropertyFilter, type BreakdownType, PropertyFilterType } from '~/types'
+
+export interface DashboardSettingsChange {
+ label: string
+ previousValue: string[]
+ value: string[]
+ status: 'new' | 'changed' | 'removed'
+}
+
+export type DashboardFilterChange = DashboardSettingsChange
+
+function formatVariableValue(variable: { isNull?: boolean; value?: unknown } | undefined): string[] {
+ if (variable?.isNull) {
+ // SQL NULL is an explicit value in the changes UI. An empty array represents an unset variable.
+ return ['null']
+ }
+ if (variable?.value == null) {
+ return []
+ }
+ return [String(variable.value)]
+}
+
+export function dashboardVariableValuesEqual(
+ previous: { isNull?: boolean; value?: unknown } | undefined,
+ current: { isNull?: boolean; value?: unknown } | undefined
+): boolean {
+ return equal(formatVariableValue(previous), formatVariableValue(current))
+}
+
+/**
+ * Deep equality that reads null and an absent key as the same setting. Both mean "inherit" for a
+ * dashboard filter, and the inherit option on each control writes null rather than dropping the key.
+ */
+function dashboardFilterValuesEqual(previous: unknown, current: unknown): boolean {
+ if (previous == null && current == null) {
+ return true
+ }
+ return equal(previous, current)
+}
+
+export function dashboardFiltersEqual(previous: DashboardFilter, current: DashboardFilter): boolean {
+ // Property filters are compared with the same rule that builds the change list, so the unsaved
+ // count can never disagree with what the change list can show. A reordered AND list holds the
+ // same filters, so it is not a change.
+ if (getPropertyFilterChanges(previous, current).length > 0) {
+ return false
+ }
+
+ const keys = new Set([...Object.keys(previous), ...Object.keys(current)])
+ return Array.from(keys).every(
+ (key) =>
+ key === 'properties' ||
+ dashboardFilterValuesEqual(
+ (previous as Record<string, unknown>)[key],
+ (current as Record<string, unknown>)[key]
+ )
+ )
+}
+
+function changeValue(value: string | undefined): string[] {
+ return value ? [value] : []
+}
+
+export function getDashboardVariableChanges(
+ previousVariables: Record<string, HogQLVariable>,
+ currentVariables: Record<string, HogQLVariable>,
+ defaultVariables: Record<string, HogQLVariable>
+): DashboardSettingsChange[] {
+ const variableIds = new Set([...Object.keys(previousVariables), ...Object.keys(currentVariables)])
+
+ return Array.from(variableIds).flatMap((variableId) => {
+ const previous = previousVariables[variableId] ?? defaultVariables[variableId]
+ const current = currentVariables[variableId] ?? defaultVariables[variableId]
+ if (dashboardVariableValuesEqual(previous, current)) {
+ return []
+ }
+
+ return [
+ {
+ label: current?.code_name ?? previous?.code_name ?? variableId,
+ previousValue: formatVariableValue(previous),
+ value: formatVariableValue(current),
+ status: getChangeStatus(!!previous, !!current),
+ },
+ ]
+ })
+}
+
+const DASHBOARD_FILTER_TYPE_LABELS: Partial<Record<string, string>> = {
+ [PropertyFilterType.Cohort]: 'cohort',
+ [PropertyFilterType.DataWarehouse]: 'data warehouse property',
+ [PropertyFilterType.DataWarehousePersonProperty]: 'data warehouse person property',
+ [PropertyFilterType.Element]: 'element',
+ [PropertyFilterType.Event]: 'event property',
+ [PropertyFilterType.EventMetadata]: 'event metadata',
+ [PropertyFilterType.Feature]: 'feature flag',
+ [PropertyFilterType.Group]: 'group property',
+ [PropertyFilterType.HogQL]: 'SQL expression',
+ [PropertyFilterType.Person]: 'person property',
+ [PropertyFilterType.RevenueAnalytics]: 'revenue analytics property',
+ [PropertyFilterType.Session]: 'session property',
+}
+
+// The same property name exists in several taxonomies, and the formatted label carries only the
+// name, the operator, and the value. Without the taxonomy, moving a filter from one to the other
+// reads as the same filter removed and added again.
+function formatProperty(property: AnyPropertyFilter): string {
+ const label = formatPropertyLabel(property, {}).trim()
+ const taxonomy = property.type ? DASHBOARD_FILTER_TYPE_LABELS[property.type] : undefined
+ return taxonomy ? `${label} (${taxonomy})` : label
+}
+
+function propertyIdentity(property: AnyPropertyFilter): string {
+ if (!('key' in property)) {
+ return JSON.stringify(property)
+ }
+
+ return JSON.stringify({
+ key: property.key,
+ type: property.type,
+ group_type_index: 'group_type_index' in property ? property.group_type_index : undefined,
+ })
+}
+
+function formatDateRange(filters: DashboardFilter): string {
+ const dateRange = dateFilterToText(filters.date_from, filters.date_to, 'All time') || 'All time'
+ // explicitDate moves the period boundaries to the current time, so a flip of the "Exact time
+ // range" switch alone has to read as a change rather than as the same range twice.
+ return filters.explicitDate ? `${dateRange} (exact time range)` : dateRange
+}
+
+// The same property name exists in several taxonomies, so a breakdown that keeps the name and
+// changes the taxonomy would otherwise read as the same value on both sides of the change.
+function formatBreakdownValue(
+ property: unknown,
+ type: BreakdownType | MultipleBreakdownType | null | undefined
+): string {
+ const name = String(property)
+ const label = type ? DASHBOARD_FILTER_TYPE_LABELS[type] : undefined
+ return label ? `${name} (${label})` : name
+}
+
+function formatBreakdown(filters: DashboardFilter): string[] {
+ const { breakdown_filter } = filters
+ if (!breakdown_filter?.breakdown && !breakdown_filter?.breakdowns?.length) {
+ return []
+ }
+
+ if (breakdown_filter.breakdowns?.length) {
+ return breakdown_filter.breakdowns.map((breakdown) => formatBreakdownValue(breakdown.property, breakdown.type))
+ }
+
+ if (Array.isArray(breakdown_filter.breakdown)) {
+ return breakdown_filter.breakdown.map((breakdown) =>
+ formatBreakdownValue(breakdown, breakdown_filter.breakdown_type)
+ )
+ }
+ return [formatBreakdownValue(breakdown_filter.breakdown, breakdown_filter.breakdown_type)]
+}
+
+function formatTestAccounts(filterTestAccounts: DashboardFilter['filterTestAccounts']): string {
+ if (filterTestAccounts === null || filterTestAccounts === undefined) {
+ return 'Default'
+ }
+ // A true filterTestAccounts filters internal and test users out.
+ return filterTestAccounts ? 'Excluded' : 'Included'
+}
+
+function getChangeStatus(previousExists: boolean, currentExists: boolean): DashboardFilterChange['status'] {
+ if (!previousExists) {
+ return 'new'
+ }
+ if (!currentExists) {
+ return 'removed'
+ }
+ return 'changed'
+}
+
+function getPropertyChanges(previous: AnyPropertyFilter[], current: AnyPropertyFilter[]): DashboardFilterChange[] {
+ const unmatchedPrevious = [...previous]
+ const changes: DashboardFilterChange[] = []
+
+ current.forEach((property) => {
+ const previousIndex = unmatchedPrevious.findIndex(
+ (previousProperty) => propertyIdentity(previousProperty) === propertyIdentity(property)
+ )
+
+ if (previousIndex === -1) {
+ changes.push({
+ label: 'Property filter',
+ previousValue: [],
+ value: [formatProperty(property)],
+ status: 'new',
+ })
+ return
+ }
+
+ const previousProperty = unmatchedPrevious.splice(previousIndex, 1)[0]
+ if (!equal(previousProperty, property)) {
+ changes.push({
+ label: 'Property filter',
+ previousValue: [formatProperty(previousProperty)],
+ value: [formatProperty(property)],
+ status: 'changed',
+ })
+ }
+ })
+
+ unmatchedPrevious.forEach((property) => {
+ changes.push({
+ label: 'Property filter',
+ previousValue: [formatProperty(property)],
+ value: [],
+ status: 'removed',
+ })
+ })
+
+ return changes
+}
+
+function getPropertyFilterChanges(
+ previousFilters: DashboardFilter,
+ currentFilters: DashboardFilter
+): DashboardFilterChange[] {
+ const previousProperties = previousFilters.properties ?? []
+ const currentProperties = currentFilters.properties ?? []
+ const changes = getPropertyChanges(previousProperties, currentProperties)
+ const previousPropertiesAreExplicit = previousFilters.properties != null
+ const currentPropertiesAreExplicit = currentFilters.properties != null
+ if (
+ !changes.length &&
+ previousPropertiesAreExplicit !== currentPropertiesAreExplicit &&
+ (previousProperties.length === 0 || currentProperties.length === 0)
+ ) {
+ changes.push({
+ label: 'Property filters',
+ previousValue: previousPropertiesAreExplicit ? ['No property filters'] : [],
+ value: currentPropertiesAreExplicit ? ['No property filters'] : [],
+ status: getChangeStatus(previousPropertiesAreExplicit, currentPropertiesAreExplicit),
+ })
+ }
+
+ return changes
+}
+
+export function getDashboardFilterChanges(
+ previousFilters: DashboardFilter,
+ currentFilters: DashboardFilter
+): DashboardFilterChange[] {
+ const changes = getPropertyFilterChanges(previousFilters, currentFilters)
+ const previousHasDate = !!previousFilters.date_from || !!previousFilters.date_to || !!previousFilters.explicitDate
+ const currentHasDate = !!currentFilters.date_from || !!currentFilters.date_to || !!currentFilters.explicitDate
+
+ if (
+ !dashboardFilterValuesEqual(previousFilters.date_from, currentFilters.date_from) ||
+ !dashboardFilterValuesEqual(previousFilters.date_to, currentFilters.date_to) ||
+ !dashboardFilterValuesEqual(previousFilters.explicitDate, currentFilters.explicitDate)
+ ) {
+ changes.push({
+ label: 'Date range',
+ previousValue: previousHasDate ? [formatDateRange(previousFilters)] : [],
+ value: currentHasDate ? [formatDateRange(currentFilters)] : [],
+ status: getChangeStatus(previousHasDate, currentHasDate),
+ })
+ }
+
+ if (!dashboardFilterValuesEqual(previousFilters.interval, currentFilters.interval)) {
+ changes.push({
+ label: 'Grouped by',
+ previousValue: changeValue(
+ previousFilters.interval ? capitalizeFirstLetter(previousFilters.interval) : undefined
+ ),
+ value: changeValue(currentFilters.interval ? capitalizeFirstLetter(currentFilters.interval) : undefined),
+ status: getChangeStatus(!!previousFilters.interval, !!currentFilters.interval),
+ })
+ }
+
+ if (!dashboardFilterValuesEqual(previousFilters.breakdown_filter, currentFilters.breakdown_filter)) {
+ const previousHasBreakdown =
+ !!previousFilters.breakdown_filter?.breakdown || !!previousFilters.breakdown_filter?.breakdowns?.length
+ const currentHasBreakdown =
+ !!currentFilters.breakdown_filter?.breakdown || !!currentFilters.breakdown_filter?.breakdowns?.length
+ changes.push({
+ label: 'Breakdown by',
+ previousValue: previousHasBreakdown ? formatBreakdown(previousFilters) : [],
+ value: currentHasBreakdown ? formatBreakdown(currentFilters) : [],
+ status: getChangeStatus(previousHasBreakdown, currentHasBreakdown),
+ })
+ }
+
+ if (!dashboardFilterValuesEqual(previousFilters.filterTestAccounts, currentFilters.filterTestAccounts)) {
+ const previousHasTestAccountSetting =
+ previousFilters.filterTestAccounts !== null && previousFilters.filterTestAccounts !== undefined
+ const currentHasTestAccountSetting =
+ currentFilters.filterTestAccounts !== null && currentFilters.filterTestAccounts !== undefined
+ changes.push({
+ label: 'Test accounts',
+ previousValue: previousHasTestAccountSetting
+ ? [formatTestAccounts(previousFilters.filterTestAccounts)]
+ : [],
+ value: currentHasTestAccountSetting ? [formatTestAccounts(currentFilters.filterTestAccounts)] : [],
+ status: getChangeStatus(previousHasTestAccountSetting, currentHasTestAccountSetting),
+ })
+ }
+
+ return changes
+}