Skip to content

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

Improve funnel layout (#6603)

Sanne de Vriesfc761fa2c8b6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef0c06af98..c19b2dc5f1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -43,6 +43,7 @@ All notable changes to this project will be documented in this file.
- Redesigned onboarding pages (add site, installation)
- Moved tracking options (outbound links, file downloads, form submissions) from the installation page to the general site settings, where they can be toggled without going through the installation flow
- Replaced HCaptcha with Friendly Captcha
+- Redesigned funnel report on dashboard to be more consistent with the rest of the UI. It now includes a `Strict`/`Sequential` label, and percentage drop-off between individual funnel steps is now visible by default.
### Fixed
diff --git a/assets/js/dashboard/components/feature-preview-mocks.tsx b/assets/js/dashboard/components/feature-preview-mocks.tsx
index 3346019628..5362c68c73 100644
--- a/assets/js/dashboard/components/feature-preview-mocks.tsx
+++ b/assets/js/dashboard/components/feature-preview-mocks.tsx
@@ -26,34 +26,29 @@ export function PropertiesPreviewMock() {
}
export function FunnelsPreviewMock() {
- const steps = [{ visitors: 100 }, { visitors: 55 }, { visitors: 24 }]
+ const steps = [100, 55, 32, 12]
return (
- <div className="size-full flex flex-col pt-5">
- <div className="h-4 w-32 bg-gray-400/60 dark:bg-gray-600 rounded-md mb-8" />
-
- <div className="flex-1 flex items-end justify-between lg:justify-around gap-6">
- {steps.map((step, i) => (
+ <div className="size-full flex flex-col gap-4 pt-4">
+ <div className="flex-1 flex gap-4">
+ {steps.map((fill, i) => (
<div
key={i}
- className="relative h-full flex-1 max-w-[160px] flex flex-col justify-end rounded-md overflow-hidden"
+ className={classNames(
+ 'flex-1 flex-col rounded-lg border border-gray-400 dark:border-gray-500 overflow-hidden',
+ i === 3 ? 'hidden lg:flex' : 'flex'
+ )}
>
- <div
- className="w-full bg-indigo-100 dark:bg-gray-700"
- style={{ height: `${100 - step.visitors}%` }}
- />
- <div
- className="w-full bg-indigo-500"
- style={{ height: `${step.visitors}%` }}
- />
- </div>
- ))}
- </div>
-
- <div className="flex justify-around gap-6 pt-4 pb-2">
- {steps.map((_, i) => (
- <div key={i} className="flex-1 max-w-[160px] flex justify-center">
- <div className="h-3 w-3/5 bg-gray-400/70 dark:bg-gray-600 rounded-md" />
+ <div className="flex flex-col gap-3 px-3 pt-3 pb-5">
+ <div className="h-3 w-24 bg-gray-400/70 dark:bg-gray-500/80 rounded" />
+ <div className="h-3 w-12 bg-gray-400/70 dark:bg-gray-500/80 rounded" />
+ </div>
+ <div className="relative flex-1">
+ <div
+ className="absolute inset-x-0 rounded-lg bottom-0 bg-indigo-200/70 dark:bg-indigo-500/30"
+ style={{ height: `${fill}%` }}
+ />
+ </div>
</div>
))}
</div>
diff --git a/assets/js/dashboard/extra/exploration/index.tsx b/assets/js/dashboard/extra/exploration/index.tsx
index f0ee0403d6..f7c9725ffc 100644
--- a/assets/js/dashboard/extra/exploration/index.tsx
+++ b/assets/js/dashboard/extra/exploration/index.tsx
@@ -5,7 +5,7 @@ import { useSiteContext } from '../../site-context'
import { useDashboardStateContext } from '../../dashboard-state-context'
import {
numberShortFormatter,
- percentageFormatter
+ rateFormatter
} from '../../util/number-formatter'
import { RefreshIcon } from '../../components/icons'
import { popover } from '../../components/popover'
@@ -134,7 +134,7 @@ export function FunnelExploration() {
<div className="order-last sm:order-none w-full sm:w-auto flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
<span>
<span className="font-medium sm:font-semibold text-gray-700 dark:text-gray-200">
- CR: {percentageFormatter(Number(overallConversionRate!))}{' '}
+ CR: {rateFormatter(overallConversionRate)}{' '}
</span>
<span className="text-gray-500 dark:text-gray-400">
({numberShortFormatter(overallConversionVisitors!)})
@@ -201,7 +201,7 @@ export function FunnelExploration() {
funnel[i]?.conversion_rate != null
? i === 0
? '100%'
- : `${Number(funnel[i].conversion_rate).toFixed(1)}%`
+ : rateFormatter(funnel[i].conversion_rate)
: null
if (isActive && steps.length >= maxJourneySteps) {
diff --git a/assets/js/dashboard/extra/funnel-tooltip.js b/assets/js/dashboard/extra/funnel-tooltip.js
deleted file mode 100644
index d9d804ac46..0000000000
--- a/assets/js/dashboard/extra/funnel-tooltip.js
+++ /dev/null
@@ -1,65 +0,0 @@
-function escapeHTML(str) {
- const div = document.createElement('div')
- div.appendChild(document.createTextNode(str))
- return div.innerHTML
-}
-
-export default function FunnelTooltip(palette, funnel) {
- return (context) => {
- const tooltipModel = context.tooltip
- const dataIndex = tooltipModel.dataPoints[0].dataIndex
- const offset = document.getElementById('funnel').getBoundingClientRect()
- let tooltipEl = document.getElementById('chartjs-tooltip-funnel')
-
- if (!tooltipEl) {
- tooltipEl = document.createElement('div')
- tooltipEl.id = 'chartjs-tooltip-funnel'
- tooltipEl.style.display = 'none'
- tooltipEl.style.opacity = 0
- document.body.appendChild(tooltipEl)
- }
-
- tooltipEl.className =
- 'absolute text-sm font-normal py-3 px-4 pointer-events-none rounded-md z-[100] bg-gray-950'
-
- if (tooltipEl && offset) {
- tooltipEl.style.opacity = 1
- }
-
- if (tooltipModel.opacity === 0) {
- tooltipEl.style.display = 'none'
- return
- }
-
- if (tooltipModel.body) {
- const currentStep = funnel.steps[dataIndex]
- const previousStep = dataIndex > 0 ? funnel.steps[dataIndex - 1] : null
-
- tooltipEl.innerHTML = `
- <aside class="text-gray-100 flex flex-col gap-2">
- <div class="flex items-center gap-3 font-semibold">${previousStep ? `<span>${escapeHTML(previousStep.label)}</span>` : ''}
- <span class="text-gray-400">→</span>
- ${escapeHTML(tooltipModel.title)}
- </div>
- <hr class="border-gray-750" />
- <div class="grid grid-cols-[1fr_auto_auto] items-center gap-y-1 gap-x-4">
- <span class="flex items-center gap-2">
- <span class="size-2 rounded-full ${palette.visitorsLegendClass}"></span>
- ${dataIndex == 0 ? 'Entered the funnel' : 'Visitors'}
- </span>
- <span class="text-right font-semibold">${dataIndex == 0 ? funnel.entering_visitors.toLocaleString() : currentStep.visitors.toLocaleString()}</span>
- <span class="text-right text-gray-400">${dataIndex == 0 ? funnel.entering_visitors_percentage : currentStep.conversion_rate_step}%</span>
-
- <span class="flex items-center gap-2">
- <span class="size-2 rounded-full ${palette.dropoffLegendClass}"></span>
- ${dataIndex == 0 ? 'Never entered the funnel' : 'Dropoff'}
- </span>
- <span class="text-right font-semibold">${dataIndex == 0 ? funnel.never_entering_visitors.toLocaleString() : currentStep.dropoff.toLocaleString()}</span>
- <span class="text-right text-gray-400">${dataIndex == 0 ? funnel.never_entering_visitors_percentage : currentStep.dropoff_percentage}%</span>
- </div>
- </aside >
- `
- }
- tooltipEl.style.display = null
- }
-}
diff --git a/assets/js/dashboard/extra/funnel.js b/assets/js/dashboard/extra/funnel.js
deleted file mode 100644
index b3987c31df..0000000000
--- a/assets/js/dashboard/extra/funnel.js
+++ /dev/null
@@ -1,417 +0,0 @@
-import React, { useEffect, useState, useRef } from 'react'
-import FlipMove from 'react-flip-move'
-import Chart from 'chart.js/auto'
-import FunnelTooltip from './funnel-tooltip'
-import ChartDataLabels from 'chartjs-plugin-datalabels'
-import { numberShortFormatter } from '../util/number-formatter'
-import Bar from '../stats/bar'
-
-import RocketIcon from '../stats/modals/rocket-icon'
-
-import * as api from '../api'
-import LazyLoader from '../components/lazy-loader'
-import { useDashboardStateContext } from '../dashboard-state-context'
-import { useSiteContext } from '../site-context'
-import { UIMode, useTheme } from '../theme-context'
-
-const getPalette = (theme) => {
- if (theme.mode === UIMode.dark) {
- return {
- dataLabelBackground: 'rgb(9, 9, 11)',
- dataLabelTextColor: 'rgb(244, 244, 245)',
- visitorsBackground: 'rgb(99, 102, 241)',
- dropoffBackground: 'rgb(63, 63, 70)',
- dropoffStripes: 'rgb(9, 9, 11)',
- stepNameLegendColor: 'rgb(228, 228, 231)',
- visitorsLegendClass: 'bg-indigo-500',
- dropoffLegendClass: 'bg-gray-600',
- smallBarClass: 'bg-indigo-500'
- }
- } else {
- return {
- dataLabelBackground: 'rgb(39, 39, 42)',
- dataLabelTextColor: 'rgb(244, 244, 245)',
- visitorsBackground: 'rgb(99, 102, 241)',
- dropoffBackground: 'rgb(224, 231, 255)',
- dropoffStripes: 'rgb(255, 255, 255)',
- stepNameLegendColor: 'rgb(24, 24, 27)',
- visitorsLegendClass: 'bg-indigo-500',
- dropoffLegendClass: 'bg-indigo-100',
- smallBarClass: 'bg-indigo-300'
- }
- }
-}
-
-export default function Funnel({ funnelName, tabs }) {
- const site = useSiteContext()
- const { dashboardState } = useDashboardStateContext()
- const [loading, setLoading] = useState(true)
- const [visible, setVisible] = useState(false)
- const [error, setError] = useState(undefined)
- const [funnel, setFunnel] = useState(null)
- const [isSmallScreen, setSmallScreen] = useState(false)
- const theme = useTheme()
- const chartRef = useRef(null)
- const canvasRef = useRef(null)
-
- useEffect(() => {
- if (visible) {
- setLoading(true)
- fetchFunnel()
- .then((res) => {
- setFunnel(res)
- setError(undefined)
- })
- .catch((error) => {
- setError(error)
- })
- .finally(() => {
- setLoading(false)
- })
-
- return () => {
- if (chartRef.current) {
- chartRef.current.destroy()
- }
- }
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [dashboardState, funnelName, visible, isSmallScreen])
-
- useEffect(() => {
- if (canvasRef.current && funnel && visible && !isSmallScreen) {
- initialiseChart(getPalette(theme))
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [funnel, visible, theme])
-
- useEffect(() => {
- const mediaQuery = window.matchMedia('(max-width: 768px)')
- setSmallScreen(mediaQuery.matches)
- const handleScreenChange = (e) => {
- setSmallScreen(e.matches)
- }
- mediaQuery.addEventListener('change', handleScreenChange)
- return () => {
- mediaQuery.removeEventListener('change', handleScreenChange)
- }
- }, [])
-
- const repositionFunnelTooltip = (e) => {
- const tooltipEl = document.getElementById('chartjs-tooltip-funnel')
- if (tooltipEl && window.innerWidth >= 768) {
- if (e.clientX > 0.66 * window.innerWidth) {
- tooltipEl.style.right =
- window.innerWidth - e.clientX + window.pageXOffset + 'px'
- tooltipEl.style.left = null
- } else {
- tooltipEl.style.right = null
- tooltipEl.style.left = e.clientX + window.pageXOffset + 'px'
- }
- tooltipEl.style.top = e.clientY + window.pageYOffset + 'px'
- tooltipEl.style.opacity = 1
- }
- }
-
- useEffect(() => {
- window.addEventListener('mousemove', repositionFunnelTooltip)
- return () => {
- window.removeEventListener('mousemove', repositionFunnelTooltip)
- }
- }, [])
-
- const formatDataLabel = (visitors, ctx) => {
- if (ctx.dataset.label === 'Visitors') {
- const conversionRate = funnel.steps[ctx.dataIndex].conversion_rate
- return `${conversionRate}% \n(${numberShortFormatter(visitors)} Visitors)`
- } else {
- return null
- }
- }
-
- const calcOffset = (ctx) => {
- const conversionRate = parseFloat(
- funnel.steps[ctx.dataIndex].conversion_rate
- )
- if (conversionRate > 90) {
- return -64
- } else if (conversionRate > 20) {
- return -28
- } else {
- return 8
- }
- }
-
- const getFunnel = () => {
- return site.funnels.find((funnel) => funnel.name === funnelName)
- }
-
- const fetchFunnel = async () => {
- const funnelMeta = getFunnel()
- if (typeof funnelMeta === 'undefined') {
- throw new Error('Could not fetch the funnel. Perhaps it was deleted?')
- } else {
- return api.get(
- `/api/stats/${encodeURIComponent(site.domain)}/funnels/${funnelMeta.id}`,
- dashboardState
- )
- }
- }
-
- const initialiseChart = (palette) => {
- if (chartRef.current) {
- chartRef.current.destroy()
- }
-
- const createDiagonalPattern = (color1, color2) => {
- // create a 10x10 px canvas for the pattern's base shape
- let shape = document.createElement('canvas')
- shape.width = 10
- shape.height = 10
- let c = shape.getContext('2d')
-
- c.fillStyle = color1
- c.strokeStyle = color2
- c.fillRect(0, 0, shape.width, shape.height)
-
- c.beginPath()
- c.moveTo(2, 0)
- c.lineTo(10, 8)
- c.stroke()
-
- c.beginPath()
- c.moveTo(0, 8)
- c.lineTo(2, 10)
- c.stroke()
-
- return c.createPattern(shape, 'repeat')
- }
-
- const labels = funnel.steps.map((step) => step.label)
- const stepData = funnel.steps.map((step) => step.visitors)
-
- const dropOffData = funnel.steps.map((step) => step.dropoff)
- const ctx = canvasRef.current.getContext('2d')
-
- const calcBarThickness = (ctx) => {
- if (ctx.dataset.data.length <= 3) {
- return 160
- } else {
- return Math.floor(650 / ctx.dataset.data.length)
- }
- }
-
- // passing those verbatim to make sure canvas rendering picks them up
- var fontFamily =
- 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'
-
- var gradient = ctx.createLinearGradient(900, 0, 900, 900)
- gradient.addColorStop(1, palette.dropoffBackground)
- gradient.addColorStop(0, palette.visitorsBackground)
-
- const data = {
- labels: labels,
- datasets: [
- {
- label: 'Visitors',
- data: stepData,
- backgroundColor: gradient,
- hoverBackgroundColor: gradient,
- borderRadius: 4,
- stack: 'Stack 0'
- },
- {
- label: 'Dropoff',
- data: dropOffData,
- backgroundColor: createDiagonalPattern(
- palette.dropoffBackground,
- palette.dropoffStripes
- ),
- hoverBackgroundColor: palette.dropoffBackground,
- borderRadius: 4,
- stack: 'Stack 0'
- }
- ]
- }
-
- const config = {
- plugins: [ChartDataLabels],
- type: 'bar',
- data: data,
- options: {
- responsive: true,
- barThickness: calcBarThickness,
- plugins: {
- legend: {
- display: false
- },
- tooltip: {
- enabled: false,
- mode: 'index',
- intersect: true,
- position: 'average',
- external: FunnelTooltip(palette, funnel)
- },
- datalabels: {
- formatter: formatDataLabel,
- anchor: 'end',
- align: 'end',
- offset: calcOffset,
- backgroundColor: palette.dataLabelBackground,
- color: palette.dataLabelTextColor,
- borderRadius: 4,
- clip: true,
- font: {
- size: 12,
- weight: 'normal',
- lineHeight: 1.6,
- family: fontFamily
- },
- textAlign: 'center',
- padding: { top: 8, bottom: 8, right: 8, left: 8 }
- }
- },
- scales: {
- y: { display: false },
- x: {
- position: 'bottom',
- display: true,
- border: { display: false },
- grid: { drawBorder: false, display: false },
- ticks: {
- padding: 8,
- font: { weight: 'bold', family: fontFamily, size: 14 },
- color: palette.stepNameLegendColor
- }
- }
- }
- }
- }
-
- chartRef.current = new Chart(ctx, config)
- }
-
- const header = () => {
- return (
- <div className="flex justify-between w-full">
- <h4 className="mt-2 text-base font-semibold dark:text-gray-100">
- {funnelName}
- </h4>
- {tabs}
- </div>
- )
- }
-
- const renderError = () => {
- if (error.name === 'AbortError') return
- if (error.payload && error.payload.level === 'normal') {
- return (
- <>
- {header()}
- <div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">
- {error.message}
- </div>
- </>
- )
- } else {
- return (
- <>
- {header()}
- <div className="text-center text-gray-900 dark:text-gray-100 mt-16">
- <RocketIcon />
- <div className="text-lg font-bold">Oops! Something went wrong</div>
- <div className="text-lg">
- {error.message ? error.message : 'Failed to render funnel'}
- </div>
- <div className="text-xs mt-8">
- Please try refreshing your browser or selecting the funnel again.
- </div>
- </div>
- </>
- )
- }
- }
-
- const renderInner = (theme) => {
- if (loading) {
- return (
- <div className="mx-auto loading pt-44">
- <div></div>
- </div>
- )
- } else if (error) {
- return renderError()
- } else if (funnel) {
- const conversionRate =
- funnel.steps[funnel.steps.length - 1].conversion_rate
-
- return (
- <div className="mb-8">
- {header()}
- <p className="mt-0.5 text-gray-500 text-sm">
- {funnel.steps.length}-step funnel • {conversionRate}% conversion
- rate
- </p>
- {isSmallScreen && (
- <div className="mt-4">{renderBars(funnel, theme)}</div>
- )}
- </div>
- )
- }
- }
-
- const renderBar = (step, theme) => {
- const palette = getPalette(theme)
- return (
- <>
- <div className="flex items-center justify-between my-1 text-sm">
- <Bar
- count={step.visitors}
- all={funnel.steps}
- bg={palette.smallBarClass}
- maxWidthDeduction={'5rem'}
- plot={'visitors'}
- >
- <span className="flex px-2 py-1.5 group dark:text-gray-100 relative z-9 break-all">
- {step.label}
- </span>
- </Bar>
-
- <span
- className="font-medium dark:text-gray-200 w-20 text-right"
- tooltip={step.visitors.toLocaleString()}
- >
- {numberShortFormatter(step.visitors)}
- </span>
- </div>
- </>
- )
- }
-
- const renderBars = (funnel, theme) => {
- return (
- <>
- <div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500 dark:text-gray-400">
- <span>&nbsp;</span>
- <span className="text-right">
- <span className="inline-block w-20">Visitors</span>
- </span>
- </div>
- <FlipMove>
- {funnel.steps.map((step) => renderBar(step, theme))}
- </FlipMove>
- </>
- )
- }
-
- return (
- <div style={{ minHeight: '400px' }}>
- <LazyLoader onVisible={() => setVisible(true)}>
- {renderInner(theme)}
- </LazyLoader>
- {!isSmallScreen && (
- <canvas className="" id="funnel" ref={canvasRef}></canvas>
- )}
- </div>
- )
-}
diff --git a/assets/js/dashboard/extra/funnel/index.tsx b/assets/js/dashboard/extra/funnel/index.tsx
new file mode 100644
index 0000000000..17bd7a65e8
--- /dev/null
+++ b/assets/js/dashboard/extra/funnel/index.tsx
@@ -0,0 +1,330 @@
+import React, { ReactNode, useEffect, useRef, useState } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { InformationCircleIcon } from '@heroicons/react/24/outline'
+import classNames from 'classnames'
+
+import * as api from '../../api'
+import LazyLoader from '../../components/lazy-loader'
+import { DashboardState } from '../../dashboard-state'
+import { getStaleTime } from '../../hooks/api-client'
+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 { StepOutcomes } from './outcome-box'
+
+const FUNNEL_REPORT_ID = 'funnel'
+
+type FunnelQueryKey = [
+ typeof FUNNEL_REPORT_ID,
+ { dashboardState: DashboardState; funnelName: string }
+]
+
+// A longer funnel scrolls horizontally, leaving PEEK_WIDTH_PX of the next
+// column in view as a hint.
+const VISIBLE_COLUMNS = 5
+const COLUMN_GAP_REM = 1
+const PEEK_WIDTH_PX = 24
+const MIN_COLUMN_WIDTH = '12rem'
+
+const BAR_MIN_HEIGHT = '8px'
+const BAR_TOP_GAP = '0.75rem'
+
+function gridTemplateColumns(stepCount: number): string {
+ if (stepCount <= VISIBLE_COLUMNS) {
+ return `repeat(${stepCount}, minmax(${MIN_COLUMN_WIDTH}, 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}))`
+}
+
+function fillPercent(step: StepMetrics | null | undefined): number {
+ return step ? Math.max(Number(step.conversionRate), 0) : 0
+}
+
+function userFacingMessage(error: Error): string | null {
+ if (!(error instanceof api.ApiError)) {
+ return null
+ }
+
+ const { payload } = error
+ const written =
+ typeof payload === 'object' &&
+ payload !== null &&
+ 'level' in payload &&
+ payload.level === 'normal'
+
+ return written && error.message ? error.message : null
+}
+
+function StepHeader({ step }: { step: StepMetrics }): ReactNode {
+ return (
+ <>
+ <span
+ className="text-xs font-medium text-gray-700 dark:text-gray-300 truncate"
+ title={step.label}
+ >
+ {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>
+ </>
+ )
+}
+
+function StepHeaderPlaceholder(): 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" />
+ <span className="h-3 w-16 rounded-sm bg-gray-150 dark:bg-gray-800" />
+ </div>
+ )
+}
+
+function StepColumn({
+ step,
+ index,
+ finalStep,
+ previousFill
+}: {
+ step: StepMetrics | null
+ index: number
+ finalStep: boolean
+ previousFill: number
+}): ReactNode {
+ const fill = fillPercent(step)
+
+ return (
+ <div
+ data-testid={`funnel-step-${index}`}
+ className="group/step 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} />}
+ </div>
+
+ <div className="relative flex-1 min-h-56">
+ <span
+ 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})`
+ }}
+ />
+ <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}
+ entryStep={index === 0}
+ finalStep={finalStep}
+ />
+ )}
+ </div>
+ </div>
+ )
+}
+
+function FunnelHeader({
+ funnelName,
+ funnel,
+ loading
+}: {
+ funnelName: string
+ funnel: FunnelResponse | null
+ loading: boolean
+}): ReactNode {
+ const lastStep = funnel ? funnel.steps[funnel.steps.length - 1] : null
+
+ return (
+ <div className="sm:h-7 flex flex-wrap items-center gap-x-3">
+ <h4
+ data-testid="funnel-title"
+ className="flex-1 text-sm font-semibold dark:text-gray-100"
+ >
+ {funnelName}
+ </h4>
+
+ {!funnel && loading && (
+ <div className="w-full sm:w-auto flex items-center gap-2 sm:gap-3 animate-pulse">
+ <span className="h-3 w-28 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>
+ )}
+
+ {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>
+
+ <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)}
+ </span>
+ </span>
+ </div>
+ )}
+ </div>
+ )
+}
+
+export default function Funnel({
+ funnelName
+}: {
+ funnelName: string
+}): ReactNode {
+ const site = useSiteContext()
+ const { dashboardState } = useDashboardStateContext()
+ const [visible, setVisible] = useState(false)
+ const containerRef = useRef<HTMLDivElement>(null)
+ const funnelMeta = site.funnels.find(({ name }) => name === funnelName)
+
+ const {
+ data: funnel,
+ error,
+ isPending: loading
+ } = useQuery<FunnelResponse, Error, FunnelResponse, FunnelQueryKey>({
+ queryKey: [FUNNEL_REPORT_ID, { dashboardState, funnelName }],
+ enabled: visible,
+ retry: false,
+ queryFn: ({ queryKey }) => {
+ if (typeof funnelMeta === 'undefined') {
+ throw new Error('Could not fetch the funnel. Perhaps it was deleted?')
+ }
+
+ return api.get(
+ `/api/stats/${encodeURIComponent(site.domain)}/funnels/${funnelMeta.id}`,
+ queryKey[1].dashboardState
+ )
+ },
+ placeholderData: (previousData) => previousData,
+ staleTime: ({ queryKey }) => {
+ return getStaleTime({
+ siteTimezoneOffset: site.offset,
+ siteStatsBegin: site.statsBegin,
+ ...queryKey[1].dashboardState
+ })
+ }
+ })
+
+ useEffect(() => {
+ if (containerRef.current) {
+ containerRef.current.scrollLeft = 0
+ }
+ }, [funnelName])
+
+ function renderError(error: Error): ReactNode {
+ if (error.name === 'AbortError') {
+ return null
+ }
+
+ const message = userFacingMessage(error)
+
+ return (
+ <div className="flex-1 flex flex-col items-center justify-center text-center gap-1">
+ <div className="text-base font-semibold text-gray-900 dark:text-gray-100">
+ {message
+ ? 'This funnel can’t be shown'
+ : 'This funnel couldn’t be loaded'}
+ </div>
+ <div className="text-sm text-gray-500 dark:text-gray-400">
+ {message ?? 'Refresh the page to try again.'}
+ </div>
+ </div>
+ )
+ }
+
+ function renderContent(): ReactNode {
+ if (error) {
+ return renderError(error)
+ }
+
+ const columns: (StepMetrics | null)[] = funnel
+ ? stepMetrics(funnel)
+ : new Array(funnelMeta?.steps_count || VISIBLE_COLUMNS).fill(null)
+
+ return (
+ <div
+ ref={containerRef}
+ data-testid="funnel-steps"
+ 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)
+ }}
+ >
+ {columns.map((step, index) => (
+ <StepColumn
+ key={`${funnelName}-${index}`}
+ step={step}
+ index={index}
+ finalStep={index === columns.length - 1}
+ previousFill={fillPercent(columns[index - 1])}
+ />
+ ))}
+ </div>
+ )
+ }
+
+ return (
+ <LazyLoader onVisible={() => setVisible(true)}>
+ <div className="flex-1 flex flex-col gap-8 pt-4">
+ <FunnelHeader
+ funnelName={funnelName}
+ funnel={error ? null : (funnel ?? null)}
+ loading={loading && !error}
+ />
+ {renderContent()}
+ </div>
+ </LazyLoader>
+ )
+}
diff --git a/assets/js/dashboard/extra/funnel/metrics.test.ts b/assets/js/dashboard/extra/funnel/metrics.test.ts
new file mode 100644
index 0000000000..c2f8b129f7
--- /dev/null
+++ b/assets/js/dashboard/extra/funnel/metrics.test.ts
@@ -0,0 +1,80 @@
+import { FunnelResponse, stepMetrics } from './metrics'
+
+const funnel: FunnelResponse = {
+ name: 'Checkout',
+ strict_order: false,
+ all_visitors: 250,
+ entering_visitors: 100,
+ entering_visitors_percentage: '40',
+ never_entering_visitors: 150,
+ never_entering_visitors_percentage: '60',
+ steps: [
+ {
+ label: 'Visit /products',
+ visitors: 100,
+ dropoff: 0,
+ dropoff_percentage: '0',
+ conversion_rate: '100',
+ conversion_rate_step: '100'
+ },
+ {
+ label: 'Add to cart',
+ visitors: 60,
+ dropoff: 40,
+ dropoff_percentage: '40',
+ conversion_rate: '60',
+ conversion_rate_step: '60'
+ },
+ {
+ label: 'Purchase',
+ visitors: 15,
+ dropoff: 45,
+ dropoff_percentage: '75',
+ conversion_rate: '15',
+ conversion_rate_step: '25'
+ }
+ ]
+}
+
+describe('stepMetrics()', () => {
+ it('gives one entry per step', () => {
+ expect(stepMetrics(funnel).map(({ label }) => label)).toEqual([
+ 'Visit /products',
+ 'Add to cart',
+ 'Purchase'
+ ])
+ })
+
+ it('compares the first step against everyone who saw the site', () => {
+ const [firstStep] = stepMetrics(funnel)
+
+ expect(firstStep.continued).toEqual({ visitors: 100, rate: '40' })
+ expect(firstStep.droppedOff).toEqual({ visitors: 150, rate: '60' })
+ })
+
+ it('compares a later step against the visitors of the previous step', () => {
+ const [, secondStep, thirdStep] = stepMetrics(funnel)
+
+ expect(secondStep.continued).toEqual({ visitors: 60, rate: '60' })
+ expect(secondStep.droppedOff).toEqual({ visitors: 40, rate: '40' })
+ expect(thirdStep.continued).toEqual({ visitors: 15, rate: '25' })
+ expect(thirdStep.droppedOff).toEqual({ visitors: 45, rate: '75' })
+ })
+
+ it('keeps the visitors and the conversion rate of every step', () => {
+ expect(
+ stepMetrics(funnel).map(({ visitors, conversionRate }) => [
+ visitors,
+ conversionRate
+ ])
+ ).toEqual([
+ [100, '100'],
+ [60, '60'],
+ [15, '15']
+ ])
+ })
+
+ it('gives no entries for a funnel without steps', () => {
+ expect(stepMetrics({ ...funnel, steps: [] })).toEqual([])
+ })
+})
diff --git a/assets/js/dashboard/extra/funnel/metrics.ts b/assets/js/dashboard/extra/funnel/metrics.ts
new file mode 100644
index 0000000000..881b7b890a
--- /dev/null
+++ b/assets/js/dashboard/extra/funnel/metrics.ts
@@ -0,0 +1,54 @@
+type FunnelStep = {
+ label: string
+ visitors: number
+ dropoff: number
+ dropoff_percentage: string
+ conversion_rate: string
+ conversion_rate_step: string
+}
+
+export type FunnelResponse = {
+ name: string
+ strict_order: boolean
+ steps: FunnelStep[]
+ all_visitors: number
+ entering_visitors: number
+ entering_visitors_percentage: string
+ never_entering_visitors: number
+ never_entering_visitors_percentage: string
+}
+
+type StepOutcome = {
+ visitors: number
+ rate: string
+}
+
+export type StepMetrics = {
+ label: string
+ visitors: number
+ conversionRate: string
+ continued: StepOutcome
+ droppedOff: StepOutcome
+}
+
+export function stepMetrics(funnel: FunnelResponse): StepMetrics[] {
+ return funnel.steps.map((step, index) => ({
+ label: step.label,
+ visitors: step.visitors,
+ conversionRate: step.conversion_rate,
+ continued:
+ index === 0
+ ? {
+ visitors: funnel.entering_visitors,
+ rate: funnel.entering_visitors_percentage
+ }
+ : { visitors: step.visitors, rate: step.conversion_rate_step },
+ droppedOff:
+ index === 0
+ ? {
+ visitors: funnel.never_entering_visitors,
+ rate: funnel.never_entering_visitors_percentage
+ }
+ : { visitors: step.dropoff, rate: step.dropoff_percentage }
+ }))
+}
diff --git a/assets/js/dashboard/extra/funnel/outcome-box.tsx b/assets/js/dashboard/extra/funnel/outcome-box.tsx
new file mode 100644
index 0000000000..7ebec530d8
--- /dev/null
+++ b/assets/js/dashboard/extra/funnel/outcome-box.tsx
@@ -0,0 +1,203 @@
+import React, { ReactNode, useLayoutEffect, useRef, useState } from 'react'
+import classNames from 'classnames'
+
+import { numberLongFormatter, rateFormatter } from '../../util/number-formatter'
+import { StepMetrics } 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
+// into a panel that shows the rates and visitor counts in full.
+//
+// CSS cannot transition to an automatic size, so the box cannot grow to
+// fit whichever contents are on show. Both states are therefore measured, and
+// their pixel sizes are published as CSS variables on the box. The box then
+// animates between those two sizes.
+
+const OUTCOME_INSET_PX = 4
+
+type Outcome = {
+ kind: 'continued' | 'droppedOff'
+ symbol: string
+ rate: string
+ detail: string
+ count: string
+}
+
+function stepOutcomes(
+ step: StepMetrics,
+ 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)})`
+ }
+ ]
+
+ if (!entryStep) {
+ const droppedOff = rateFormatter(step.droppedOff.rate)
+
+ outcomes.push({
+ kind: 'droppedOff',
+ symbol: '↓',
+ rate: droppedOff,
+ detail: `${droppedOff} dropped off`,
+ count: `(${numberLongFormatter(step.droppedOff.visitors)})`
+ })
+ }
+
+ return outcomes
+}
+
+function OutcomeText({
+ outcome,
+ detailed
+}: {
+ outcome: Outcome
+ detailed: boolean
+}): ReactNode {
+ const dropoff = outcome.kind === 'droppedOff'
+
+ return (
+ <span
+ className={classNames(
+ 'flex items-start gap-1 font-medium',
+ dropoff
+ ? 'text-gray-500 dark:text-gray-400'
+ : 'text-gray-900 dark:text-gray-100'
+ )}
+ >
+ <span className="font-semibold">{outcome.symbol}</span>
+ <span className="flex flex-wrap gap-x-1">
+ <span className="whitespace-nowrap">
+ {detailed ? outcome.detail : outcome.rate}
+ </span>
+ {detailed && <span className="whitespace-nowrap">{outcome.count}</span>}
+ </span>
+ </span>
+ )
+}
+
+// Publishes the size of the compact contents and the size of the expanded
+// contents on the box, as the CSS variables that its transition reads.
+function useOutcomeSize(measureKey: string) {
+ const box = useRef<HTMLButtonElement>(null)
+ const compact = useRef<HTMLDivElement>(null)
+ const expanded = useRef<HTMLDivElement>(null)
+
+ useLayoutEffect(() => {
+ const boxElement = box.current
+ const compactElement = compact.current
+ const expandedElement = expanded.current
+ const plot = boxElement?.parentElement
+
+ if (!boxElement || !compactElement || !expandedElement || !plot) {
+ return
+ }
+
+ const measure = (): void => {
+ const expandedAt = (width: string): DOMRect => {
+ expandedElement.style.width = width
+ return expandedElement.getBoundingClientRect()
+ }
+
+ // The detailed contents keep to one line while that fits the column, and
+ // wrap to their narrowest form when it does not. Each candidate is
+ // measured in the state it will really be in, so the height that comes
+ // back already accounts for the extra lines.
+ const oneLine = expandedAt('max-content')
+ const room = plot.clientWidth - 2 * OUTCOME_INSET_PX
+ const grown = oneLine.width <= room ? oneLine : expandedAt('min-content')
+ expandedElement.style.width = ''
+
+ const collapsed = compactElement.getBoundingClientRect()
+
+ boxElement.style.setProperty('--outcome-w', `${collapsed.width}px`)
+ boxElement.style.setProperty('--outcome-h', `${collapsed.height}px`)
+ boxElement.style.setProperty('--outcome-grown-w', `${grown.width}px`)
+ boxElement.style.setProperty('--outcome-grown-h', `${grown.height}px`)
+ }
+
+ measure()
+
+ // Watching the expanded element would loop, because measure resizes it.
+ const observer = new ResizeObserver(measure)
+ observer.observe(plot)
+ observer.observe(compactElement)
+
+ return () => observer.disconnect()
+ }, [measureKey])
+
+ return { box, compact, expanded }
+}
+
+export function StepOutcomes({
+ step,
+ entryStep,
+ finalStep
+}: {
+ step: StepMetrics
+ entryStep: boolean
+ finalStep: boolean
+}): ReactNode {
+ const [open, setOpen] = useState(false)
+
+ const outcomes = stepOutcomes(step, entryStep, finalStep)
+ const label = outcomes
+ .map(({ detail, count }) => `${detail} ${count}`)
+ .join(', ')
+
+ const { box, compact, expanded } = useOutcomeSize(label)
+
+ return (
+ <button
+ ref={box}
+ type="button"
+ aria-label={label}
+ data-open={open || undefined}
+ onClick={() => setOpen((shown) => !shown)}
+ style={{ left: OUTCOME_INSET_PX, bottom: OUTCOME_INSET_PX }}
+ className={classNames(
+ 'group/outcome absolute overflow-hidden rounded-md text-left cursor-default bg-white/70 dark:bg-gray-900/60 backdrop-blur-xs',
+ 'ring-1 ring-gray-900/5 dark:ring-white/10 shadow-xs',
+ '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)]',
+ '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)]'
+ )}
+ >
+ <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"
+ >
+ {outcomes.map((outcome) => (
+ <OutcomeText key={outcome.kind} outcome={outcome} detailed={false} />
+ ))}
+ </div>
+
+ <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"
+ >
+ {outcomes.map((outcome) => (
+ <OutcomeText key={outcome.kind} outcome={outcome} detailed={true} />
+ ))}
+ </div>
+ </button>
+ )
+}
diff --git a/assets/js/dashboard/util/number-formatter.test.ts b/assets/js/dashboard/util/number-formatter.test.ts
index 0721cbb38e..a733f3e611 100644
--- a/assets/js/dashboard/util/number-formatter.test.ts
+++ b/assets/js/dashboard/util/number-formatter.test.ts
@@ -1,4 +1,8 @@
-import { numberLongFormatter, numberShortFormatter } from './number-formatter'
+import {
+ numberLongFormatter,
+ numberShortFormatter,
+ rateFormatter
+} from './number-formatter'
describe('numberShortFormatter()', () => {
it('converts to short format', () => {
@@ -16,6 +20,29 @@ describe('numberShortFormatter()', () => {
})
})
+describe('rateFormatter()', () => {
+ it('formats a rate that the API sends as a decimal string', () => {
+ expect(rateFormatter('0')).toEqual('0%')
+ expect(rateFormatter('100')).toEqual('100%')
+ expect(rateFormatter('33.33')).toEqual('33.3%')
+ expect(rateFormatter('50.0')).toEqual('50%')
+ })
+
+ it('keeps two decimals for a rate that is close to an extreme', () => {
+ expect(rateFormatter('0.01')).toEqual('0.01%')
+ expect(rateFormatter('0.05')).toEqual('0.05%')
+ expect(rateFormatter('99.95')).toEqual('99.95%')
+ expect(rateFormatter('99.99')).toEqual('99.99%')
+ })
+
+ it('keeps a pair of rates apart from 0% and 100%', () => {
+ expect([rateFormatter('0.01'), rateFormatter('99.99')]).toEqual([
+ '0.01%',
+ '99.99%'
+ ])
+ })
+})
+
describe('numberLongFormatter()', () => {
it('converts to short format', () => {
expect(numberLongFormatter(0)).toEqual('0')
diff --git a/assets/js/dashboard/util/number-formatter.ts b/assets/js/dashboard/util/number-formatter.ts
index 90d138bc57..3f2c2801b3 100644
--- a/assets/js/dashboard/util/number-formatter.ts
+++ b/assets/js/dashboard/util/number-formatter.ts
@@ -82,3 +82,11 @@ export function percentageFormatter(number: number | null): string {
return '-'
}
}
+
+export function rateFormatter(rate: string): string {
+ const value = Number(rate)
+ const nearExtreme =
+ (value > 0 && value < 0.1) || (value > 99.9 && value < 100)
+
+ return Number(value.toFixed(nearExtreme ? 2 : 1)) + '%'
+}
diff --git a/assets/package-lock.json b/assets/package-lock.json
index 3e62b33100..74da5b20d9 100644
--- a/assets/package-lock.json
+++ b/assets/package-lock.json
@@ -20,8 +20,6 @@
"@tanstack/react-query": "^5.51.1",
"abortcontroller-polyfill": "^1.7.3",
"alpinejs": "^3.13.1",
- "chart.js": "^3.3.2",
- "chartjs-plugin-datalabels": "^2.2.0",
"classnames": "^2.3.1",
"d3": "^7.9.0",
"dayjs": "^1.11.7",
@@ -3612,17 +3610,6 @@
"node": ">=10"
}
},
- "node_modules/chart.js": {
- "version": "3.9.1",
- "license": "MIT"
- },
- "node_modules/chartjs-plugin-datalabels": {
- "version": "2.2.0",
- "license": "MIT",
- "peerDependencies": {
- "chart.js": ">=3.0.0"
- }
- },
"node_modules/chokidar": {
"version": "3.5.3",
"funding": [
diff --git a/assets/package.json b/assets/package.json
index f5789913cd..65b9f3cce8 100644
--- a/assets/package.json
+++ b/assets/package.json
@@ -24,8 +24,6 @@
"@tanstack/react-query": "^5.51.1",
"abortcontroller-polyfill": "^1.7.3",
"alpinejs": "^3.13.1",
- "chart.js": "^3.3.2",
- "chartjs-plugin-datalabels": "^2.2.0",
"classnames": "^2.3.1",
"d3": "^7.9.0",
"dayjs": "^1.11.7",
diff --git a/e2e/tests/dashboard/behaviours.spec.ts b/e2e/tests/dashboard/behaviours.spec.ts
index 7046baa62e..b2ac936cca 100644
--- a/e2e/tests/dashboard/behaviours.spec.ts
+++ b/e2e/tests/dashboard/behaviours.spec.ts
@@ -996,7 +996,22 @@ test('funnels', async ({ page, request }) => {
await expect(report.getByText('3-step funnel')).toBeVisible()
- await expect(report.getByText('33.33% conversion rate')).toBeVisible()
+ await expect(report.getByText('Sequential')).toBeVisible()
+
+ await expect(report.getByText(/Conversion rate:\s*33\.3%/)).toBeVisible()
+
+ 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%')
+ await expect(steps.nth(2)).toContainText('33.3%')
+
+ const outcome = steps.nth(1).getByRole('button')
+ await expect(outcome).toHaveAccessibleName(/continued .* dropped off/)
+
+ await expect(outcome).not.toHaveAttribute('data-open')
+ await outcome.click()
+ await expect(outcome).toHaveAttribute('data-open', 'true')
})
await test.step('loading more', async () => {
diff --git a/extra/lib/plausible/stats/funnel.ex b/extra/lib/plausible/stats/funnel.ex
index 39cdd3d785..19b6b04797 100644
--- a/extra/lib/plausible/stats/funnel.ex
+++ b/extra/lib/plausible/stats/funnel.ex
@@ -56,6 +56,7 @@ defmodule Plausible.Stats.Funnel do
{:ok,
%{
name: funnel.name,
+ strict_order: funnel.strict_order,
steps: steps,
all_visitors: all_visitors,
entering_visitors: visitors_at_first_step,
diff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.ex
index 51b5ebcfcf..a18a5f7bef 100644
--- a/lib/plausible_web/controllers/api/stats_controller.ex
+++ b/lib/plausible_web/controllers/api/stats_controller.ex
@@ -117,7 +117,7 @@ defmodule PlausibleWeb.Api.StatsController do
H.too_many_requests(conn, "Too many exploration requests")
{:error, :empty_journey} ->
- H.bad_request(conn, "We are unable to show funnels when journey is empty")
+ H.bad_request(conn, "Funnels aren't available when journey is empty")
{:error, :journey_too_long} ->
H.bad_request(conn, "The journey is too long")
@@ -203,7 +203,7 @@ defmodule PlausibleWeb.Api.StatsController do
{:error, {:invalid_funnel_query, due_to}} ->
H.bad_request(
conn,
- "We are unable to show funnels when the dashboard is filtered by #{due_to}",
+ "Funnels aren't available when the dashboard is filtered by #{due_to}",
%{
level: :normal
}
diff --git a/test/plausible/funnels_test.exs b/test/plausible/funnels_test.exs
index 48581ba86e..222e56a2ed 100644
--- a/test/plausible/funnels_test.exs
+++ b/test/plausible/funnels_test.exs
@@ -379,6 +379,9 @@ defmodule Plausible.FunnelsTest do
assert Enum.at(non_strict_funnel_data.steps, 2).visitors == 1
assert Enum.at(strict_funnel_data.steps, 2).visitors == 0
+
+ assert non_strict_funnel_data.strict_order == false
+ assert strict_funnel_data.strict_order == true
end
test "funnels can be evaluated even where there are no visits yet", %{
diff --git a/test/plausible_web/controllers/api/stats_controller/exploration_test.exs b/test/plausible_web/controllers/api/stats_controller/exploration_test.exs
index d5c7e4a44c..4135080a52 100644
--- a/test/plausible_web/controllers/api/stats_controller/exploration_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/exploration_test.exs
@@ -217,7 +217,7 @@ defmodule PlausibleWeb.Api.StatsController.ExplorationTest do
})
|> json_response(400)
- assert resp["error"] == "We are unable to show funnels when journey is empty"
+ assert resp["error"] == "Funnels aren't available when journey is empty"
end
test "supports backward direction", %{conn: conn, site: site} do
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 7bdee7d079..a54dce3162 100644
--- a/test/plausible_web/controllers/api/stats_controller/funnels_test.exs
+++ b/test/plausible_web/controllers/api/stats_controller/funnels_test.exs
@@ -36,6 +36,7 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest do
assert %{
"name" => "Test funnel",
+ "strict_order" => false,
"all_visitors" => 3,
"entering_visitors" => 2,
"entering_visitors_percentage" => "66.67",
@@ -78,6 +79,27 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest do
} = resp
end
+ test "computes a strict-order funnel for a day", %{conn: conn, site: site} do
+ {:ok, funnel} = setup_funnel(site, @build_funnel_with, strict_order?: true)
+
+ populate_stats(site, [
+ build(:pageview, pathname: "/blog/announcement", user_id: @user_id),
+ build(:event, name: "Signup", user_id: @user_id)
+ ])
+
+ resp =
+ conn
+ |> get("/api/stats/#{site.domain}/funnels/#{funnel.id}/?period=day")
+ |> json_response(200)
+
+ assert %{
+ "name" => "Test funnel",
+ "strict_order" => true,
+ "all_visitors" => 1,
+ "entering_visitors" => 1
+ } = resp
+ end
+
test "404 for unknown funnel", %{site: site, conn: conn} do
resp =
conn
@@ -256,8 +278,7 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest do
|> json_response(400)
assert resp == %{
- "error" =>
- "We are unable to show funnels when the dashboard is filtered by pages",
+ "error" => "Funnels aren't available when the dashboard is filtered by pages",
"level" => "normal"
}
end
@@ -274,8 +295,7 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest do
|> json_response(400)
assert resp == %{
- "error" =>
- "We are unable to show funnels when the dashboard is filtered by goals",
+ "error" => "Funnels aren't available when the dashboard is filtered by goals",
"level" => "normal"
}
end
@@ -290,7 +310,7 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest do
assert resp == %{
"error" =>
- "We are unable to show funnels when the dashboard is filtered by realtime period",
+ "Funnels aren't available when the dashboard is filtered by realtime period",
"level" => "normal"
}
end
@@ -420,9 +440,15 @@ defmodule PlausibleWeb.Api.StatsController.FunnelsTest do
{:ok, goals}
end
- defp setup_funnel(site, goal_names) do
+ defp setup_funnel(site, goal_names, opts \\ []) do
{:ok, goals} = setup_goals(site, goal_names)
- Plausible.Funnels.create(site, "Test funnel", Enum.map(goals, &%{"goal_id" => &1.id}))
+
+ Plausible.Funnels.create(
+ site,
+ "Test funnel",
+ Enum.map(goals, &%{"goal_id" => &1.id}),
+ opts
+ )
end
end
end