: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(insights): derive chart type previews from a loaded trends result (#102753)
Sam Pennington1f9db2e1a2c9
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.tsindex 885ac3ad4e37..71870443d2fc 100644--- a/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts@@ -1,4 +1,4 @@-import type { BreakdownFilter } from '~/queries/schema/schema-general'+import type { BreakdownFilter, TrendsFilter } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'export type ChartDisplayIcon =@@ -45,6 +45,22 @@ function isCountryProperty(value: unknown): boolean {return typeof value === 'string' && COUNTRY_PROPERTIES.has(value)}+// Trends writes breakdowns as a list; older queries carry a single breakdown. Both count.+export function breakdownProperties(breakdownFilter?: BreakdownFilter | null): (string | number)[] {+ if (breakdownFilter?.breakdowns?.length) {+ return breakdownFilter.breakdowns.map((entry) => entry.property)+ }+ const single = breakdownFilter?.breakdown+ if (single == null) {+ return []+ }+ return Array.isArray(single) ? single : [single]+}++export function hasTrendsFormula(trendsFilter?: TrendsFilter | null): boolean {+ return !!trendsFilter?.formula || !!trendsFilter?.formulas?.length || !!trendsFilter?.formulaNodes?.length+}+export function getChartDisplayOptions({boxPlotMissingProperty,hasMetricInsight,@@ -54,9 +70,9 @@ export function getChartDisplayOptions({breakdown,breakdowns,}: ChartDisplayOptionEligibility): ChartDisplayOptionGroup[] {- const singleBreakdownProperty = breakdowns?.length === 1 ? breakdowns[0].property : breakdown- const hasSupportedCountryBreakdown =- (breakdowns?.length ?? 0) <= 1 && (!singleBreakdownProperty || isCountryProperty(singleBreakdownProperty))+ const breakdownProps = breakdownProperties({ breakdown, breakdowns })+ const worldMapBreakdownDisabled =+ breakdownProps.length > 1 || breakdownProps.some((property) => !isCountryProperty(property))const trendsOnlyDisabledReason = !isTrends ? 'This type is only available in Trends.' : undefinedconst singleSeriesOnlyDisabledReason = !hasSingleSeriesOutput? 'This type currently only supports insights with one series, and this insight has multiple series.'@@ -184,9 +200,9 @@ export function getChartDisplayOptions({trendsOnlyDisabledReason ||(hasTrendsFormula? "This type isn't available, because it doesn't support formulas."- : hasSupportedCountryBreakdown- ? undefined- : "This type isn't available, because there's a breakdown other than by Country Code or Country Name properties."),+ : worldMapBreakdownDisabled+ ? "This type isn't available, because there's a breakdown other than by Country Code or Country Name properties."+ : undefined),},{display: ChartDisplayType.CalendarHeatmap,diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.tsnew file mode 100644index 000000000000..6e9dff9cd055--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.ts@@ -0,0 +1,213 @@+import type { AnyResponseType, TrendsQuery } from '~/queries/schema/schema-general'+import { NodeKind } from '~/queries/schema/schema-general'+import { ChartDisplayType, CompareLabelType } from '~/types'+import type { TrendResult } from '~/types'++import { deriveChartPreview } from './chartPreviewData'+import type { ChartPreviewData } from './chartPreviewData'++function series(overrides: Partial<TrendResult> & { math?: string }): TrendResult {+ const { math = 'total', ...rest } = overrides+ return {+ action: { id: '$pageview', type: 'events', order: 0, math } as TrendResult['action'],+ label: '$pageview',+ data: [1, 2, 3, 4],+ days: ['2026-01-01', '2026-01-02', '2026-01-03', '2026-01-04'],+ labels: ['1-Jan', '2-Jan', '3-Jan', '4-Jan'],+ count: 10,+ aggregated_value: 0,+ ...rest,+ } as TrendResult+}++function query(display: ChartDisplayType, overrides: Partial<TrendsQuery> = {}): TrendsQuery {+ return {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ trendsFilter: { display },+ ...overrides,+ }+}++function response(results: unknown[], hasMore = false): AnyResponseType {+ return { results, result: results, hasMore } as AnyResponseType+}++// The preview canvas rebuilds `result` from `results`, so a derivation that only sets one key renders the wrong rows.+function results(preview: ChartPreviewData | null): TrendResult[] {+ const { results, result } = preview!.response as { results: TrendResult[]; result: TrendResult[] }+ expect(result).toBe(results)+ return results+}++describe('deriveChartPreview', () => {+ it.each([+ ['cumulative', ChartDisplayType.ActionsLineGraphCumulative, [1, 3, 6, 10], 10],+ ['slope', ChartDisplayType.SlopeGraph, [1, 4], 10],+ ])('derives the %s series exactly from the loaded time series', (_, display, data, count) => {+ const preview = deriveChartPreview(display, query(ChartDisplayType.ActionsLineGraph), response([series({})]))+ expect(preview?.sample).toBe(false)+ expect(results(preview)[0]).toMatchObject({ data, count })+ })++ it.each(['total', 'sum'])('derives a %s total from raw buckets', (math) => {+ const preview = deriveChartPreview(+ ChartDisplayType.BoldNumber,+ query(ChartDisplayType.ActionsLineGraph),+ response([series({ math })])+ )+ expect(results(preview)[0]).toMatchObject({ data: [], aggregated_value: 10 })+ })++ it.each([+ ['distinct users', 'dau', {}],+ ['average', 'avg', {}],+ ['percentile', 'p90', {}],+ ['formula', 'total', { trendsFilter: { formula: 'A / B' } }],+ ['smoothed buckets', 'total', { trendsFilter: { smoothingIntervals: 2 } }],+ ['sampled buckets', 'total', { samplingFactor: 0.1 }],+ ])('does not reconstruct a total from %s', (_, math, queryOverrides) => {+ expect(+ deriveChartPreview(+ ChartDisplayType.BoldNumber,+ query(ChartDisplayType.ActionsLineGraph, queryOverrides),+ response([series({ math })])+ )+ ).toBeNull()+ })++ it.each([ChartDisplayType.BoldNumber, ChartDisplayType.Metric])(+ 'does not fold breakdown rows to preview %s',+ (display) => {+ const source = query(ChartDisplayType.ActionsLineGraph, {+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+ })+ const rows = [+ series({ breakdown_value: 'Chrome' }),+ series({ breakdown_value: 'Safari', data: [10, 0, 0, 0] }),+ ]++ expect(deriveChartPreview(display, source, response(rows))).toBeNull()+ }+ )++ it('keeps breakdown totals separate when the target supports a breakdown', () => {+ const source = query(ChartDisplayType.ActionsLineGraph, {+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+ })+ const rows = [series({ breakdown_value: 'Chrome' }), series({ breakdown_value: 'Safari', data: [10, 0, 0, 0] })]++ const pie = deriveChartPreview(ChartDisplayType.ActionsPie, source, response(rows))+ expect(results(pie).map((row) => [row.breakdown_value, row.aggregated_value])).toEqual([+ ['Chrome', 10],+ ['Safari', 10],+ ])+ })++ it.each([ChartDisplayType.WorldMap, ChartDisplayType.CalendarHeatmap, ChartDisplayType.BoxPlot])(+ 'shows sample data for %s instead of querying',+ (display) => {+ const preview = deriveChartPreview(+ display,+ query(ChartDisplayType.ActionsLineGraph),+ response([series({})])+ )+ expect(preview?.sample).toBe(true)+ expect(results(preview).length).toBeGreaterThan(0)+ }+ )++ it('renders a complete country breakdown as a live map', () => {+ const preview = deriveChartPreview(+ ChartDisplayType.WorldMap,+ query(ChartDisplayType.ActionsLineGraph, {+ breakdownFilter: { breakdown: '$geoip_country_code', breakdown_type: 'event' },+ }),+ response([series({ breakdown_value: 'US' }), series({ breakdown_value: 'GB', data: [5, 5, 0, 0] })])+ )+ expect(preview?.sample).toBe(false)+ expect(results(preview).map((r) => [r.breakdown_value, r.aggregated_value])).toEqual([+ ['US', 10],+ ['GB', 10],+ ])+ })++ it('uses sample map data when the country breakdown is truncated', () => {+ expect(+ deriveChartPreview(+ ChartDisplayType.WorldMap,+ query(ChartDisplayType.ActionsLineGraph, {+ breakdownFilter: { breakdown: '$geoip_country_code', breakdown_type: 'event' },+ }),+ response([series({ breakdown_value: 'US' })], true)+ )?.sample+ ).toBe(true)+ })++ it('drops the previous-period series the metric runner adds unless the query compares', () => {+ const rows = [+ series({ compare_label: CompareLabelType.Current }),+ series({ compare_label: CompareLabelType.Previous, data: [9, 9, 9, 9] }),+ ]+ const source = query(ChartDisplayType.Metric)++ const line = deriveChartPreview(ChartDisplayType.ActionsLineGraph, source, response(rows))+ expect(results(line)).toHaveLength(1)+ expect(results(line)[0]).not.toHaveProperty('compare_label')++ const comparing = deriveChartPreview(+ ChartDisplayType.ActionsLineGraph,+ query(ChartDisplayType.Metric, { compareFilter: { compare: true } }),+ response(rows)+ )+ expect(results(comparing)).toHaveLength(2)+ })++ it('derives time series tiles from the remembered time series when only a total value is loaded', () => {+ const loaded = response([series({ math: 'dau', data: [], aggregated_value: 42 })])+ const remembered = response([+ series({ compare_label: CompareLabelType.Current }),+ series({ compare_label: CompareLabelType.Previous }),+ ])+ const source = query(ChartDisplayType.ActionsPie)++ expect(deriveChartPreview(ChartDisplayType.ActionsLineGraph, source, loaded)).toBeNull()+ expect(deriveChartPreview(ChartDisplayType.BoldNumber, source, loaded)).toEqual({+ response: loaded,+ sample: false,+ })++ const line = deriveChartPreview(ChartDisplayType.ActionsLineGraph, source, loaded, remembered)+ expect(line?.sample).toBe(false)+ expect(results(line!)).toHaveLength(1)+ expect(results(line!)[0]).toMatchObject({ data: [1, 2, 3, 4] })++ const cumulative = deriveChartPreview(ChartDisplayType.ActionsLineGraphCumulative, source, loaded, remembered)+ expect(results(cumulative!)[0]).toMatchObject({ data: [1, 3, 6, 10] })+ })++ it.each([+ ['cumulative', ChartDisplayType.ActionsLineGraphCumulative, [1, 3, 6, 10]],+ ['slope', ChartDisplayType.SlopeGraph, [1, 4]],+ ])('does not treat transformed %s output as raw buckets', (_, sourceDisplay, data) => {+ const source = query(sourceDisplay)+ const transformed = response([series({ data })])++ expect(deriveChartPreview(ChartDisplayType.BoldNumber, source, transformed)).toBeNull()++ const preview = deriveChartPreview(ChartDisplayType.BoldNumber, source, transformed, response([series({})]))+ expect(results(preview)[0]).toMatchObject({ aggregated_value: 10 })+ })++ it.each([+ ['smoothed buckets', query(ChartDisplayType.ActionsLineGraph, { trendsFilter: { smoothingIntervals: 2 } })],+ [+ 'breakdown buckets',+ query(ChartDisplayType.ActionsLineGraph, {+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+ }),+ ],+ ])('does not derive a slope from %s', (_, source) => {+ expect(deriveChartPreview(ChartDisplayType.SlopeGraph, source, response([series({})]))).toBeNull()+ })+})diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.tsnew file mode 100644index 000000000000..f64d59fbb23f--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts@@ -0,0 +1,221 @@+import type { AnyResponseType, TrendsQuery } from '~/queries/schema/schema-general'+import { ChartDisplayType, type TrendResult } from '~/types'++import { breakdownProperties, hasTrendsFormula } from './chartDisplayOptions'+import { sampleBoxPlotRows, sampleCalendarHeatmapRows, sampleWorldMapRows } from './chartPreviewSamples'++export interface ChartPreviewData {+ response: AnyResponseType+ sample: boolean+}++const SUMMABLE_MATHS = new Set(['total', 'sum'])++// Displays whose loaded result is the raw bucketed time series every other tile derives from.+export const RAW_TIME_SERIES_DISPLAYS = new Set<ChartDisplayType>([+ ChartDisplayType.ActionsLineGraph,+ ChartDisplayType.ActionsAreaGraph,+ ChartDisplayType.ActionsUnstackedBar,+ ChartDisplayType.ActionsBar,+ ChartDisplayType.ActionsStackedBar,+ ChartDisplayType.Metric,+])++interface PreviewRows {+ response: AnyResponseType+ results: TrendResult[]+}++type ResultShape = 'timeSeries' | 'totalValue' | 'heatmap' | 'boxPlot' | 'empty'++function resultsOf(response: AnyResponseType): TrendResult[] {+ const raw =+ (response as { result?: unknown; results?: unknown }).result ?? (response as { results?: unknown }).results+ return Array.isArray(raw) ? (raw as TrendResult[]) : []+}++// insightDataLogic rebuilds `result` from `results`, so both keys must carry the derived rows.+function withResults(response: AnyResponseType, results: unknown[]): AnyResponseType {+ return { ...(response as object), results, result: results } as AnyResponseType+}++function shapeOf(results: TrendResult[]): ResultShape {+ const first = results[0] as (TrendResult & { calendar_heatmap_data?: unknown; median?: number }) | undefined+ if (!first) {+ return 'empty'+ }+ if (first.calendar_heatmap_data) {+ return 'heatmap'+ }+ if (typeof first.median === 'number' && !Array.isArray(first.data)) {+ return 'boxPlot'+ }+ if (Array.isArray(first.data) && first.data.length > 0) {+ return 'timeSeries'+ }+ return first.aggregated_value != null ? 'totalValue' : 'empty'+}++function canSumBuckets(source: TrendsQuery, results: TrendResult[]): boolean {+ return (+ !hasTrendsFormula(source.trendsFilter) &&+ (source.trendsFilter?.smoothingIntervals ?? 1) <= 1 &&+ // The backend rounds each sampled bucket, so their sum can differ from a sampled total.+ (source.samplingFactor ?? 1) === 1 &&+ results.every((result) => result.action != null && SUMMABLE_MATHS.has(result.action.math ?? 'total'))+ )+}++function toTotalValue(result: TrendResult): TrendResult {+ return {+ ...result,+ data: [],+ count: 0,+ aggregated_value: (result.data ?? []).reduce((sum, value) => sum + value, 0),+ }+}++function toSlope(result: TrendResult): TrendResult {+ const ends = <T>(values: T[] | undefined): T[] =>+ values && values.length > 2 ? [values[0], values[values.length - 1]] : (values ?? [])+ return { ...result, data: ends(result.data), days: ends(result.days), labels: ends(result.labels) }+}++function toCumulative(result: TrendResult): TrendResult {+ let running = 0+ const data = (result.data ?? []).map((value) => (running += value))+ return { ...result, data, count: data[data.length - 1] ?? 0 }+}++function hasBreakdown(source: TrendsQuery): boolean {+ return breakdownProperties(source.breakdownFilter).length > 0+}++function hasCountryCodeBreakdown(source: TrendsQuery): boolean {+ const properties = breakdownProperties(source.breakdownFilter)+ return properties.length === 1 && properties[0] === '$geoip_country_code'+}++function isCompleteBreakdown(response: AnyResponseType): boolean {+ return (response as { hasMore?: boolean }).hasMore === false+}++// The Metric runner adds a previous-period series for its change pill even when the query does not compare,+// so other displays must not inherit it.+function stripComparison(results: TrendResult[]): TrendResult[] {+ if (!results.some((result) => result.compare_label)) {+ return results+ }+ return results+ .filter((result) => result.compare_label !== 'previous')+ .map(({ compare_label: _label, compare: _compare, ...rest }) => rest as TrendResult)+}++function previewRows(response: AnyResponseType, keepComparison: boolean): PreviewRows {+ const raw = resultsOf(response)+ const results = keepComparison ? raw : stripComparison(raw)+ return { response: results === raw ? response : withResults(response, results), results }+}++// Only standard time-series displays return raw buckets. Cumulative and slope results have already transformed or+// discarded buckets, so they need the remembered standard time-series response.+function rawBuckets(source: TrendsQuery, loaded: PreviewRows, remembered: PreviewRows | null): PreviewRows | null {+ const currentDisplay = source.trendsFilter?.display ?? ChartDisplayType.ActionsLineGraph+ if (shapeOf(loaded.results) === 'timeSeries' && RAW_TIME_SERIES_DISPLAYS.has(currentDisplay)) {+ return loaded+ }+ return remembered && shapeOf(remembered.results) === 'timeSeries' ? remembered : null+}++type RowsNeeded = 'buckets' | 'totals' | 'heatmap' | 'boxPlot'++interface PreviewRecipe {+ needs: RowsNeeded+ when?: (source: TrendsQuery, rows: PreviewRows) => boolean+ transform?: (result: TrendResult) => TrendResult+ sampleRows?: (loaded: TrendResult[]) => unknown[]+}++const noBreakdown = (source: TrendsQuery): boolean => !hasBreakdown(source)+const summable = (source: TrendsQuery, rows: PreviewRows): boolean => canSumBuckets(source, rows.results)+const canSlope = (source: TrendsQuery): boolean =>+ (source.trendsFilter?.smoothingIntervals ?? 1) <= 1 && !hasBreakdown(source)+const completeCountries = (source: TrendsQuery, rows: PreviewRows): boolean =>+ hasCountryCodeBreakdown(source) && isCompleteBreakdown(rows.response)++// A display without a recipe renders the loaded result as it is.+const RECIPES: Partial<Record<ChartDisplayType, PreviewRecipe>> = {+ [ChartDisplayType.ActionsLineGraph]: { needs: 'buckets' },+ [ChartDisplayType.ActionsAreaGraph]: { needs: 'buckets' },+ [ChartDisplayType.ActionsUnstackedBar]: { needs: 'buckets' },+ [ChartDisplayType.ActionsBar]: { needs: 'buckets' },+ [ChartDisplayType.ActionsStackedBar]: { needs: 'buckets' },+ [ChartDisplayType.Metric]: { needs: 'buckets', when: noBreakdown },+ [ChartDisplayType.ActionsLineGraphCumulative]: { needs: 'buckets', when: summable, transform: toCumulative },+ [ChartDisplayType.SlopeGraph]: { needs: 'buckets', when: canSlope, transform: toSlope },+ [ChartDisplayType.BoldNumber]: { needs: 'totals', when: noBreakdown },+ [ChartDisplayType.ActionsPie]: { needs: 'totals' },+ [ChartDisplayType.ActionsDonut]: { needs: 'totals' },+ [ChartDisplayType.ActionsBarValue]: { needs: 'totals' },+ [ChartDisplayType.ActionsTable]: { needs: 'totals' },+ [ChartDisplayType.WorldMap]: { needs: 'totals', when: completeCountries, sampleRows: sampleWorldMapRows },+ [ChartDisplayType.CalendarHeatmap]: { needs: 'heatmap', sampleRows: sampleCalendarHeatmapRows },+ [ChartDisplayType.BoxPlot]: { needs: 'boxPlot', sampleRows: sampleBoxPlotRows },+}++// The rows that can satisfy a need, best first.+function candidateRows(+ needs: RowsNeeded,+ source: TrendsQuery,+ loaded: PreviewRows,+ buckets: PreviewRows | null+): PreviewRows[] {+ if (needs === 'buckets') {+ return buckets ? [buckets] : []+ }+ const candidates = shapeOf(loaded.results) === (needs === 'totals' ? 'totalValue' : needs) ? [loaded] : []+ if (needs === 'totals' && buckets && canSumBuckets(source, buckets.results)) {+ const results = buckets.results.map(toTotalValue)+ candidates.push({ response: withResults(buckets.response, results), results })+ }+ return candidates+}++// Builds the result a chart type would render, without a query: from the insight's loaded result, or from+// a raw time series for the same query when the loaded result is a total value. Returns null when neither+// can produce the display.+export function deriveChartPreview(+ display: ChartDisplayType,+ source: TrendsQuery,+ loadedResponse: AnyResponseType,+ timeSeriesResponse: AnyResponseType | null = null+): ChartPreviewData | null {+ const keepComparison =+ (display !== ChartDisplayType.SlopeGraph && !!source.compareFilter?.compare) ||+ display === ChartDisplayType.Metric++ const loaded = previewRows(loadedResponse, keepComparison)+ const recipe = RECIPES[display]++ if (!recipe || display === (source.trendsFilter?.display ?? ChartDisplayType.ActionsLineGraph)) {+ return { response: loaded.response, sample: false }+ }++ const remembered = timeSeriesResponse ? previewRows(timeSeriesResponse, keepComparison) : null+ const buckets = rawBuckets(source, loaded, remembered)+ const rows = candidateRows(recipe.needs, source, loaded, buckets).find(+ (candidate) => recipe.when?.(source, candidate) ?? true+ )++ if (rows) {+ const response = recipe.transform+ ? withResults(rows.response, rows.results.map(recipe.transform))+ : rows.response++ return { response, sample: false }+ }++ return recipe.sampleRows+ ? { response: withResults(loaded.response, recipe.sampleRows(loaded.results)), sample: true }+ : null+}diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewSamples.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewSamples.tsnew file mode 100644index 000000000000..271e741f881e--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewSamples.ts@@ -0,0 +1,91 @@+import type { BoxPlotDatum } from '~/queries/schema/schema-general'+import type { TrendResult } from '~/types'++const SAMPLE_COUNTRIES: [string, number][] = [+ ['US', 1840],+ ['GB', 920],+ ['DE', 610],+ ['IN', 540],+ ['CA', 430],+ ['FR', 380],+ ['BR', 310],+ ['AU', 260],+ ['JP', 220],+ ['NL', 170],+]++const SAMPLE_BOX_PLOT_DAYS = 7++function sampleAction(result: TrendResult | undefined): Pick<TrendResult, 'action' | 'label'> {+ return { action: result?.action ?? null, label: result?.label ?? 'Sample' }+}++export function sampleWorldMapRows(loaded: TrendResult[]): unknown[] {+ const base = sampleAction(loaded[0])+ return SAMPLE_COUNTRIES.map(([code, value]) => ({+ ...base,+ breakdown_value: code,+ data: [],+ days: [],+ labels: [],+ count: 0,+ aggregated_value: value,+ }))+}++export function sampleCalendarHeatmapRows(loaded: TrendResult[]): unknown[] {+ const data: { row: number; column: number; value: number }[] = []+ const rows = Array.from({ length: 7 }, () => 0)+ const columns = Array.from({ length: 24 }, () => 0)+ let all = 0+ for (let row = 0; row < 7; row++) {+ const weekday = row >= 1 && row <= 5+ for (let column = 0; column < 24; column++) {+ const working = column >= 8 && column <= 18+ const value = (weekday ? 40 : 12) + (working ? 60 : 0) + ((row * 7 + column * 3) % 11)+ data.push({ row, column, value })+ rows[row] += value+ columns[column] += value+ all += value+ }+ }+ return [+ {+ ...sampleAction(loaded[0]),+ data: [],+ days: [],+ labels: [],+ count: all,+ aggregated_value: all,+ calendar_heatmap_data: {+ data,+ rowAggregations: rows.map((value, row) => ({ row, value })),+ columnAggregations: columns.map((value, column) => ({ column, value })),+ allAggregations: all,+ },+ },+ ]+}++export function sampleBoxPlotRows(loaded: TrendResult[]): BoxPlotDatum[] {+ const first = loaded[0]+ const days = first?.days?.length+ ? first.days+ : Array.from({ length: SAMPLE_BOX_PLOT_DAYS }, (_, i) => `Day ${i + 1}`)+ const labels = first?.labels?.length === days.length ? first.labels : days+ return days.map((day, index) => {+ const median = 40 + ((index * 13) % 17)+ return {+ day,+ label: labels[index],+ min: median - 25,+ p25: median - 10,+ median,+ p75: median + 12,+ max: median + 30,+ mean: median + 2,+ series_index: 0,+ series_label: first?.label ?? 'Sample',+ }+ })+}