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.

fix(metrics): open the new-dashboard dialog from the viewer's picker (#88565)

Daniel Viscae4558f35c403
diff --git a/products/metrics/frontend/components/MetricStatPanel.tsx b/products/metrics/frontend/components/MetricStatPanel.tsx
deleted file mode 100644
index 6902ddb5c06a..000000000000
--- a/products/metrics/frontend/components/MetricStatPanel.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { LemonTag, Tooltip } from '@posthog/lemon-ui'
-import { MetricCard, useChartTheme } from '@posthog/quill-charts'
-
-import {
- computeMetricSummary,
- computeMetricSummaryChange,
- getMetricChangeTooltip,
- type MetricSummary,
- METRIC_SUMMARY_LABELS,
-} from 'lib/components/Metric/metricSummary'
-import { dayjs } from 'lib/dayjs'
-import { humanFriendlyNumber } from 'lib/utils/numbers'
-
-import { MetricAggregation, MetricsAnomalyBadge } from './metricsViewerLogic'
-
-export interface MetricStatPanelProps {
- /** Headline title — the metric name. */
- title: string
- /** How the series is summarized into one value. */
- summary: MetricSummary
- /** The bucket aggregation, shown in the subtitle for context. */
- aggregation: MetricAggregation
- /** Grand total across buckets (basis for the 'total' summary). */
- total: number
- /** Per-bucket values the summary and sparkline are computed from. */
- values: number[]
- /** Pre-formatted bucket labels for the sparkline hover. */
- labels: string[]
- /** "vs baseline" anomaly badge, or null when the metric is flat / not characterized. */
- anomaly: MetricsAnomalyBadge | null
-}
-
-/** A Grafana-style "stat" panel: one headline value + change pill + sparkline, with an optional anomaly badge. */
-export function MetricStatPanel({
- title,
- summary,
- aggregation,
- total,
- values,
- labels,
- anomaly,
-}: MetricStatPanelProps): JSX.Element {
- const theme = useChartTheme()
- return (
- <div className="flex flex-col h-full">
- {anomaly && (
- <div className="flex justify-end">
- <Tooltip
- title={`Baseline ${humanFriendlyNumber(anomaly.baselineMean)} → recent ${humanFriendlyNumber(
- anomaly.anomalyMean
- )}${anomaly.onsetTime ? `, onset ${dayjs(anomaly.onsetTime).format('D MMM HH:mm')}` : ''}`}
- >
- <LemonTag type="warning">
- {anomaly.direction === 'up' ? '▲' : '▼'} {anomaly.percent}% vs baseline
- </LemonTag>
- </Tooltip>
- </div>
- )}
- <MetricCard
- className="flex-1"
- title={title}
- restingSubtitle={`${METRIC_SUMMARY_LABELS[summary]} · ${aggregation}`}
- value={computeMetricSummary(summary, total, values)}
- change={computeMetricSummaryChange(summary, { total, data: values }, undefined)}
- changeTooltip={getMetricChangeTooltip(summary, false, null)}
- changeSize="md"
- changeInline
- hoverChangeFromPreviousPoint
- data={values}
- labels={labels}
- theme={theme}
- sparklineFill
- sparklineHeight={140}
- formatValue={(value) => humanFriendlyNumber(value)}
- dataAttr="metrics-stat-value"
- />
- </div>
- )
-}
diff --git a/products/metrics/frontend/components/MetricsViewer.test.tsx b/products/metrics/frontend/components/MetricsViewer.test.tsx
new file mode 100644
index 000000000000..8ef47d855b53
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsViewer.test.tsx
@@ -0,0 +1,90 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { insightsApi } from 'scenes/insights/utils/api'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import {
+ AccessControlLevel,
+ AccessControlResourceType,
+ AppContext,
+ InsightShortId,
+ QueryBasedInsightModel,
+} from '~/types'
+
+import {
+ metricsAttributesRetrieve,
+ metricsQueryCreate,
+ metricsValuesRetrieve,
+} from 'products/metrics/frontend/generated/api'
+
+import { MetricsViewer } from './MetricsViewer'
+import { metricsViewerLogic } from './metricsViewerLogic'
+
+jest.mock('products/metrics/frontend/generated/api', () => ({
+ ...jest.requireActual('products/metrics/frontend/generated/api'),
+ metricsValuesRetrieve: jest.fn(),
+ metricsQueryCreate: jest.fn(),
+ metricsSamplesCreate: jest.fn(),
+ metricsAttributesRetrieve: jest.fn(),
+ metricsCharacterizeCreate: jest.fn(),
+}))
+jest.mock('scenes/insights/utils/api', () => ({
+ insightsApi: { create: jest.fn(), update: jest.fn() },
+}))
+
+// What the viewer reads off a freshly saved insight: `short_id` keys the insight logic the
+// picker binds to, and `id` is what a dashboard write would patch. Typed as a Partial — the
+// shape `insightsApi.create` accepts — so these two fields are checked without padding the
+// fixture with the rest of the model, which this flow never touches.
+const SAVED_INSIGHT: Partial<QueryBasedInsightModel> = { id: 7, short_id: 'insight7' as InsightShortId }
+
+describe('MetricsViewer', () => {
+ let logic: ReturnType<typeof metricsViewerLogic.build>
+
+ beforeEach(() => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ resource_access_control: {
+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
+ [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
+ [AccessControlResourceType.Insight]: AccessControlLevel.Editor,
+ },
+ } as AppContext
+ useMocks({ get: { '/api/environments/:team_id/dashboards/': { count: 0, results: [] } } })
+ initKeaTests()
+ jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: [] })
+ jest.mocked(metricsQueryCreate).mockResolvedValue({ results: [] })
+ jest.mocked(metricsAttributesRetrieve).mockResolvedValue({ results: [], count: 0 })
+ jest.mocked(insightsApi.create).mockResolvedValue(SAVED_INSIGHT as QueryBasedInsightModel)
+ logic = metricsViewerLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic?.unmount()
+ })
+
+ // "Add to dashboard" saves the query as an insight, then hands off to the shared dashboard
+ // picker. That picker's "Add to a new dashboard" does nothing unless the create-dashboard
+ // dialog is rendered alongside it, which is easy to leave out of a scene.
+ it('opens the create-dashboard dialog from the dashboard picker', async () => {
+ logic.actions.setMetricName('http.server.duration')
+
+ render(
+ <Provider>
+ <MetricsViewer />
+ </Provider>
+ )
+
+ fireEvent.click(screen.getByText('Add to dashboard'))
+
+ fireEvent.click(await screen.findByText('Add to a new dashboard'))
+
+ expect(await screen.findByText('Create a dashboard')).toBeInTheDocument()
+ })
+})
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index 6520c4b0c8ff..32e35ea6bced 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -8,16 +8,16 @@ import {
LemonBanner,
LemonDropdown,
LemonInputSelect,
- LemonSegmentedButton,
LemonSelect,
LemonSwitch,
+ LemonTag,
SpinnerOverlay,
+ Tooltip,
} from '@posthog/lemon-ui'
import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboardModal'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
-import { type MetricSummary } from 'lib/components/Metric/metricSummary'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'
import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'
@@ -26,6 +26,8 @@ import { dayjs } from 'lib/dayjs'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'
import {
AccessControlLevel,
@@ -47,29 +49,16 @@ import { MetricsSamplesPanel } from './MetricsSamplesPanel'
import { MetricsSeriesChart } from './MetricsSeriesChart'
import { metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'
import { MetricsStarterDashboardModal } from './MetricsStarterDashboardModal'
-import { MetricStatPanel } from './MetricStatPanel'
import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'
import {
LIVE_REFRESH_MS,
METRIC_FILTER_OPERATOR_ALLOWLIST,
MetricAggregation,
+ MetricsAnomalyBadge,
metricsViewerLogic,
- MetricsViewMode,
RECOMMENDED_AGGREGATION_BY_TYPE,
} from './metricsViewerLogic'
-const VIEW_MODE_OPTIONS: { value: MetricsViewMode; label: string; 'data-attr': string }[] = [
- { value: 'chart', label: 'Chart', 'data-attr': 'metrics-viewer-view-mode-chart' },
- { value: 'stat', label: 'Stat', 'data-attr': 'metrics-viewer-view-mode-stat' },
-]
-
-// How the stat card summarizes the series into one headline value.
-const SUMMARY_OPTIONS: { value: MetricSummary; label: string }[] = [
- { value: 'latest', label: 'Latest' },
- { value: 'average', label: 'Average' },
- { value: 'total', label: 'Total' },
-]
-
const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [
{ value: 'sum', label: 'Sum' },
{ value: 'avg', label: 'Average' },
@@ -114,10 +103,6 @@ const DATE_OPTIONS: DateMappingOption[] = [
},
]
-function renderLabel(label: string): string {
- return dayjs(label).format('D MMM YYYY HH:mm:ss')
-}
-
export const MetricsViewer = (): JSX.Element => {
const logic = metricsViewerLogic()
// Keep the picker logic mounted alongside the viewer so the chosen metric's
@@ -132,15 +117,10 @@ export const MetricsViewer = (): JSX.Element => {
aggregation,
dateFrom,
dateTo,
- viewMode,
- statSummary,
groupByKeys,
filterGroup,
attributeEndpointFilters,
chartSeries,
- sparklineValues,
- sparklineLabels,
- statTotal,
anomalyBadge,
liveRefresh,
queryResultsLoading,
@@ -149,14 +129,13 @@ export const MetricsViewer = (): JSX.Element => {
savedInsight,
isAddToDashboardModalOpen,
hasMetricName,
+ hasResults,
} = useValues(logic)
const {
setMetricName,
setAggregation,
setDateFrom,
setDateTo,
- setViewMode,
- setStatSummary,
setFilterGroup,
setLiveRefresh,
fetchQueryResults,
@@ -207,14 +186,15 @@ export const MetricsViewer = (): JSX.Element => {
fetchQueryResults({})
}, [metricName, aggregation, dateFrom, dateTo, groupByKeys, filterGroup]) // eslint-disable-line react-hooks/exhaustive-deps
- // Characterize the recent window only while the stat card is visible — the badge is stat-mode only.
+ // Characterize the recent window against the rest, so the chart carries a "vs baseline"
+ // badge without the user having to eyeball the shape.
useEffect(() => {
- if (viewMode === 'stat' && hasMetricName) {
+ if (hasMetricName) {
fetchAnomaly({})
} else {
clearAnomaly()
}
- }, [metricName, aggregation, dateFrom, dateTo, viewMode, hasMetricName, filterGroup]) // eslint-disable-line react-hooks/exhaustive-deps
+ }, [metricName, aggregation, dateFrom, dateTo, hasMetricName, filterGroup]) // eslint-disable-line react-hooks/exhaustive-deps
const selectedMetricType = useMemo(
() => pickerItems.find((item) => item.name === metricName)?.metric_type,
@@ -222,8 +202,6 @@ export const MetricsViewer = (): JSX.Element => {
)
const recommendedAggregation = selectedMetricType ? RECOMMENDED_AGGREGATION_BY_TYPE[selectedMetricType] : undefined
- const hasResults = sparklineValues.length > 0
-
return (
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-2">
@@ -284,16 +262,9 @@ export const MetricsViewer = (): JSX.Element => {
/>
</div>
</div>
- {/* Aggregation, grouping, and view controls sit below the filter bar. */}
+ {/* Aggregation and grouping controls sit below the filter bar. */}
<div className="flex flex-wrap items-center gap-2 justify-between">
<div className="flex flex-wrap items-center gap-2">
- <LemonSegmentedButton
- size="small"
- value={viewMode}
- options={VIEW_MODE_OPTIONS}
- onChange={(value) => setViewMode(value)}
- disabledReason={metricsViewerDisabledReason ?? undefined}
- />
<LemonSelect
size="small"
value={aggregation}
@@ -303,16 +274,7 @@ export const MetricsViewer = (): JSX.Element => {
disabledReason={metricsViewerDisabledReason}
/>
<MetricsGroupByButton disabledReason={metricsViewerDisabledReason} />
- {viewMode === 'stat' && (
- <LemonSelect
- size="small"
- value={statSummary}
- options={SUMMARY_OPTIONS}
- onChange={(value) => setStatSummary(value)}
- data-attr="metrics-viewer-stat-summary"
- disabledReason={metricsViewerDisabledReason}
- />
- )}
+ {anomalyBadge && <MetricsAnomalyTag anomaly={anomalyBadge} />}
</div>
<div className="flex flex-wrap items-center gap-2">
<LemonButton
@@ -344,6 +306,7 @@ export const MetricsViewer = (): JSX.Element => {
onClick={openStarterDashboardModal}
tooltip="Create a dashboard with one insight per metric, using each metric's recommended aggregation"
data-attr="metrics-viewer-starter-dashboard"
+ disabledReason={insightEditorDisabledReason}
>
New service dashboard
</LemonButton>
@@ -352,13 +315,18 @@ export const MetricsViewer = (): JSX.Element => {
</div>
<MetricsStarterDashboardModal />
{savedInsight && (
- <AddToDashboardModal
- isOpen={isAddToDashboardModalOpen}
- closeModal={closeAddToDashboardModal}
- insightProps={{ dashboardItemId: savedInsight.short_id, cachedInsight: savedInsight }}
- canEditInsight={!insightEditorDisabledReason}
- data-attr="metrics-viewer-add-to-dashboard-modal"
- />
+ <>
+ <AddToDashboardModal
+ isOpen={isAddToDashboardModalOpen}
+ closeModal={closeAddToDashboardModal}
+ insightProps={{ dashboardItemId: savedInsight.short_id, cachedInsight: savedInsight }}
+ canEditInsight={!insightEditorDisabledReason}
+ data-attr="metrics-viewer-add-to-dashboard-modal"
+ />
+ {/* The picker's "Add to a new dashboard" only opens this dialog, so the two
+ have to be rendered together (as the insight scene does). */}
+ <NewDashboardModal />
+ </>
)}
<div className="flex flex-col xl:flex-row gap-3 items-stretch">
<div className="flex-1 min-w-0">
@@ -373,16 +341,6 @@ export const MetricsViewer = (): JSX.Element => {
{queryError}
</LemonBanner>
</div>
- ) : hasResults && viewMode === 'stat' ? (
- <MetricStatPanel
- title={metricName}
- summary={statSummary}
- aggregation={aggregation}
- total={statTotal}
- values={sparklineValues}
- labels={sparklineLabels.map(renderLabel)}
- anomaly={anomalyBadge}
- />
) : hasResults ? (
<MetricsSeriesChart
series={chartSeries}
@@ -397,7 +355,7 @@ export const MetricsViewer = (): JSX.Element => {
{queryResultsLoading && <SpinnerOverlay />}
</div>
</div>
- {viewMode === 'chart' && hasMetricName && (
+ {hasMetricName && (
<div className="xl:w-[26rem] shrink-0 xl:max-h-[360px] flex flex-col">
<MetricsSamplesPanel />
</div>
@@ -407,6 +365,20 @@ export const MetricsViewer = (): JSX.Element => {
)
}
+// How the recent slice of the window compares against the rest of it, sitting next to the
+// controls that define the window rather than over the chart, where it would fight the legend.
+const MetricsAnomalyTag = ({ anomaly }: { anomaly: MetricsAnomalyBadge }): JSX.Element => (
+ <Tooltip
+ title={`Baseline ${humanFriendlyNumber(anomaly.baselineMean)} → recent ${humanFriendlyNumber(
+ anomaly.anomalyMean
+ )}${anomaly.onsetTime ? `, onset ${dayjs(anomaly.onsetTime).format('D MMM HH:mm')}` : ''}`}
+ >
+ <LemonTag type="warning" data-attr="metrics-viewer-anomaly-badge">
+ {anomaly.direction === 'up' ? '▲' : '▼'} {anomaly.percent}% vs baseline
+ </LemonTag>
+ </Tooltip>
+)
+
// Filter chips + "Add filter" button, mirroring the logs viewer's applied-filters row: picking an
// attribute opens the chip for value selection, with suggestions fed by the metrics attribute endpoints.
const MetricsViewerFilterBar = ({ disabledReason }: { disabledReason: string | null }): JSX.Element => {
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.test.ts b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
index df841e62ac35..2573b8a568a1 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.test.ts
+++ b/products/metrics/frontend/components/metricsSamplesLogic.test.ts
@@ -205,18 +205,12 @@ describe('metricsSamplesLogic', () => {
})
// Regression: the chart's exemplar overlay starves (never fetches samples)
- // unless the samples tab happens to be open — a chart redraw must refresh
- // them in chart mode, and must not fire needless requests in stat mode.
- it('refreshes samples on chart query success only in chart mode', async () => {
+ // unless the samples tab happens to be open — a chart redraw must refresh them.
+ it('refreshes samples on chart query success', async () => {
metricsViewerLogic.actions.setMetricName('demo_checkout_duration_ms')
metricsViewerLogic.actions.fetchQueryResultsSuccess([])
await expectLogic(logic).toDispatchActions(['loadSamplesSuccess'])
expect(mockSamplesCreate).toHaveBeenCalledTimes(1)
-
- metricsViewerLogic.actions.setViewMode('stat')
- metricsViewerLogic.actions.fetchQueryResultsSuccess([])
- await expectLogic(logic).delay(10)
- expect(mockSamplesCreate).toHaveBeenCalledTimes(1)
})
})
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.tsx b/products/metrics/frontend/components/metricsSamplesLogic.tsx
index 6309f52190d8..127b98d27ef9 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.tsx
+++ b/products/metrics/frontend/components/metricsSamplesLogic.tsx
@@ -14,7 +14,7 @@ import type {
import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'
import { formatSeriesName, seriesColor } from './metricsSeries'
-import { type MetricsViewMode, type MetricsViewerSeries, metricsViewerLogic, resolveDate } from './metricsViewerLogic'
+import { type MetricsViewerSeries, metricsViewerLogic, resolveDate } from './metricsViewerLogic'
// The side panel next to the chart: per-series aggregates, or the raw emissions
// behind the chart with their trace linkage (the metric->trace pivot).
@@ -47,7 +47,6 @@ export interface metricsSamplesLogicValues {
queryFilters: _MetricFilterApi[] // metricsViewerLogic
queryResults: MetricsViewerSeries[] // metricsViewerLogic
selectedMetricType: OtelMetricTypeEnumApi | null // metricsViewerLogic
- viewMode: MetricsViewMode // metricsViewerLogic
currentTeamId: number | null // teamLogic
activeTab: MetricsPanelTab
aggregateRows: MetricsAggregateRow[]
@@ -125,7 +124,7 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
teamLogic,
['currentTeamId'],
metricsViewerLogic,
- ['metricName', 'dateFrom', 'dateTo', 'queryFilters', 'selectedMetricType', 'queryResults', 'viewMode'],
+ ['metricName', 'dateFrom', 'dateTo', 'queryFilters', 'selectedMetricType', 'queryResults'],
],
actions: [
metricsViewerLogic,
@@ -223,11 +222,9 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
}
},
// The chart's exemplar overlay renders from these samples, so every chart
- // redraw refreshes them; stat mode has no chart to dot, so skip it there.
+ // redraw refreshes them.
fetchQueryResultsSuccess: () => {
- if (values.viewMode === 'chart') {
- actions.loadSamples({})
- }
+ actions.loadSamples({})
},
setMetricName: reloadWhenShown,
setDateFrom: reloadWhenShown,
diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
index f0eeeb73d846..cbd3552c9bf2 100644
--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
@@ -92,16 +92,6 @@ describe('metricsUsageTrackingLogic', () => {
() => metricsViewerLogic.actions.setAggregation('p95'),
{ aggregation: 'p95' },
],
- [
- 'metrics viewer view mode changed',
- () => metricsViewerLogic.actions.setViewMode('stat'),
- { view_mode: 'stat' },
- ],
- [
- 'metrics viewer stat summary changed',
- () => metricsViewerLogic.actions.setStatSummary('total'),
- { stat_summary: 'total' },
- ],
['metrics viewer live toggled', () => metricsViewerLogic.actions.setLiveRefresh(true), { enabled: true }],
[
'metrics viewer date range changed',
diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
index db219704cc69..3094f472374f 100644
--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
@@ -7,7 +7,6 @@ import { type MetricsQuery, ProductIntentContext, ProductKey } from '~/queries/s
import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'
-import type { MetricSummary } from '../../../../frontend/src/lib/components/Metric/metricSummary'
import type { ProductIntentProperties } from '../../../../frontend/src/lib/utils/product-intents'
import type { Node } from '../../../../frontend/src/queries/schema/schema-general'
import type { QueryBasedInsightModel, UniversalFiltersGroup } from '../../../../frontend/src/types'
@@ -17,7 +16,7 @@ import type { MetricsSceneActiveTab } from '../metricsSceneLogic'
import { metricsSamplesLogic } from './metricsSamplesLogic'
import type { MetricsPanelTab } from './metricsSamplesLogic'
import { isUserInitiatedError, metricsViewerLogic } from './metricsViewerLogic'
-import type { MetricAggregation, MetricsViewMode } from './metricsViewerLogic'
+import type { MetricAggregation } from './metricsViewerLogic'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsUsageTrackingLogicValues {
@@ -85,12 +84,6 @@ export interface metricsUsageTrackingLogicActions {
setMetricName: (metricName: string) => {
metricName: string
} // metricsViewerLogic
- setStatSummary: (statSummary: MetricSummary) => {
- statSummary: MetricSummary
- } // metricsViewerLogic
- setViewMode: (viewMode: MetricsViewMode) => {
- viewMode: MetricsViewMode
- } // metricsViewerLogic
addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
exemplarDotClicked: (hasSpanId: boolean) => {
hasSpanId: boolean
@@ -125,8 +118,6 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
'setMetricName',
'setAggregation',
'setDateFrom',
- 'setViewMode',
- 'setStatSummary',
'setLiveRefresh',
'setGroupByKeys',
'setFilterGroup',
@@ -166,12 +157,6 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
setDateFrom: ({ dateFrom }) => {
posthog.capture('metrics viewer date range changed', { date_from: dateFrom })
},
- setViewMode: ({ viewMode }) => {
- posthog.capture('metrics viewer view mode changed', { view_mode: viewMode })
- },
- setStatSummary: ({ statSummary }) => {
- posthog.capture('metrics viewer stat summary changed', { stat_summary: statSummary })
- },
setLiveRefresh: ({ liveRefresh }) => {
posthog.capture('metrics viewer live toggled', { enabled: liveRefresh })
},
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 506ff17d430d..37c4460efb9b 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -4,7 +4,6 @@ import { router } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
-import { type MetricSummary } from 'lib/components/Metric/metricSummary'
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/constants'
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { dayjs } from 'lib/dayjs'
@@ -41,12 +40,9 @@ import type { MetricsChartSeries } from './metricsSeries'
export type MetricAggregation = 'sum' | 'avg' | 'count' | 'p95' | 'rate' | 'increase'
-// `chart` shows the time series; `stat` shows a single headline value + change pill (a Grafana "stat" panel).
-export type MetricsViewMode = 'chart' | 'stat'
-
export type MetricsViewerSeries = _MetricSeriesApi
-// Display shape for the stat card's "vs baseline" anomaly badge (null = no anomaly / flat metric).
+// Display shape for the "vs baseline" anomaly badge (null = no anomaly / flat metric).
export interface MetricsAnomalyBadge {
direction: MetricAnomalyDirectionEnumApi
percent: number
@@ -166,13 +162,13 @@ export interface metricsViewerLogicValues {
}[]
attributeKeyOptionsLoading: boolean
chartSeries: MetricsChartSeries[]
- currentSeries: MetricsViewerSeries | undefined
dateFrom: string | null
dateTo: string | null
filterGroup: UniversalFiltersGroup
groupByKeys: string[]
groupBySearch: string
hasMetricName: boolean
+ hasResults: boolean
isAddToDashboardModalOpen: boolean
lastSavedQueryNode: MetricsQuery | null
liveRefresh: boolean
@@ -187,11 +183,6 @@ export interface metricsViewerLogicValues {
savedInsight: QueryBasedInsightModel | null
savedInsightLoading: boolean
selectedMetricType: OtelMetricTypeEnumApi | null
- sparklineLabels: string[]
- sparklineValues: number[]
- statSummary: MetricSummary
- statTotal: number
- viewMode: MetricsViewMode
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -338,12 +329,6 @@ export interface metricsViewerLogicActions {
setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => {
metricType: OtelMetricTypeEnumApi | null
}
- setStatSummary: (statSummary: MetricSummary) => {
- statSummary: MetricSummary
- }
- setViewMode: (viewMode: MetricsViewMode) => {
- viewMode: MetricsViewMode
- }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -361,11 +346,8 @@ export interface metricsViewerLogicMeta {
) => MetricsQuery | null
queryFilters: (filterGroup: UniversalFiltersGroup) => _MetricFilterApi[]
attributeEndpointFilters: (dateFrom: string | null, dateTo: string | null) => Record<string, string>
- currentSeries: (queryResults: _MetricSeriesApi[]) => MetricsViewerSeries | undefined
chartSeries: (queryResults: _MetricSeriesApi[]) => MetricsChartSeries[]
- sparklineValues: (currentSeries: _MetricSeriesApi | undefined) => number[]
- sparklineLabels: (currentSeries: _MetricSeriesApi | undefined) => string[]
- statTotal: (sparklineValues: number[]) => number
+ hasResults: (queryResults: _MetricSeriesApi[]) => boolean
anomalyBadge: (anomalyReport: _MetricAnomalyReportApi | null) => MetricsAnomalyBadge | null
}
}
@@ -392,8 +374,6 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
setRecommendedAggregation: (aggregation: MetricAggregation) => ({ aggregation }),
setDateFrom: (dateFrom: string | null) => ({ dateFrom }),
setDateTo: (dateTo: string | null) => ({ dateTo }),
- setViewMode: (viewMode: MetricsViewMode) => ({ viewMode }),
- setStatSummary: (statSummary: MetricSummary) => ({ statSummary }),
setLiveRefresh: (liveRefresh: boolean) => ({ liveRefresh }),
setGroupByKeys: (groupByKeys: string[]) => ({ groupByKeys }),
setGroupBySearch: (groupBySearch: string) => ({ groupBySearch }),
@@ -430,9 +410,6 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
],
dateFrom: [DEFAULT_DATE_FROM as string | null, { setDateFrom: (_, { dateFrom }) => dateFrom }],
dateTo: [null as string | null, { setDateTo: (_, { dateTo }) => dateTo }],
- viewMode: ['chart' as MetricsViewMode, { setViewMode: (_, { viewMode }) => viewMode }],
- // 'latest' (current value) is the natural default for a live single-metric stat.
- statSummary: ['latest' as MetricSummary, { setStatSummary: (_, { statSummary }) => statSummary }],
liveRefresh: [false, { setLiveRefresh: (_, { liveRefresh }) => liveRefresh }],
// Attribute keys to split the metric into one series each (e.g. ['service.name', 'env']).
groupByKeys: [[] as string[], { setGroupByKeys: (_, { groupByKeys }) => groupByKeys }],
@@ -545,9 +522,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
cache.disposables.add(() => {
const intervalId = setInterval(() => {
actions.fetchQueryResults({})
- if (values.viewMode === 'stat') {
- actions.fetchAnomaly({})
- }
+ actions.fetchAnomaly({})
}, LIVE_REFRESH_MS)
return () => clearInterval(intervalId)
}, LIVE_REFRESH_KEY)
@@ -761,11 +736,6 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
...(resolveDate(dateTo) ? { dateTo: resolveDate(dateTo) as string } : {}),
}),
],
- // Metrics has no compare/previous-series concept, so "current" is simply the first series.
- currentSeries: [
- (s) => [s.queryResults],
- (results: MetricsViewerSeries[]): MetricsViewerSeries | undefined => results[0],
- ],
// All series rendered as chart lines (a group-by query returns one series per label combination).
// `MetricsSeriesChart` owns naming and colors; this only bridges the API's snake_case field.
chartSeries: [
@@ -777,17 +747,12 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
metricName: series.metric_name,
})),
],
- sparklineValues: [
- (s) => [s.currentSeries],
- (series: MetricsViewerSeries | undefined) => (series?.points ?? []).map((p) => p.value ?? 0),
- ],
- sparklineLabels: [
- (s) => [s.currentSeries],
- (series: MetricsViewerSeries | undefined) => (series?.points ?? []).map((p) => p.time),
+ // Whether the chart has anything to draw. A metric can return a series with no points
+ // in the selected window, which is the empty state rather than a plottable result.
+ hasResults: [
+ (s) => [s.queryResults],
+ (results: MetricsViewerSeries[]): boolean => (results[0]?.points.length ?? 0) > 0,
],
- // The stat card summarizes the per-bucket `sparklineValues` into one headline value;
- // `statTotal` is the grand total across buckets (the basis for the 'total' summary).
- statTotal: [(s) => [s.sparklineValues], (values: number[]) => values.reduce((sum, v) => sum + v, 0)],
// Display shape for the anomaly badge — null when there's no report or the metric is flat.
anomalyBadge: [
(s) => [s.anomalyReport],