Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Add support for comparison in funnels (#6632)

Sanne de Vriesc70260e946e8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f3849b683a..e9ecae6424 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ All notable changes to this project will be documented in this file.
- Add "Last 24 Hours" to dashboard time range picker and Stats API v2
- Always compare against the same time range in comparisons with "Today"
- Added vertical indicator line to graph to make it easier to see what's hovered / selected
+- Added comparison support to funnels
### Removed
diff --git a/assets/js/dashboard/extra/funnel/index.tsx b/assets/js/dashboard/extra/funnel/index.tsx
index 17bd7a65e8..2320b37573 100644
--- a/assets/js/dashboard/extra/funnel/index.tsx
+++ b/assets/js/dashboard/extra/funnel/index.tsx
@@ -6,12 +6,24 @@ import classNames from 'classnames'
import * as api from '../../api'
import LazyLoader from '../../components/lazy-loader'
import { DashboardState } from '../../dashboard-state'
+import { isComparisonEnabled } from '../../dashboard-time-periods'
import { getStaleTime } from '../../hooks/api-client'
+import {
+ formatDateRangeLabel,
+ MetricValueTooltipContent
+} from '../../stats/breakdowns'
+import { ChangeArrow } from '../../stats/reports/change-arrow'
import { numberLongFormatter, rateFormatter } from '../../util/number-formatter'
import { Tooltip } from '../../util/tooltip'
import { useDashboardStateContext } from '../../dashboard-state-context'
import { useSiteContext } from '../../site-context'
-import { FunnelResponse, StepMetrics, stepMetrics } from './metrics'
+import {
+ FunnelResponse,
+ StepMetrics,
+ StepValues,
+ conversionRateChange,
+ stepMetrics
+} from './metrics'
import { StepOutcomes } from './outcome-box'
const FUNNEL_REPORT_ID = 'funnel'
@@ -26,23 +38,40 @@ type FunnelQueryKey = [
const VISIBLE_COLUMNS = 5
const COLUMN_GAP_REM = 1
const PEEK_WIDTH_PX = 24
-const MIN_COLUMN_WIDTH = '12rem'
+const MIN_BAR_WIDTH = '12rem'
+const BAR_GAP_REM = 0.5
const BAR_MIN_HEIGHT = '8px'
const BAR_TOP_GAP = '0.75rem'
-function gridTemplateColumns(stepCount: number): string {
+function gridTemplateColumns(stepCount: number, comparing: boolean): string {
+ const minWidth = comparing
+ ? `calc(2 * ${MIN_BAR_WIDTH} + ${BAR_GAP_REM}rem)`
+ : MIN_BAR_WIDTH
+
if (stepCount <= VISIBLE_COLUMNS) {
- return `repeat(${stepCount}, minmax(${MIN_COLUMN_WIDTH}, 1fr))`
+ return `repeat(${stepCount}, minmax(${minWidth}, 1fr))`
}
const reserved = `${PEEK_WIDTH_PX}px + ${VISIBLE_COLUMNS} * ${COLUMN_GAP_REM}rem`
const width = `calc((100% - (${reserved})) / ${VISIBLE_COLUMNS})`
- return `repeat(${stepCount}, max(${MIN_COLUMN_WIDTH}, ${width}))`
+ return `repeat(${stepCount}, max(${minWidth}, ${width}))`
+}
+
+function fillPercent(values: StepValues | null | undefined): number {
+ return values ? Math.max(Number(values.conversionRate), 0) : 0
}
-function fillPercent(step: StepMetrics | null | undefined): number {
- return step ? Math.max(Number(step.conversionRate), 0) : 0
+function showingComparison(
+ step: StepMetrics | null | undefined,
+ comparing: boolean
+): boolean {
+ return step ? step.comparison !== null : comparing
+}
+
+function verticalLineBottom(heights: number[]): string {
+ const tops = [...heights.map((height) => `${height}%`), BAR_MIN_HEIGHT]
+ return `calc(max(${tops.join(', ')}) + ${BAR_TOP_GAP})`
}
function userFacingMessage(error: Error): string | null {
@@ -60,7 +89,68 @@ function userFacingMessage(error: Error): string | null {
return written && error.message ? error.message : null
}
-function StepHeader({ step }: { step: StepMetrics }): ReactNode {
+function ConversionChange({
+ current,
+ previous
+}: {
+ current: string
+ previous: string
+}): ReactNode {
+ return (
+ <ChangeArrow
+ metric="conversion_rate"
+ change={conversionRateChange(current, previous)}
+ className="shrink-0 text-xs font-medium text-gray-500 dark:text-gray-100"
+ />
+ )
+}
+
+function PeriodStats({
+ values,
+ change,
+ muted
+}: {
+ values: StepValues
+ change?: ReactNode
+ muted?: boolean
+}): ReactNode {
+ return (
+ <div
+ className={classNames(
+ 'flex flex-col min-w-0 flex-1',
+ muted && 'text-gray-500/80 dark:text-gray-400'
+ )}
+ >
+ <span className="flex items-baseline gap-1">
+ <span
+ className={classNames(
+ 'shrink-0 text-base font-semibold',
+ !muted && 'text-gray-900 dark:text-gray-100'
+ )}
+ >
+ {rateFormatter(values.conversionRate)}
+ </span>
+ {change}
+ </span>
+ <span
+ className={classNames(
+ 'text-xs font-medium truncate',
+ !muted && 'text-gray-500 dark:text-gray-400'
+ )}
+ >
+ {numberLongFormatter(values.visitors)} visitors
+ </span>
+ </div>
+ )
+}
+
+function StepHeader({
+ step,
+ entryStep
+}: {
+ step: StepMetrics
+ entryStep: boolean
+}): ReactNode {
return (
<>
<span
@@ -69,49 +159,130 @@ function StepHeader({ step }: { step: StepMetrics }): ReactNode {
>
{step.label}
</span>
- <div className="flex items-baseline gap-2">
- <span className="shrink-0 text-base font-semibold text-gray-900 dark:text-gray-100">
- {rateFormatter(step.conversionRate)}
- </span>
- <span className="text-xs font-medium text-gray-500 dark:text-gray-400 truncate">
- {numberLongFormatter(step.visitors)} visitors
- </span>
+ <div className="flex">
+ <PeriodStats
+ values={step}
+ change={
+ step.comparison && !entryStep ? (
+ <ConversionChange
+ current={step.conversionRate}
+ previous={step.comparison.conversionRate}
+ />
+ ) : undefined
+ }
+ />
+ {step.comparison && <PeriodStats values={step.comparison} muted />}
</div>
</>
)
}
-function StepHeaderPlaceholder(): ReactNode {
+function MetricPlaceholder(): ReactNode {
return (
- <div className="flex flex-col gap-2 h-9 animate-pulse">
- <span className="h-3 w-24 rounded-sm bg-gray-150 dark:bg-gray-800" />
+ <div className="flex flex-col gap-2 flex-1">
<span className="h-3 w-16 rounded-sm bg-gray-150 dark:bg-gray-800" />
+ <span className="h-3 w-20 rounded-sm bg-gray-150 dark:bg-gray-800" />
+ </div>
+ )
+}
+
+function StepHeaderPlaceholder({
+ comparing
+}: {
+ comparing: boolean
+}): ReactNode {
+ return (
+ <div className="flex flex-col gap-2 animate-pulse">
+ <span className="h-3 w-24 rounded-sm bg-gray-150 dark:bg-gray-800" />
+ <div className="flex">
+ <MetricPlaceholder />
+ {comparing && <MetricPlaceholder />}
+ </div>
+ </div>
+ )
+}
+
+function StepBar({
+ values,
+ previousFill,
+ entryStep,
+ finalStep,
+ previousPeriod
+}: {
+ values: StepValues | null
+ previousFill: number
+ entryStep: boolean
+ finalStep: boolean
+ previousPeriod?: boolean
+}): ReactNode {
+ return (
+ <div className="group/bar relative flex-1">
+ <div
+ className="absolute inset-x-0 bottom-0 rounded-t-md bg-gray-100 dark:bg-gray-800 transition-[height] duration-500 ease-out"
+ style={{ height: `${previousFill}%` }}
+ />
+ <div
+ data-testid={previousPeriod ? 'funnel-comparison-bar' : 'funnel-bar'}
+ className={classNames(
+ 'absolute inset-x-0 bottom-0 rounded-md transition-[height] duration-500 ease-out',
+ previousPeriod
+ ? 'bg-indigo-100 dark:bg-indigo-500/30'
+ : 'bg-linear-to-b from-indigo-300 to-indigo-400 dark:from-indigo-500/60 dark:to-indigo-500/90',
+ 'after:absolute after:inset-0 after:rounded-md after:transition-colors',
+ previousPeriod
+ ? 'after:bg-indigo-200/0 dark:after:bg-indigo-400/0 group-hover/bar:after:bg-indigo-200/15 dark:group-hover/bar:after:bg-indigo-400/5'
+ : 'after:bg-indigo-500/0 dark:after:bg-indigo-400/0 group-hover/bar:after:bg-indigo-500/10 dark:group-hover/bar:after:bg-indigo-400/15'
+ )}
+ style={{ height: `max(${fillPercent(values)}%, ${BAR_MIN_HEIGHT})` }}
+ />
+ {values !== null && (
+ <StepOutcomes
+ values={values}
+ entryStep={entryStep}
+ finalStep={finalStep}
+ previousPeriod={previousPeriod}
+ />
+ )}
</div>
)
}
function StepColumn({
step,
+ previousStep,
index,
finalStep,
- previousFill
+ comparing
}: {
step: StepMetrics | null
+ previousStep: StepMetrics | null | undefined
index: number
finalStep: boolean
- previousFill: number
+ comparing: boolean
}): ReactNode {
- const fill = fillPercent(step)
+ const paired = showingComparison(step, comparing)
+
+ const previousFill = fillPercent(previousStep)
+ const previousComparisonFill = fillPercent(previousStep?.comparison)
+
+ const heights = [previousFill, fillPercent(step)]
+ if (paired) {
+ heights.push(previousComparisonFill, fillPercent(step?.comparison))
+ }
return (
<div
data-testid={`funnel-step-${index}`}
- className="group/step flex flex-col"
+ className="flex flex-col"
style={{ gap: BAR_TOP_GAP }}
>
<div className="relative flex flex-col gap-0.5 pl-2">
<span className="absolute inset-y-0 left-0 w-px bg-gray-200 dark:bg-gray-750" />
- {step === null ? <StepHeaderPlaceholder /> : <StepHeader step={step} />}
+ {step === null ? (
+ <StepHeaderPlaceholder comparing={paired} />
+ ) : (
+ <StepHeader step={step} entryStep={index === 0} />
+ )}
</div>
<div className="relative flex-1 min-h-56">
@@ -119,52 +290,97 @@ function StepColumn({
className="absolute left-0 w-px bg-gray-200 dark:bg-gray-750 transition-[bottom] duration-500 ease-out"
style={{
top: `-${BAR_TOP_GAP}`,
- bottom: `calc(max(${previousFill}%, ${fill}%, ${BAR_MIN_HEIGHT}) + ${BAR_TOP_GAP})`
+ bottom: verticalLineBottom(heights)
}}
/>
<div
- className="absolute inset-x-0 bottom-0 rounded-t-md bg-gray-100 dark:bg-gray-800 transition-[height] duration-500 ease-out"
- style={{ height: `${previousFill}%` }}
- />
- <div
- data-testid="funnel-bar"
- className={classNames(
- 'absolute inset-x-0 bottom-0 rounded-md transition-[height] duration-500 ease-out',
- 'bg-linear-to-b from-indigo-200 to-indigo-300 dark:from-indigo-500/35 dark:to-indigo-500/50',
- 'after:absolute after:inset-0 after:rounded-md after:transition-colors',
- 'after:bg-indigo-400/0 dark:after:bg-indigo-400/15',
- 'group-hover/step:after:bg-indigo-400/25 dark:group-hover/step:after:bg-indigo-400/30'
- )}
- style={{ height: `max(${fill}%, ${BAR_MIN_HEIGHT})` }}
- />
- {step !== null && (
- <StepOutcomes
- step={step}
+ className="absolute inset-0 flex"
+ style={{ gap: paired ? `${BAR_GAP_REM}rem` : undefined }}
+ >
+ <StepBar
+ values={step}
+ previousFill={previousFill}
entryStep={index === 0}
finalStep={finalStep}
/>
- )}
+ {paired && (
+ <StepBar
+ values={step?.comparison ?? null}
+ previousFill={previousComparisonFill}
+ entryStep={index === 0}
+ finalStep={finalStep}
+ previousPeriod
+ />
+ )}
+ </div>
</div>
</div>
)
}
+function ConversionRateSummary({
+ current,
+ previous,
+ dateRange,
+ comparisonDateRange
+}: {
+ current: string
+ previous: string | null
+ dateRange: [string, string] | undefined
+ comparisonDateRange: [string, string] | null | undefined
+}): ReactNode {
+ const rate = (
+ <span className="flex items-baseline gap-1">
+ <span className="shrink-0">Conversion rate:</span>
+ <span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
+ {rateFormatter(current)}
+ </span>
+ {previous && <ConversionChange current={current} previous={previous} />}
+ </span>
+ )
+
+ if (!previous || !dateRange || !comparisonDateRange) {
+ return rate
+ }
+
+ return (
+ <Tooltip
+ className="flex"
+ containerRef={{ current: document.body }}
+ info={
+ <MetricValueTooltipContent
+ value={Number(current)}
+ comparison={{ value: Number(previous) }}
+ metric="conversion_rate"
+ metricLabel="Conversion rate"
+ dateRangeLabel={formatDateRangeLabel(dateRange)}
+ comparisonDateRangeLabel={formatDateRangeLabel(comparisonDateRange)}
+ />
+ }
+ >
+ {rate}
+ </Tooltip>
+ )
+}
+
function FunnelHeader({
funnelName,
funnel,
+ steps,
loading
}: {
funnelName: string
funnel: FunnelResponse | null
+ steps: StepMetrics[] | null
loading: boolean
}): ReactNode {
- const lastStep = funnel ? funnel.steps[funnel.steps.length - 1] : null
+ const lastStep = steps?.[steps.length - 1] ?? null
return (
- <div className="sm:h-7 flex flex-wrap items-center gap-x-3">
+ <div className="sm:h-7 flex flex-wrap items-baseline gap-x-3">
<h4
data-testid="funnel-title"
- className="flex-1 text-sm font-semibold dark:text-gray-100"
+ className="grow basis-auto min-w-0 truncate text-sm font-semibold dark:text-gray-100"
>
{funnelName}
</h4>
@@ -177,40 +393,42 @@ function FunnelHeader({
)}
{funnel && lastStep && (
- <div className="w-full sm:w-auto flex items-center gap-2 sm:gap-3 text-xs font-medium text-gray-500 dark:text-gray-400">
- <span>{funnel.steps.length}-step funnel</span>
-
- <span className="text-gray-300 dark:text-gray-600 select-none">
- |
- </span>
-
- <div className="flex items-center gap-1">
- {funnel.strict_order ? 'Strict' : 'Sequential'}
- <Tooltip
- className="flex"
- containerRef={{ current: document.body }}
- info={
- <span>
- {funnel.strict_order
- ? 'No other activity is allowed between steps.'
- : 'Other activity is allowed between steps.'}
- </span>
- }
- >
- <InformationCircleIcon className="size-3.5" />
- </Tooltip>
- </div>
+ <div className="overflow-x-auto">
+ <div className="w-full sm:w-auto flex gap-2 sm:gap-3 text-xs font-medium text-gray-500 dark:text-gray-400 items-baseline">
+ <span className="shrink-0">{funnel.steps.length}-step funnel</span>
- <span className="text-gray-300 dark:text-gray-600 select-none">
- |
- </span>
+ <span className="text-gray-300 dark:text-gray-600 select-none">
+ |
+ </span>
- <span className="flex items-baseline gap-1">
- Conversion rate:
- <span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
- {rateFormatter(lastStep.conversion_rate)}
+ <div className="flex items-center gap-1">
+ {funnel.strict_order ? 'Strict' : 'Sequential'}
+ <Tooltip
+ className="flex"
+ containerRef={{ current: document.body }}
+ info={
+ <span>
+ {funnel.strict_order
+ ? 'No other activity is allowed between steps.'
+ : 'Other activity is allowed between steps.'}
+ </span>
+ }
+ >
+ <InformationCircleIcon className="size-3.5" />
+ </Tooltip>
+ </div>
+
+ <span className="text-gray-300 dark:text-gray-600 select-none">
+ |
</span>
- </span>
+
+ <ConversionRateSummary
+ current={lastStep.conversionRate}
+ previous={lastStep.comparison?.conversionRate ?? null}
+ dateRange={funnel.date_range}
+ comparisonDateRange={funnel.comparison_date_range}
+ />
+ </div>
</div>
)}
</div>
@@ -227,6 +445,7 @@ export default function Funnel({
const [visible, setVisible] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const funnelMeta = site.funnels.find(({ name }) => name === funnelName)
+ const comparing = isComparisonEnabled(dashboardState.comparison)
const {
data: funnel,
@@ -246,7 +465,10 @@ export default function Funnel({
queryKey[1].dashboardState
)
},
- placeholderData: (previousData) => previousData,
+ placeholderData: (previousData) =>
+ previousData != null && Boolean(previousData.comparison) === comparing
+ ? previousData
+ : undefined,
staleTime: ({ queryKey }) => {
return getStaleTime({
siteTimezoneOffset: site.offset,
@@ -256,6 +478,9 @@ export default function Funnel({
}
})
+ const visibleFunnel = error ? null : (funnel ?? null)
+ const steps = visibleFunnel ? stepMetrics(visibleFunnel) : null
+
useEffect(() => {
if (containerRef.current) {
containerRef.current.scrollLeft = 0
@@ -288,8 +513,8 @@ export default function Funnel({
return renderError(error)
}
- const columns: (StepMetrics | null)[] = funnel
- ? stepMetrics(funnel)
+ const columns: (StepMetrics | null)[] = steps
+ ? steps
: new Array(funnelMeta?.steps_count || VISIBLE_COLUMNS).fill(null)
return (
@@ -299,16 +524,20 @@ export default function Funnel({
className="relative flex-1 grid overflow-x-auto -mx-5 px-5 -mb-3 pb-3 [scrollbar-width:thin] [scrollbar-color:theme(colors.gray.300)_transparent] dark:[scrollbar-color:theme(colors.gray.600)_transparent]"
style={{
gap: `${COLUMN_GAP_REM}rem`,
- gridTemplateColumns: gridTemplateColumns(columns.length)
+ gridTemplateColumns: gridTemplateColumns(
+ columns.length,
+ showingComparison(columns[0], comparing)
+ )
}}
>
{columns.map((step, index) => (
<StepColumn
key={`${funnelName}-${index}`}
step={step}
+ previousStep={columns[index - 1]}
index={index}
finalStep={index === columns.length - 1}
- previousFill={fillPercent(columns[index - 1])}
+ comparing={comparing}
/>
))}
</div>
@@ -320,7 +549,8 @@ export default function Funnel({
<div className="flex-1 flex flex-col gap-8 pt-4">
<FunnelHeader
funnelName={funnelName}
- funnel={error ? null : (funnel ?? null)}
+ funnel={visibleFunnel}
+ steps={steps}
loading={loading && !error}
/>
{renderContent()}
diff --git a/assets/js/dashboard/extra/funnel/metrics.test.ts b/assets/js/dashboard/extra/funnel/metrics.test.ts
index c2f8b129f7..158ca78e88 100644
--- a/assets/js/dashboard/extra/funnel/metrics.test.ts
+++ b/assets/js/dashboard/extra/funnel/metrics.test.ts
@@ -1,4 +1,4 @@
-import { FunnelResponse, stepMetrics } from './metrics'
+import { FunnelResponse, conversionRateChange, stepMetrics } from './metrics'
const funnel: FunnelResponse = {
name: 'Checkout',
@@ -36,6 +36,40 @@ const funnel: FunnelResponse = {
]
}
+const comparison: NonNullable<FunnelResponse['comparison']> = {
+ all_visitors: 200,
+ entering_visitors: 80,
+ entering_visitors_percentage: '40',
+ never_entering_visitors: 120,
+ never_entering_visitors_percentage: '60',
+ steps: [
+ {
+ label: 'Visit /products',
+ visitors: 80,
+ dropoff: 0,
+ dropoff_percentage: '0',
+ conversion_rate: '100',
+ conversion_rate_step: '100'
+ },
+ {
+ label: 'Add to cart',
+ visitors: 40,
+ dropoff: 40,
+ dropoff_percentage: '50',
+ conversion_rate: '50',
+ conversion_rate_step: '50'
+ },
+ {
+ label: 'Purchase',
+ visitors: 8,
+ dropoff: 32,
+ dropoff_percentage: '80',
+ conversion_rate: '10',
+ conversion_rate_step: '20'
+ }
+ ]
+}
+
describe('stepMetrics()', () => {
it('gives one entry per step', () => {
expect(stepMetrics(funnel).map(({ label }) => label)).toEqual([
@@ -77,4 +111,50 @@ describe('stepMetrics()', () => {
it('gives no entries for a funnel without steps', () => {
expect(stepMetrics({ ...funnel, steps: [] })).toEqual([])
})
+
+ it('leaves out the comparison when the funnel has none', () => {
+ expect(stepMetrics(funnel).map(({ comparison }) => comparison)).toEqual([
+ null,
+ null,
+ null
+ ])
+ })
+
+ it('takes the comparison values from the matching comparison step', () => {
+ const [firstStep, , thirdStep] = stepMetrics({ ...funnel, comparison })
+
+ expect(firstStep.comparison).toEqual({
+ visitors: 80,
+ conversionRate: '100',
+ continued: { visitors: 80, rate: '40' },
+ droppedOff: { visitors: 120, rate: '60' }
+ })
+ expect(thirdStep.comparison).toEqual({
+ visitors: 8,
+ conversionRate: '10',
+ continued: { visitors: 8, rate: '20' },
+ droppedOff: { visitors: 32, rate: '80' }
+ })
+ })
+
+ it('keeps the current values next to the comparison values', () => {
+ const [firstStep] = stepMetrics({ ...funnel, comparison })
+
+ expect(firstStep.visitors).toBe(100)
+ expect(firstStep.continued).toEqual({ visitors: 100, rate: '40' })
+ })
+})
+
+describe('conversionRateChange()', () => {
+ it('gives the difference in percentage points', () => {
+ expect(conversionRateChange('60.8', '52.7')).toBe(8.1)
+ })
+
+ it('is zero when the rates match', () => {
+ expect(conversionRateChange('100', '100')).toBe(0)
+ })
+
+ it('is negative when the rate fell', () => {
+ expect(conversionRateChange('10', '15')).toBe(-5)
+ })
})
diff --git a/assets/js/dashboard/extra/funnel/metrics.ts b/assets/js/dashboard/extra/funnel/metrics.ts
index 881b7b890a..dbf76c1cdf 100644
--- a/assets/js/dashboard/extra/funnel/metrics.ts
+++ b/assets/js/dashboard/extra/funnel/metrics.ts
@@ -7,9 +7,7 @@ type FunnelStep = {
conversion_rate_step: string
}
-export type FunnelResponse = {
- name: string
- strict_order: boolean
+type FunnelPeriod = {
steps: FunnelStep[]
all_visitors: number
entering_visitors: number
@@ -18,22 +16,37 @@ export type FunnelResponse = {
never_entering_visitors_percentage: string
}
-type StepOutcome = {
+export type FunnelResponse = FunnelPeriod & {
+ name: string
+ strict_order: boolean
+ comparison?: FunnelPeriod | null
+ date_range?: [string, string]
+ comparison_date_range?: [string, string] | null
+}
+
+export type StepOutcome = {
visitors: number
rate: string
}
-export type StepMetrics = {
- label: string
+export type StepValues = {
visitors: number
conversionRate: string
continued: StepOutcome
droppedOff: StepOutcome
}
-export function stepMetrics(funnel: FunnelResponse): StepMetrics[] {
- return funnel.steps.map((step, index) => ({
- label: step.label,
+export type StepMetrics = StepValues & {
+ label: string
+ comparison: StepValues | null
+}
+
+function stepValues(
+ funnel: FunnelPeriod,
+ step: FunnelStep,
+ index: number
+): StepValues {
+ return {
visitors: step.visitors,
conversionRate: step.conversion_rate,
continued:
@@ -50,5 +63,29 @@ export function stepMetrics(funnel: FunnelResponse): StepMetrics[] {
rate: funnel.never_entering_visitors_percentage
}
: { visitors: step.dropoff, rate: step.dropoff_percentage }
- }))
+ }
+}
+
+export function conversionRateChange(
+ current: string,
+ previous: string
+): number {
+ return Math.round((Number(current) - Number(previous)) * 10) / 10
+}
+
+export function stepMetrics(funnel: FunnelResponse): StepMetrics[] {
+ const previous = funnel.comparison
+
+ return funnel.steps.map((step, index) => {
+ const previousStep = previous?.steps[index]
+
+ return {
+ label: step.label,
+ ...stepValues(funnel, step, index),
+ comparison:
+ previous && previousStep
+ ? stepValues(previous, previousStep, index)
+ : null
+ }
+ })
}
diff --git a/assets/js/dashboard/extra/funnel/outcome-box.tsx b/assets/js/dashboard/extra/funnel/outcome-box.tsx
index 7ebec530d8..854f3899d7 100644
--- a/assets/js/dashboard/extra/funnel/outcome-box.tsx
+++ b/assets/js/dashboard/extra/funnel/outcome-box.tsx
@@ -2,7 +2,7 @@ import React, { ReactNode, useLayoutEffect, useRef, useState } from 'react'
import classNames from 'classnames'
import { numberLongFormatter, rateFormatter } from '../../util/number-formatter'
-import { StepMetrics } from './metrics'
+import { StepOutcome, StepValues } from './metrics'
// The outcome box sits at the foot of a funnel bar. By default it is a compact
// pill with the rates only ("→ 55% ↓ 45%"). On hover, focus, or touch it grows
@@ -23,38 +23,40 @@ type Outcome = {
count: string
}
+function outcome(
+ kind: Outcome['kind'],
+ symbol: string,
+ { rate, visitors }: StepOutcome,
+ verb: string
+): Outcome {
+ const formatted = rateFormatter(rate)
+
+ return {
+ kind,
+ symbol,
+ rate: formatted,
+ detail: `${formatted} ${verb}`,
+ count: `(${numberLongFormatter(visitors)})`
+ }
+}
+
function stepOutcomes(
- step: StepMetrics,
+ values: StepValues,
entryStep: boolean,
finalStep: boolean
): Outcome[] {
- const continued = rateFormatter(step.continued.rate)
const continuedVerb = entryStep
? 'entered'
: finalStep
? 'converted'
: 'continued'
- const outcomes: Outcome[] = [
- {
- kind: 'continued',
- symbol: finalStep ? '✓' : '→',
- rate: continued,
- detail: `${continued} ${continuedVerb}`,
- count: `(${numberLongFormatter(step.continued.visitors)})`
- }
+ const outcomes = [
+ outcome('continued', finalStep ? '✓' : '→', values.continued, continuedVerb)
]
if (!entryStep) {
- const droppedOff = rateFormatter(step.droppedOff.rate)
-
- outcomes.push({
- kind: 'droppedOff',
- symbol: '↓',
- rate: droppedOff,
- detail: `${droppedOff} dropped off`,
- count: `(${numberLongFormatter(step.droppedOff.visitors)})`
- })
+ outcomes.push(outcome('droppedOff', '↓', values.droppedOff, 'dropped off'))
}
return outcomes
@@ -67,13 +69,11 @@ function OutcomeText({
outcome: Outcome
detailed: boolean
}): ReactNode {
- const dropoff = outcome.kind === 'droppedOff'
-
return (
<span
className={classNames(
'flex items-start gap-1 font-medium',
- dropoff
+ outcome.kind === 'droppedOff'
? 'text-gray-500 dark:text-gray-400'
: 'text-gray-900 dark:text-gray-100'
)}
@@ -143,28 +143,32 @@ function useOutcomeSize(measureKey: string) {
}
export function StepOutcomes({
- step,
+ values,
entryStep,
- finalStep
+ finalStep,
+ previousPeriod
}: {
- step: StepMetrics
+ values: StepValues
entryStep: boolean
finalStep: boolean
+ previousPeriod?: boolean
}): ReactNode {
const [open, setOpen] = useState(false)
- const outcomes = stepOutcomes(step, entryStep, finalStep)
+ const outcomes = stepOutcomes(values, entryStep, finalStep)
const label = outcomes
.map(({ detail, count }) => `${detail} ${count}`)
.join(', ')
- const { box, compact, expanded } = useOutcomeSize(label)
+ const accessibleName = previousPeriod ? `Previous period: ${label}` : label
+
+ const { box, compact, expanded } = useOutcomeSize(accessibleName)
return (
<button
ref={box}
type="button"
- aria-label={label}
+ aria-label={accessibleName}
data-open={open || undefined}
onClick={() => setOpen((shown) => !shown)}
style={{ left: OUTCOME_INSET_PX, bottom: OUTCOME_INSET_PX }}
@@ -174,7 +178,7 @@ export function StepOutcomes({
'w-[var(--outcome-w,max-content)] h-[var(--outcome-h,auto)]',
'transition-[width,height] duration-200 ease-out',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500/40',
- 'group-hover/step:w-[var(--outcome-grown-w)] group-hover/step:h-[var(--outcome-grown-h)]',
+ 'group-hover/bar:w-[var(--outcome-grown-w)] group-hover/bar:h-[var(--outcome-grown-h)]',
'focus-visible:w-[var(--outcome-grown-w)] focus-visible:h-[var(--outcome-grown-h)]',
'data-open:w-[var(--outcome-grown-w)] data-open:h-[var(--outcome-grown-h)]'
)}
@@ -182,7 +186,7 @@ export function StepOutcomes({
<div
ref={compact}
aria-hidden="true"
- className="flex items-center gap-1.5 w-max px-1.5 py-0.5 text-xs leading-4 whitespace-nowrap transition-opacity duration-200 starting:opacity-0 group-hover/step:opacity-0 group-focus-visible/outcome:opacity-0 group-data-open/outcome:opacity-0"
+ className="flex items-center gap-1.5 w-max px-1.5 py-0.5 text-xs leading-4 whitespace-nowrap transition-opacity duration-200 starting:opacity-0 group-hover/bar:opacity-0 group-focus-visible/outcome:opacity-0 group-data-open/outcome:opacity-0"
>
{outcomes.map((outcome) => (
<OutcomeText key={outcome.kind} outcome={outcome} detailed={false} />
@@ -192,7 +196,7 @@ export function StepOutcomes({
<div
ref={expanded}
aria-hidden="true"
- className="absolute top-0 left-0 flex flex-col gap-0.5 w-[var(--outcome-grown-w,max-content)] px-1.5 py-0.5 text-xs leading-4 opacity-0 transition-opacity duration-150 group-hover/step:opacity-100 group-focus-visible/outcome:opacity-100 group-data-open/outcome:opacity-100"
+ className="absolute top-0 left-0 flex flex-col gap-0.5 w-[var(--outcome-grown-w,max-content)] px-1.5 py-0.5 text-xs leading-4 opacity-0 transition-opacity duration-150 group-hover/bar:opacity-100 group-focus-visible/outcome:opacity-100 group-data-open/outcome:opacity-100"
>
{outcomes.map((outcome) => (
<OutcomeText key={outcome.kind} outcome={outcome} detailed={true} />
diff --git a/assets/js/dashboard/stats/breakdowns.tsx b/assets/js/dashboard/stats/breakdowns.tsx
index 1ff25fe286..60a1e8c6e7 100644
--- a/assets/js/dashboard/stats/breakdowns.tsx
+++ b/assets/js/dashboard/stats/breakdowns.tsx
@@ -123,7 +123,7 @@ export function MetricValueTooltipContent({
comparisonDateRangeLabel
}: {
value: ValueType
- comparison: { value: ValueType; change: number } | null
+ comparison: { value: ValueType; change?: number } | null
metric: Metric
metricLabel: string
dateRangeLabel: string
@@ -146,11 +146,13 @@ export function MetricValueTooltipContent({
{dateRangeLabel}
</div>
</div>
- <ChangeArrow
- metric={metric}
- change={comparison.change}
- className="text-xs/6 font-medium text-white"
- />
+ {comparison.change != null && (
+ <ChangeArrow
+ metric={metric}
+ change={comparison.change}
+ className="text-xs/6 font-medium text-white"
+ />
+ )}
</div>
</div>
<div className="w-full border-t border-gray-600" />
diff --git a/e2e/tests/dashboard/behaviours.spec.ts b/e2e/tests/dashboard/behaviours.spec.ts
index b2ac936cca..5172bc225f 100644
--- a/e2e/tests/dashboard/behaviours.spec.ts
+++ b/e2e/tests/dashboard/behaviours.spec.ts
@@ -1042,3 +1042,139 @@ test('funnels', async ({ page, request }) => {
])
})
})
+
+test('funnels - comparisons', async ({ page, request }) => {
+ const report = getReport(page)
+ const { domain } = await setupSite({ page, request })
+
+ const thirtyDays = 30 * 24 * 60
+ const yesterday = 24 * 60
+
+ await populateStats({
+ request,
+ domain,
+ events: [
+ {
+ user_id: 120,
+ name: 'pageview',
+ pathname: '/products',
+ timestamp: { minutesAgo: thirtyDays + 60 }
+ },
+ {
+ user_id: 120,
+ name: 'pageview',
+ pathname: '/cart',
+ timestamp: { minutesAgo: thirtyDays + 55 }
+ },
+ {
+ user_id: 120,
+ name: 'pageview',
+ pathname: '/checkout',
+ timestamp: { minutesAgo: thirtyDays + 50 }
+ },
+ {
+ user_id: 121,
+ name: 'pageview',
+ pathname: '/products',
+ timestamp: { minutesAgo: thirtyDays + 55 }
+ },
+ {
+ user_id: 121,
+ name: 'pageview',
+ pathname: '/cart',
+ timestamp: { minutesAgo: thirtyDays + 50 }
+ },
+ {
+ user_id: 123,
+ name: 'pageview',
+ pathname: '/products',
+ timestamp: { minutesAgo: yesterday + 60 }
+ },
+ {
+ user_id: 123,
+ name: 'pageview',
+ pathname: '/cart',
+ timestamp: { minutesAgo: yesterday + 55 }
+ },
+ {
+ user_id: 123,
+ name: 'pageview',
+ pathname: '/checkout',
+ timestamp: { minutesAgo: yesterday + 50 }
+ },
+ {
+ user_id: 124,
+ name: 'pageview',
+ pathname: '/products',
+ timestamp: { minutesAgo: yesterday + 55 }
+ },
+ {
+ user_id: 124,
+ name: 'pageview',
+ pathname: '/cart',
+ timestamp: { minutesAgo: yesterday + 50 }
+ },
+ {
+ user_id: 125,
+ name: 'pageview',
+ pathname: '/products',
+ timestamp: { minutesAgo: yesterday + 50 }
+ }
+ ]
+ })
+
+ await addPageviewGoal({ page, domain, pathname: '/products' })
+ await addPageviewGoal({ page, domain, pathname: '/cart' })
+ await addPageviewGoal({ page, domain, pathname: '/checkout' })
+
+ await addFunnel({
+ request,
+ domain,
+ name: `Shopping Funnel`,
+ steps: ['Visit /products', 'Visit /cart', 'Visit /checkout']
+ })
+
+ await page.goto('/' + domain, { waitUntil: 'commit' })
+
+ const funnelsTabButton = tabButtonWithDropdown(report, 'Funnels')
+
+ await test.step('rendering funnels', async () => {
+ await funnelsTabButton.click()
+ await report.getByTestId('report-end').scrollIntoViewIfNeeded()
+ await dropdown(report)
+ .getByRole('button', { name: 'Shopping Funnel' })
+ .click()
+
+ await expect(tabButton(funnelsTabButton, 'Funnels')).toHaveAttribute(
+ 'data-active',
+ 'true'
+ )
+
+ // enable compare
+ await page.keyboard.press('x')
+
+ await expect(report.getByRole('heading')).toHaveText('Shopping Funnel')
+
+ await expect(report.getByText('3-step funnel')).toBeVisible()
+
+ await expect(report.getByText('Sequential')).toBeVisible()
+
+ await expect(report.getByText(/Conversion rate:\s*33\.3%/)).toBeVisible()
+
+ await expect(report.getByTestId('change-arrow').first()).toHaveText('16.7%')
+
+ const steps = report.locator('[data-testid^="funnel-step-"]')
+ await expect(steps).toHaveCount(3)
+ await expect(steps.nth(0)).toContainText('Visit /products')
+ await expect(steps.nth(0)).toContainText('100% entered')
+ await expect(steps.nth(0)).toContainText('3 visitors')
+ await expect(steps.nth(0)).toContainText('2 visitors')
+ await expect(steps.nth(1)).toContainText('Visit /cart')
+ await expect(steps.nth(1)).toContainText('66.7% continued')
+ await expect(steps.nth(1)).toContainText('100% continued')
+ await expect(steps.nth(1)).toContainText('2 visitors')
+ await expect(steps.nth(2)).toContainText('Visit /checkout')
+ await expect(steps.nth(2)).toContainText('33.3%')
+ await expect(steps.nth(2)).toContainText('50% converted')
+ })
+})
diff --git a/extra/lib/plausible/stats/funnel.ex b/extra/lib/plausible/stats/funnel.ex
index 19b6b04797..3b8925bc4a 100644
--- a/extra/lib/plausible/stats/funnel.ex
+++ b/extra/lib/plausible/stats/funnel.ex
@@ -14,7 +14,7 @@ defmodule Plausible.Stats.Funnel do
import Plausible.Stats.Util, only: [percentage: 2]
alias Plausible.ClickhouseRepo
- alias Plausible.Stats.{Base, Query}
+ alias Plausible.Stats.{Base, Comparisons, DateTimeRange, Query}
@spec funnel(Plausible.Site.t(), Plausible.Stats.Query.t(), Funnel.t() | pos_integer()) ::
{:ok, map()} | {:error, :funnel_not_found}
@@ -29,6 +29,29 @@ defmodule Plausible.Stats.Funnel do
end
def funnel(_site, query, %Funnel{} = funnel) do
+ comparison =
+ if query.comparison_utc_time_range do
+ query
+ |> Comparisons.get_comparison_query()
+ |> compute(funnel)
+ end
+
+ {:ok,
+ query
+ |> compute(funnel)
+ |> Map.merge(%{
+ name: funnel.name,
+ strict_order: funnel.strict_order,
+ comparison: comparison,
+ date_range: tz_date_range(query.utc_time_range, query.timezone),
+ comparison_date_range:
+ if(query.comparison_utc_time_range,
+ do: tz_date_range(query.comparison_utc_time_range, query.timezone)
+ )
+ })}
+ end
+
+ defp compute(query, funnel) do
goals = Enum.map(funnel.steps, & &1.goal)
funnel_data =
@@ -53,17 +76,14 @@ defmodule Plausible.Stats.Funnel do
visitors_at_first_step = List.first(steps).visitors
- {:ok,
- %{
- name: funnel.name,
- strict_order: funnel.strict_order,
- steps: steps,
- all_visitors: all_visitors,
- entering_visitors: visitors_at_first_step,
- entering_visitors_percentage: percentage(visitors_at_first_step, all_visitors),
- never_entering_visitors: all_visitors - visitors_at_first_step,
- never_entering_visitors_percentage: percentage(not_entering_visitors, all_visitors)
- }}
+ %{
+ steps: steps,
+ all_visitors: all_visitors,
+ entering_visitors: visitors_at_first_step,
+ entering_visitors_percentage: percentage(visitors_at_first_step, all_visitors),
+ never_entering_visitors: all_visitors - visitors_at_first_step,
+ never_entering_visitors_percentage: percentage(not_entering_visitors, all_visitors)
+ }
end
defp funnel_query(query, funnel_definition) do
@@ -169,4 +189,9 @@ defmodule Plausible.Stats.Funnel do
|> elem(2)
|> Enum.reverse()
end
+
+ defp tz_date_range(utc_time_range, timezone) do
+ range = DateTimeRange.to_date_range(utc_time_range, timezone)
+ [range.first, range.last]
+ end
end
diff --git a/test/plausible_web/controllers/api/stats_controller/funnels_test.exs b/test/plausible_web/controllers/api/stats_controller/funnels_test.exs
index a54dce3162..7070dbdde1 100644
--- a/test/plausible_web/controllers/api/stats_controller/funnels_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/funnels_test.exs
@@ -37,6 +37,7 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest do
assert %{
"name" => "Test funnel",
"strict_order" => false,
+ "comparison" => nil,
"all_visitors" => 3,
"entering_visitors" => 2,
"entering_visitors_percentage" => "66.67",
@@ -264,6 +265,122 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest do
end
end
+ describe "GET /api/stats/funnel - comparisons" do
+ setup [:create_user, :log_in, :create_site]
+
+ @comparison_stats [
+ # 2021-01-02: one visitor reaches Signup
+ {"/blog/announcement", @user_id, ~N[2021-01-02 12:00:00]},
+ {"Signup", @user_id, ~N[2021-01-02 12:01:00]},
+ # 2021-01-01: two visitors enter, one reaches Signup
+ {"/blog/announcement", @user_id, ~N[2021-01-01 12:00:00]},
+ {"/blog/announcement", @other_user_id, ~N[2021-01-01 13:00:00]},
+ {"Signup", @other_user_id, ~N[2021-01-01 13:01:00]}
+ ]
+
+ defp populate_comparison_stats(site) do
+ populate_stats(
+ site,
+ Enum.map(@comparison_stats, fn
+ {"/" <> _ = pathname, user_id, timestamp} ->
+ build(:pageview, pathname: pathname, user_id: user_id, timestamp: timestamp)
+
+ {name, user_id, timestamp} ->
+ build(:event, name: name, user_id: user_id, timestamp: timestamp)
+ end)
+ )
+ end
+
+ test "gives no comparison without a comparison param", %{conn: conn, site: site} do
+ {:ok, funnel} = setup_funnel(site, @build_funnel_with)
+ populate_comparison_stats(site)
+
+ resp =
+ conn
+ |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day&date=2021-01-02")
+ |> json_response(200)
+
+ assert resp["comparison"] == nil
+ assert resp["comparison_date_range"] == nil
+ assert resp["date_range"] == ["2021-01-02", "2021-01-02"]
+ end
+
+ test "compares against the previous period", %{conn: conn, site: site} do
+ {:ok, funnel} = setup_funnel(site, @build_funnel_with)
+ populate_comparison_stats(site)
+
+ resp =
+ conn
+ |> get(
+ "/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day&date=2021-01-02&comparison=previous_period"
+ )
+ |> json_response(200)
+
+ assert %{
+ "all_visitors" => 1,
+ "entering_visitors" => 1,
+ "date_range" => ["2021-01-02", "2021-01-02"],
+ "comparison_date_range" => ["2021-01-01", "2021-01-01"],
+ "steps" => [
+ %{"label" => "Visit /blog/announcement", "visitors" => 1},
+ %{"label" => "Signup", "visitors" => 1, "conversion_rate" => "100"},
+ %{"label" => "Visit /cart/add/product", "visitors" => 0},
+ %{"label" => "Purchase", "visitors" => 0}
+ ],
+ "comparison" => %{
+ "all_visitors" => 2,
+ "entering_visitors" => 2,
+ "entering_visitors_percentage" => "100",
+ "never_entering_visitors" => 0,
+ "never_entering_visitors_percentage" => "0",
+ "steps" => [
+ %{
+ "label" => "Visit /blog/announcement",
+ "visitors" => 2,
+ "conversion_rate" => "100"
+ },
+ %{
+ "label" => "Signup",
+ "visitors" => 1,
+ "conversion_rate" => "50",
+ "dropoff" => 1,
+ "dropoff_percentage" => "50"
+ },
+ %{"label" => "Visit /cart/add/product", "visitors" => 0},
+ %{"label" => "Purchase", "visitors" => 0}
+ ]
+ }
+ } = resp
+ end
+
+ test "compares against a custom period", %{conn: conn, site: site} do
+ {:ok, funnel} = setup_funnel(site, @build_funnel_with)
+ populate_comparison_stats(site)
+
+ resp =
+ conn
+ |> get(
+ "/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day&date=2021-01-02&comparison=custom&compare_from=2021-01-01&compare_to=2021-01-01"
+ )
+ |> json_response(200)
+
+ assert %{
+ "date_range" => ["2021-01-02", "2021-01-02"],
+ "comparison_date_range" => ["2021-01-01", "2021-01-01"],
+ "comparison" => %{
+ "all_visitors" => 2,
+ "entering_visitors" => 2,
+ "steps" => [
+ %{"visitors" => 2},
+ %{"visitors" => 1},
+ %{"visitors" => 0},
+ %{"visitors" => 0}
+ ]
+ }
+ } = resp
+ end
+ end
+
describe "GET /api/stats/funnel - disallowed filters" do
setup [:create_user, :log_in, :create_site]