Skip to content

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

Improve explore tab UI (#6276)

Sanne de Vries0bf625cd32be
diff --git a/assets/js/dashboard/components/icons.tsx b/assets/js/dashboard/components/icons.tsx
index f70d27af69..5047e2b780 100644
--- a/assets/js/dashboard/components/icons.tsx
+++ b/assets/js/dashboard/components/icons.tsx
@@ -41,6 +41,68 @@ export const FilterIcon = ({ className }: { className?: string }) => (
</svg>
)
+export const RefreshIcon = ({ className }: { className?: string }) => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 18 18"
+ fill="none"
+ className={className}
+ >
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ d="M5.25 9.5L3 7.25L0.75 9.5"
+ />
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ d="M13.495 13.345C12.3587 14.5226 10.7641 15.25 9 15.25C5.548 15.25 2.75 12.45 2.75 9C2.75 8.4 2.834 7.83003 2.99 7.28003"
+ />
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ d="M12.75 8.5L15 10.75L17.25 8.5"
+ />
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ d="M4.50629 4.65564C5.64249 3.48544 7.23658 2.75 8.99998 2.75C12.452 2.75 15.25 5.55 15.25 9C15.25 9.58 15.171 10.14 15.024 10.67"
+ />
+ </svg>
+)
+
+export const CursorIcon = ({
+ className,
+ title
+}: {
+ className?: string
+ title?: string
+}) => (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ className={className}
+ >
+ {title && <title>{title}</title>}
+ <path
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ d="m4.63 3.711 15.23 5.565c.641.235.623 1.148-.028 1.358l-6.97 2.23-2.232 6.971c-.208.65-1.122.67-1.357.028L3.71 4.631a.717.717 0 0 1 .92-.92"
+ />
+ </svg>
+)
+
export const Spinner = ({ className }: { className?: string }) => (
<svg
className={className}
diff --git a/assets/js/dashboard/components/popover.tsx b/assets/js/dashboard/components/popover.tsx
index ef0bfedde3..cbe076c963 100644
--- a/assets/js/dashboard/components/popover.tsx
+++ b/assets/js/dashboard/components/popover.tsx
@@ -32,10 +32,11 @@ const panel = {
const toggleButton = {
classNames: {
- rounded:
- 'flex items-center rounded-md text-sm leading-tight h-8 transition-all duration-150',
+ rounded: 'flex items-center rounded-md text-sm leading-tight h-8',
shadow:
'bg-white dark:bg-gray-750 shadow-sm text-gray-800 dark:text-gray-200 dark:hover:bg-gray-700',
+ outline:
+ 'border border-gray-300 dark:border-gray-750 bg-white dark:bg-gray-750 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 dark:hover:border-gray-700 dark:hover:text-gray-100',
ghost:
'gap-x-1.5 px-2.5 font-medium text-gray-700 dark:text-gray-100 hover:bg-gray-150/80 dark:hover:bg-gray-800 aria-expanded:bg-gray-150/80 dark:aria-expanded:bg-gray-800',
truncatedText: 'truncate block',
diff --git a/assets/js/dashboard/extra/exploration.js b/assets/js/dashboard/extra/exploration.js
index c1bdd45b0d..63261ada3f 100644
--- a/assets/js/dashboard/extra/exploration.js
+++ b/assets/js/dashboard/extra/exploration.js
@@ -1,4 +1,10 @@
-import React, { useState, useEffect, useRef } from 'react'
+import React, {
+ useState,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useCallback
+} from 'react'
import * as api from '../api'
import * as url from '../util/url'
import { Tooltip } from '../util/tooltip'
@@ -9,6 +15,10 @@ import {
numberShortFormatter,
numberLongFormatter
} from '../util/number-formatter'
+import { RefreshIcon, CursorIcon } from '../components/icons'
+import { ChevronUpDownIcon, ChevronRightIcon } from '@heroicons/react/20/solid'
+import { FlagIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline'
+import { popover } from '../components/popover'
const PAGE_FILTER_KEYS = ['page', 'entry_page', 'exit_page']
const EXPLORATION_DIRECTIONS = {
@@ -16,6 +26,10 @@ const EXPLORATION_DIRECTIONS = {
BACKWARD: 'backward'
}
+function randomKey() {
+ return Math.random().toString()
+}
+
function stateWithApplicableFilters(dashboardState, steps) {
if (steps.length === 0) {
return dashboardState
@@ -77,6 +91,240 @@ function isSameStep(step, otherStep) {
)
}
+function truncateFrozenResultsAtIndex(frozenResults, fromIndex) {
+ const next = {}
+ Object.keys(frozenResults).forEach((key) => {
+ const idx = Number(key)
+ if (idx < fromIndex) next[idx] = frozenResults[key]
+ })
+ return next
+}
+
+function DirectionDropdown({ direction, onDirectionChange }) {
+ const [open, setOpen] = useState(false)
+ const ref = useRef(null)
+
+ useEffect(() => {
+ if (!open) return
+ function handleClickOutside(e) {
+ if (ref.current && !ref.current.contains(e.target)) setOpen(false)
+ }
+ document.addEventListener('mousedown', handleClickOutside)
+ return () => document.removeEventListener('mousedown', handleClickOutside)
+ }, [open])
+
+ const label =
+ direction === EXPLORATION_DIRECTIONS.FORWARD
+ ? 'Starting point'
+ : 'End point'
+
+ return (
+ <div ref={ref} className="relative shrink-0">
+ <button
+ onClick={() => setOpen((o) => !o)}
+ className="flex items-center gap-0.5 text-xs font-semibold text-gray-900 dark:text-gray-100 hover:text-gray-700 dark:hover:text-gray-200"
+ >
+ {label}
+ <ChevronUpDownIcon className="size-3.5 shrink-0" />
+ </button>
+ {open && (
+ <div
+ className={`absolute -left-1 top-full mt-1 z-10 min-w-40 dark:!bg-gray-900 ${popover.panel.classNames.roundedSheet}`}
+ >
+ {[
+ [EXPLORATION_DIRECTIONS.FORWARD, 'Starting point'],
+ [EXPLORATION_DIRECTIONS.BACKWARD, 'End point']
+ ].map(([value, optionLabel]) => (
+ <button
+ key={value}
+ onClick={() => {
+ onDirectionChange(value)
+ setOpen(false)
+ }}
+ className={`w-full text-left text-sm rounded-md dark:hover:!bg-gray-750 data-[selected=true]:dark:!bg-gray-750 ${popover.items.classNames.navigationLink} ${popover.items.classNames.hoverLink} ${
+ direction === value
+ ? popover.items.classNames.selectedOption
+ : ''
+ }`}
+ data-selected={direction === value}
+ >
+ {optionLabel}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
+
+// Returns the x coordinate of a column's right or left edge,
+// adjusted for the container's scroll position so it is stable
+// in SVG/document space even when the user scrolls horizontally.
+function columnEdgeX(colEl, side, containerRect, scrollLeft) {
+ const rect = colEl.getBoundingClientRect()
+ const edgeX = side === 'right' ? rect.right : rect.left
+ return edgeX - containerRect.left + scrollLeft
+}
+
+// Returns the vertical midpoint of a step row element relative to
+// the top of the scroll container (not the viewport).
+function stepRowMidY(stepRowEl, containerRect) {
+ const rect = stepRowEl.getBoundingClientRect()
+ return (rect.top + rect.bottom) / 2 - containerRect.top
+}
+
+// Builds an SVG path string for a stepped connector with rounded
+// corners between two points. The path goes: horizontal → rounded
+// corner → vertical → rounded corner → horizontal.
+function steppedPath(x1, y1, x2, y2) {
+ const mx = (x1 + x2) / 2
+ const dy = y2 - y1
+
+ if (Math.abs(dy) < 1) {
+ // Points are on the same horizontal line — plain horizontal segment.
+ return `M ${x1} ${y1} H ${x2}`
+ }
+
+ const r = Math.min(10, Math.abs(dy) / 2)
+
+ if (dy > 0) {
+ // Target is below: corners curve downward then outward.
+ return `M ${x1} ${y1} H ${mx - r} A ${r} ${r} 0 0 1 ${mx} ${y1 + r} V ${y2 - r} A ${r} ${r} 0 0 0 ${mx + r} ${y2} H ${x2}`
+ } else {
+ // Target is above: corners curve upward then outward.
+ return `M ${x1} ${y1} H ${mx - r} A ${r} ${r} 0 0 0 ${mx} ${y1 - r} V ${y2 + r} A ${r} ${r} 0 0 1 ${mx + r} ${y2} H ${x2}`
+ }
+}
+
+// Computes the clip rect that confines connectors to the list area,
+// so they don't bleed into column headers.
+function listClipRect(container, containerRect) {
+ const firstList = container.querySelector('[data-exploration-list]')
+ const listRect = firstList ? firstList.getBoundingClientRect() : null
+ return {
+ y: listRect ? listRect.top - containerRect.top : 0,
+ height: listRect ? listRect.height : container.clientHeight
+ }
+}
+
+function emptyConnectorSvgData() {
+ return {
+ paths: [],
+ width: 0,
+ height: 0,
+ clipY: 0,
+ clipHeight: 0
+ }
+}
+
+function calculateConnectors(container, steps) {
+ const containerRect = container.getBoundingClientRect()
+ const newPaths = []
+
+ const columns = container.querySelectorAll(`[data-exploration-column]`)
+ const stepRows = container.querySelectorAll(`[data-exploration-step]`)
+
+ for (let i = 0; i < steps.length - 1; i++) {
+ const colA = columns[i]
+ const colB = columns[i + 1]
+
+ const stepRowA = stepRows[i]
+ const stepRowB = stepRows[i + 1]
+
+ if (colA && stepRowA && colB && stepRowB) {
+ const x1 = columnEdgeX(colA, 'right', containerRect, container.scrollLeft)
+ const x2 = columnEdgeX(colB, 'left', containerRect, container.scrollLeft)
+ const y1 = stepRowMidY(stepRowA, containerRect)
+ const y2 = stepRowMidY(stepRowB, containerRect)
+
+ newPaths.push(steppedPath(x1, y1, x2, y2))
+ }
+ }
+
+ const clip = listClipRect(container, containerRect)
+
+ return {
+ paths: newPaths,
+ width: container.scrollWidth,
+ height: container.clientHeight,
+ clipY: clip.y,
+ clipHeight: clip.height
+ }
+}
+
+function PathConnectors({ steps, containerRef }) {
+ const [svgData, setSvgData] = useState(emptyConnectorSvgData)
+
+ const calculateCallback = useCallback(() => {
+ const container = containerRef.current
+
+ if (container) {
+ setSvgData(calculateConnectors(container, steps))
+ }
+ }, [steps, containerRef])
+
+ useLayoutEffect(() => {
+ const container = containerRef.current
+
+ if (!container || steps.length < 2) {
+ setSvgData(emptyConnectorSvgData)
+ return
+ } else {
+ setSvgData(calculateConnectors(container, steps))
+
+ const observer = new ResizeObserver(calculateCallback)
+ observer.observe(container)
+ window.addEventListener('resize', calculateCallback)
+
+ const lists = Array.from(
+ container.querySelectorAll('[data-exploration-list]')
+ )
+
+ lists.forEach((list) =>
+ list.addEventListener('scroll', calculateCallback)
+ )
+
+ return () => {
+ observer.disconnect()
+ window.removeEventListener('resize', calculateCallback)
+ lists.forEach((list) =>
+ list.removeEventListener('scroll', calculateCallback)
+ )
+ }
+ }
+ }, [steps, containerRef, calculateCallback])
+
+ if (svgData.paths.length === 0) return null
+
+ return (
+ <svg
+ className="absolute inset-0 pointer-events-none overflow-visible"
+ height={svgData.height}
+ >
+ <defs>
+ <clipPath id="exploration-list-clip">
+ <rect
+ x="0"
+ y={svgData.clipY}
+ width={svgData.width}
+ height={svgData.clipHeight}
+ />
+ </clipPath>
+ </defs>
+ {svgData.paths.map((d, i) => (
+ <path
+ key={i}
+ d={d}
+ fill="none"
+ clipPath="url(#exploration-list-clip)"
+ className="stroke-indigo-500 dark:stroke-indigo-400"
+ strokeWidth="1.5"
+ />
+ ))}
+ </svg>
+ )
+}
+
function ExplorationColumn({
header,
// null means column should not be rendered (no preceding step selected)
@@ -89,7 +337,12 @@ function ExplorationColumn({
selectedConversionRate,
onSelect,
onFilterChange,
- filter
+ filter,
+ direction,
+ onDirectionChange,
+ headerConversionRate,
+ colIndex,
+ className
}) {
const debouncedOnFilterChange = useDebounce((event) =>
onFilterChange(event.target.value)
@@ -97,62 +350,86 @@ function ExplorationColumn({
const stepMaxVisitors = maxVisitors || results[0]?.visitors
- // When a step is selected we show only that one item.
- // If the full results list has loaded and contains a matching entry we use it
- // so the bar widths are still relative to the column's data; otherwise we
- // fall back to a synthetic item built from the funnel data
- const selectedResult =
- selected && results.find(({ step }) => isSameStep(step, selected))
-
- const listItems = selected
- ? [
- selectedResult || {
- step: selected,
- visitors: selectedVisitors ?? 0
- }
- ]
- : results.slice(0, 10)
+ // When a step is selected we keep showing the full candidate list so the
+ // user can quickly switch to another option. If we don't have the candidate
+ // list (e.g. preloaded journey), fall back to a synthetic single item built
+ // from the funnel data so the column still renders the selected step.
+ const listItems =
+ selected && results.length === 0
+ ? [{ step: selected, visitors: selectedVisitors ?? 0 }]
+ : results.slice(0, 10)
return (
- <div className="min-w-80 flex-1 border border-gray-200 dark:border-gray-750 rounded-lg overflow-hidden">
- <div className="h-12 pl-4 pr-1.5 flex items-center justify-between">
- <span className="shrink-0 text-xs font-medium text-gray-500 dark:text-gray-400">
- {header}
- </span>
- {!selected && active && (
+ <div
+ data-exploration-column={colIndex}
+ className={`bg-gray-50 dark:bg-gray-850 rounded-lg overflow-hidden ${className || ''}`}
+ >
+ <div className="h-[42px] py-2 pl-4 pr-1.5 flex items-center justify-between gap-x-2">
+ {onDirectionChange ? (
+ <DirectionDropdown
+ direction={direction}
+ onDirectionChange={onDirectionChange}
+ />
+ ) : (
+ <span className="shrink-0 text-xs font-semibold text-gray-900 dark:text-gray-100">
+ {header}
+ </span>
+ )}
+ {!selected && active && (results.length > 0 || filter) && (
<input
data-testid="search-input"
type="text"
defaultValue={filter}
placeholder="Search"
onChange={debouncedOnFilterChange}
- className="peer max-w-48 w-full text-xs dark:text-gray-100 block border-gray-300 dark:border-gray-750 rounded-md dark:bg-gray-750 dark:placeholder:text-gray-400 focus:outline-none focus:ring-3 focus:ring-indigo-500/20 dark:focus:ring-indigo-500/25 focus:border-indigo-500"
+ className="peer max-w-48 w-full text-xs dark:text-gray-100 block border-gray-300 dark:border-gray-700 rounded-md dark:bg-gray-700 dark:placeholder:text-gray-400 focus:outline-none focus:ring-3 focus:ring-indigo-500/20 dark:focus:ring-indigo-500/25 focus:border-indigo-500"
/>
)}
- {selected && (
- <button
- onClick={() => onSelect(null)}
- className="pr-2.5 text-xs text-indigo-500 font-medium hover:text-indigo-700 dark:text-indigo-400 dark:hover:text-indigo-200"
- >
- Clear
- </button>
+ {headerConversionRate && (
+ <span className="shrink-0 text-xs font-semibold text-gray-900 dark:text-gray-100">
+ {headerConversionRate}
+ </span>
)}
</div>
{loading ? (
- <div className="h-112 flex items-center justify-center">
+ <div className="h-110 flex items-center justify-center">
<div className="mx-auto loading pt-4">
<div></div>
</div>
</div>
) : results.length === 0 && !selected ? (
- <div className="h-108 flex items-center justify-center text-sm text-gray-400 dark:text-gray-500">
- {!active ? 'Select an event to continue' : 'No data'}
+ <div className="h-110 flex items-center justify-center max-w-2/3 mx-auto text-center text-sm text-pretty text-gray-400 dark:text-gray-500">
+ {!active ? (
+ <span className="flex flex-col items-center gap-2">
+ <CursorIcon className="size-5" />
+ {colIndex === 1
+ ? direction === EXPLORATION_DIRECTIONS.BACKWARD
+ ? 'Select an end point to continue'
+ : 'Select a starting point to continue'
+ : 'Select an event to continue'}
+ </span>
+ ) : filter ? (
+ <span className="flex flex-col items-center gap-2">
+ <MagnifyingGlassIcon className="size-4.5" />
+ {'No events found'}
+ </span>
+ ) : (
+ <span className="flex flex-col items-center gap-2">
+ <FlagIcon className="size-4.5" />
+ {"You've reached the end of this journey"}
+ </span>
+ )}
</div>
) : (
- <ul className="flex flex-col gap-y-0.5 px-1.5 pb-1.5 h-108 overflow-y-auto">
+ <ul
+ data-exploration-list
+ className="flex flex-col gap-y-2 px-2 pb-2 h-110 overflow-y-auto [scrollbar-width:thin] [scrollbar-color:theme(colors.gray.300)_transparent] dark:[scrollbar-color:theme(colors.gray.600)_transparent]"
+ >
{listItems.map(({ step, visitors }) => {
const isSelected = !!selected && isSameStep(step, selected)
+ const isDimmed = !!selected && !isSelected
+ const isCustomEvent = step.name !== 'pageview'
const visitorsToShow =
isSelected && selectedVisitors !== null
? selectedVisitors
@@ -161,42 +438,83 @@ function ExplorationColumn({
isSelected && selectedConversionRate !== null
? selectedConversionRate
: Math.round((visitors / stepMaxVisitors) * 100)
- const label = step.includes_subpaths
- ? `${step.label}… (${numberShortFormatter(step.subpaths_count)} pages)`
- : step.label
+ const label = step.label
return (
<li key={label}>
<button
- className={`group w-full border text-left px-2.5 pt-2 pb-2.5 text-sm rounded-md focus:outline-none ${
+ data-exploration-step={isSelected ? colIndex : undefined}
+ className={`group w-full border text-left px-4 py-3 text-sm rounded-md focus:outline-none ${
isSelected
- ? 'bg-indigo-50/80 dark:bg-gray-750 border-indigo-50 dark:border-transparent'
- : 'hover:bg-gray-100 dark:hover:bg-gray-800 border-transparent'
+ ? 'bg-indigo-50 dark:bg-gray-600/70 border-indigo-100 dark:border-transparent'
+ : 'bg-white dark:bg-gray-750 border-gray-150 dark:border-gray-750'
}`}
onClick={() => onSelect(isSelected ? null : step)}
>
<div className="flex items-center justify-between gap-2 mb-1">
<span
- className="truncate font-medium text-gray-800 dark:text-gray-200"
- title={label}
+ className={`flex items-center gap-1.5 min-w-0 ${
+ isDimmed
+ ? 'text-gray-400 dark:text-gray-500'
+ : 'text-gray-900 dark:text-gray-100'
+ }`}
+ title={
+ step.includes_subpaths
+ ? `${label} > all (${step.subpaths_count})`
+ : label
+ }
>
- {label}
+ {isCustomEvent && (
+ <CursorIcon
+ title="Custom event"
+ className={`size-4 shrink-0 ${isDimmed ? 'text-gray-300 dark:text-gray-600' : 'text-gray-900 dark:text-gray-100'}`}
+ />
+ )}
+ <span className="truncate">{label}</span>
+ {step.includes_subpaths && (
+ <>
+ <ChevronRightIcon
+ className={`mt-0.5 size-3 shrink-0 ${isDimmed ? 'text-gray-400 dark:text-gray-500' : 'text-gray-500 dark:text-gray-400'}`}
+ />
+ <span
+ className={`shrink-0 ${isDimmed ? 'text-gray-400 dark:text-gray-500' : 'text-gray-500 dark:text-gray-400'}`}
+ >
+ all{' '}
+ <span className="text-[0.85rem]">
+ ({numberShortFormatter(step.subpaths_count)})
+ </span>
+ </span>
+ </>
+ )}
</span>
- <span className="shrink-0 text-gray-800 dark:text-gray-200 tabular-nums">
+ <span
+ className={`shrink-0 font-medium ${
+ isDimmed
+ ? 'text-gray-400 dark:text-gray-500'
+ : 'text-gray-800 dark:text-gray-200'
+ }`}
+ >
<Tooltip info={numberLongFormatter(visitorsToShow)}>
{numberShortFormatter(visitorsToShow)}
</Tooltip>
</span>
</div>
<div
- className={`h-1 rounded-full overflow-hidden
- ${isSelected ? 'bg-indigo-100 dark:bg-gray-700' : 'bg-indigo-100/70 dark:bg-gray-700 group-hover:bg-indigo-100 dark:group-hover:bg-gray-600'}`}
+ className={`h-1 rounded-full overflow-hidden ${
+ isSelected
+ ? 'bg-indigo-200/70 dark:bg-gray-500/60'
+ : isDimmed
+ ? 'bg-gray-150 dark:bg-gray-700'
+ : 'bg-gray-150 dark:bg-gray-600'
+ }`}
>
<div
className={`h-full rounded-full transition-[width] ease-in-out ${
isSelected
- ? 'bg-indigo-500 dark:bg-white'
- : 'bg-indigo-300 dark:bg-gray-300 group-hover:bg-indigo-400 dark:group-hover:bg-white'
+ ? 'bg-indigo-500 dark:bg-indigo-400'
+ : isDimmed
+ ? 'bg-indigo-200 dark:bg-indigo-400/30'
+ : 'bg-indigo-300 dark:bg-indigo-400/75 group-hover:bg-indigo-400 dark:group-hover:bg-indigo-400'
}`}
style={{ width: `${barWidth}%` }}
/>
@@ -233,10 +551,21 @@ export function FunnelExploration() {
const [activeColumnResults, setActiveColumnResults] = useState([])
const [activeColumnFilter, setActiveColumnFilter] = useState('')
const [activeColumnLoading, setActiveColumnLoading] = useState(false)
+ // Snapshot of candidate results at the moment a step was selected, kept per
+ // column index so previously-active columns can keep showing their full
+ // candidate list (with the selected option highlighted) instead of
+ // collapsing to a single item.
+ const [frozenColumnResults, setFrozenColumnResults] = useState({})
// Initial visitor/bar data for a newly selected step, held until
// real funnel response arrives. Prevents from flashing "0 visitors"
// during the loading window.
const [provisionalFunnelEntries, setProvisionalFunnelEntries] = useState({})
+ // Workaround for force refreshing connectors between steps
+ // when dashboardState changes. Currently the connectors
+ // logic extracts part of the state from DOM, which shouldn't be the
+ // case. It will eventually be properlu rewritten and the workaround
+ // will no longer be needed.
+ const [connectorsKey, setConnectorsKey] = useState(randomKey)
// Tracks the steps/direction/dashboardState values from the previous effect
// run so we can tell whether the journey changed (needs funnel) or only the
// search filter changed (next steps only, no funnel).
@@ -245,8 +574,13 @@ export function FunnelExploration() {
const prevDashboardStateRef = useRef(dashboardState)
const preloadFiredRef = useRef(false)
const funnelFromPreloadRef = useRef(false)
+ // Bumped whenever the user actively changes the journey or direction.
+ // Used to discard stale preload-driven candidate fetches that resolve
+ // after the user has already navigated away from the preloaded prefix.
+ const journeyVersionRef = useRef(0)
function handleSelect(columnIndex, selected) {
+ journeyVersionRef.current++
// Reset the active-column filter whenever the journey changes
setActiveColumnFilter('')
@@ -254,15 +588,20 @@ export function FunnelExploration() {
setProvisionalFunnelEntries({})
setActiveColumnResults([])
setActiveColumnLoading(true)
+ setFrozenColumnResults((prev) =>
+ truncateFrozenResultsAtIndex(prev, columnIndex)
+ )
setSteps(steps.slice(0, columnIndex))
} else {
// Snapshot the clicked step's visitor count from the current results so
// the column can display a sensible value immediately, before the funnel
// API response arrives. The bar width is computed relative to the first
// step's visitor count (same baseline the real funnel uses).
- const match = activeColumnResults.find(({ step }) =>
- isSameStep(step, selected)
- )
+ const sourceResults =
+ columnIndex === steps.length
+ ? activeColumnResults
+ : frozenColumnResults[columnIndex] || []
+ const match = sourceResults.find(({ step }) => isSameStep(step, selected))
if (match) {
const firstStepVisitors = funnel[0]?.visitors ?? match.visitors
const conversionRate = Math.round(
@@ -277,23 +616,64 @@ export function FunnelExploration() {
} else {
setProvisionalFunnelEntries({})
}
+ setFrozenColumnResults((prev) => {
+ if (columnIndex === steps.length) {
+ // Selecting from the active column: freeze its current results so
+ // they remain visible in the now-selected column.
+ return {
+ ...truncateFrozenResultsAtIndex(prev, columnIndex),
+ [columnIndex]: activeColumnResults
+ }
+ }
+ // Selecting from a previously-frozen column: keep its frozen results
+ // (the user is browsing them) but drop anything beyond, since the
+ // journey downstream just changed.
+ return truncateFrozenResultsAtIndex(prev, columnIndex + 1)
+ })
setActiveColumnResults([])
setActiveColumnLoading(true)
setSteps([...steps.slice(0, columnIndex), selected])
}
}
+ function handleReset() {
+ journeyVersionRef.current++
+ setSteps([])
+ setFunnel([])
+ setActiveColumnResults([])
+ setActiveColumnFilter('')
+ setProvisionalFunnelEntries({})
+ setFrozenColumnResults({})
+ }
+
function handleDirectionSelect(nextDirection) {
if (nextDirection === direction) return
+ journeyVersionRef.current++
setDirection(nextDirection)
- setSteps(steps.toReversed())
+ setSteps([])
setFunnel([])
setActiveColumnResults([])
setActiveColumnFilter('')
setProvisionalFunnelEntries({})
+ setFrozenColumnResults({})
}
+ // Frozen candidate lists were fetched against a specific site +
+ // dashboard filter context. When either changes the cached candidates
+ // become stale, so drop them and invalidate any in-flight preload
+ // backfills. We skip the initial run so we don't clobber the freshly
+ // populated state on mount.
+ const initialFilterContextRef = useRef(true)
+ useEffect(() => {
+ if (initialFilterContextRef.current) {
+ initialFilterContextRef.current = false
+ return
+ }
+ journeyVersionRef.current++
+ setFrozenColumnResults({})
+ }, [site, dashboardState])
+
// On first render fire the interesting-funnel preload and skip the normal
// next-with-funnel fetch. Once the preload resolves it sets steps
// and funnel, which re-triggers this effect for the next-step candidates fetch.
@@ -319,10 +699,12 @@ export function FunnelExploration() {
fetchInterestingFunnel(site, dashboardState)
.then((response) => {
if (cancelled) return
- if (response && response.length > 0) {
+ if (response && response.funnel && response.funnel.length > 0) {
funnelFromPreloadRef.current = true
- setSteps(response.map(({ step }) => step))
- setFunnel(response)
+ const preloadedSteps = response.funnel.map(({ step }) => step)
+ setSteps(preloadedSteps)
+ setFunnel(response.funnel)
+ setFrozenColumnResults(response.candidates)
} else {
// Nothing to preload, fall back to a plain next-steps fetch
fetchNextWithFunnel(site, dashboardState, [], '', direction, false)
@@ -394,6 +776,8 @@ export function FunnelExploration() {
if (!cancelled) setActiveColumnLoading(false)
})
+ setConnectorsKey(randomKey)
+
return () => {
cancelled = true
}
@@ -401,55 +785,80 @@ export function FunnelExploration() {
const numColumns = Math.max(steps.length + 1, 3)
const activeColumnIndex = steps.length
- const scrollRef = useRef(null)
+ const containerRef = useRef(null)
+
+ const lastFunnelStep = funnel.length >= 2 ? funnel[funnel.length - 1] : null
+ const overallConversionRate = lastFunnelStep?.conversion_rate ?? null
+ const overallConversionVisitors = lastFunnelStep?.visitors ?? null
+ const prevStepsLengthRef = useRef(0)
useEffect(() => {
- const el = scrollRef.current
+ const el = containerRef.current
if (!el) return
- el.scrollTo({ left: el.scrollWidth, behavior: 'smooth' })
+ if (steps.length !== prevStepsLengthRef.current) {
+ const activeColumn = el.querySelector(
+ `[data-exploration-column="${steps.length}"]`
+ )
+ if (activeColumn) {
+ const { left: colLeft, right: colRight } =
+ activeColumn.getBoundingClientRect()
+ const { left: containerLeft, right: containerRight } =
+ el.getBoundingClientRect()
+ if (colRight > containerRight || colLeft < containerLeft) {
+ el.scrollTo({
+ left: el.scrollLeft + colLeft - containerLeft,
+ behavior: 'smooth'
+ })
+ }
+ } else {
+ el.scrollTo({ left: el.scrollWidth, behavior: 'smooth' })
+ }
+ }
+ prevStepsLengthRef.current = steps.length
}, [steps.length])
return (
- <div className="flex flex-col gap-4 pt-3">
- <div className="flex flex-wrap items-center justify-between gap-3">
- <div className="flex flex-col">
- <h4 className="text-base font-semibold dark:text-gray-100">
- Explore
- </h4>
- </div>
- <div className="flex shrink-0 items-center gap-3">
- <div className="flex gap-1 overflow-hidden">
- <button
- onClick={() =>
- handleDirectionSelect(EXPLORATION_DIRECTIONS.FORWARD)
- }
- className={`px-2 py-1.5 text-xs font-medium rounded-md ${
- direction === EXPLORATION_DIRECTIONS.FORWARD
- ? 'bg-gray-150 text-gray-900 dark:bg-gray-750 dark:text-gray-100'
- : 'text-gray-500 dark:text-gray-400'
- }`}
- >
- Starting point
- </button>
- <button
- onClick={() =>
- handleDirectionSelect(EXPLORATION_DIRECTIONS.BACKWARD)
- }
- className={`px-2 py-1.5 text-xs font-medium rounded-md ${
- direction === EXPLORATION_DIRECTIONS.BACKWARD
- ? 'bg-gray-150 text-gray-900 dark:bg-gray-750 dark:text-gray-100'
- : 'text-gray-500 dark:text-gray-400'
- }`}
- >
- End point
- </button>
+ <div className="flex flex-col gap-4 pt-4">
+ <div className="flex flex-wrap items-center gap-x-3">
+ <h4 className="flex-1 text-base font-semibold dark:text-gray-100">
+ {funnel.length >= 2
+ ? `${funnel.length}-step user journey`
+ : 'Explore user journeys'}
+ </h4>
+ {overallConversionRate != null && (
+ <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">
+ Conversion: {parseFloat(overallConversionRate).toFixed(1)}%{' '}
+ </span>
+ <span className="text-gray-500 dark:text-gray-400">
+ ({numberShortFormatter(overallConversionVisitors)})
+ </span>
+ </span>
+ <span className="hidden sm:inline text-gray-300 dark:text-gray-600 select-none">
+ |
+ </span>
</div>
- </div>
+ )}
+ <Tooltip
+ info={<span className="whitespace-nowrap">Deselect all</span>}
+ className={steps.length === 0 ? 'invisible pointer-events-none' : ''}
+ >
+ <button
+ onClick={handleReset}
+ className={`${popover.toggleButton.classNames.rounded} ${popover.toggleButton.classNames.outline} justify-center !h-7 px-1.5`}
+ >
+ <RefreshIcon className="size-3.5" />
+ </button>
+ </Tooltip>
</div>
<div
- ref={scrollRef}
- className="flex gap-4 overflow-x-auto -mx-5 px-5 -mb-3 pb-3"
+ ref={containerRef}
+ className="relative grid gap-6 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={{
+ gridTemplateColumns: `repeat(${numColumns}, minmax(20rem, 1fr))`
+ }}
>
{Array.from({ length: numColumns }, (_, i) => {
const isActive = i === activeColumnIndex
@@ -458,12 +867,25 @@ export function FunnelExploration() {
return (
<ExplorationColumn
key={i}
+ colIndex={i}
header={columnHeader(i, direction)}
+ className={
+ steps.length === 0 && i === 2
+ ? 'sm:hidden'
+ : steps.length === 0 && i === 1
+ ? 'sm:[grid-column:span_2]'
+ : undefined
+ }
active={isReachable}
- // Active column gets live results; selected columns show a single
- // item sourced from funnel data (passed as selectedVisitors /
- // selectedConversionRate) so they need no results of their own.
- results={isActive ? activeColumnResults : []}
+ // Active column gets live results; previously-active (now
+ // selected) columns get the candidate list that was visible at
+ // the moment of selection so the user can switch options
+ // without losing context. Pre-selected columns (e.g. populated
+ // by interesting-funnel preload) have no frozen results and
+ // fall back to a single-item display sourced from funnel data.
+ results={
+ isActive ? activeColumnResults : frozenColumnResults[i] || []
+ }
loading={isActive ? activeColumnLoading : false}
selected={steps[i] || null}
selectedVisitors={
@@ -481,9 +903,22 @@ export function FunnelExploration() {
onFilterChange={isActive ? setActiveColumnFilter : () => {}}
filter={isActive ? activeColumnFilter : ''}
direction={direction}
+ onDirectionChange={i === 0 ? handleDirectionSelect : undefined}
+ headerConversionRate={
+ funnel[i]?.conversion_rate != null
+ ? i === 0
+ ? '100%'
+ : `${parseFloat(funnel[i].conversion_rate).toFixed(1)}%`
+ : null
+ }
/>
)
})}
+ <PathConnectors
+ key={connectorsKey}
+ containerRef={containerRef}
+ steps={steps}
+ />
</div>
</div>
)
diff --git a/extra/lib/plausible/stats/exploration.ex b/extra/lib/plausible/stats/exploration.ex
index 7ebab60274..6eaa5f77f2 100644
--- a/extra/lib/plausible/stats/exploration.ex
+++ b/extra/lib/plausible/stats/exploration.ex
@@ -144,7 +144,7 @@ defmodule Plausible.Stats.Exploration do
(default: true)
"""
@spec interesting_funnel(Query.t(), keyword()) ::
- {:ok, [funnel_step()]} | {:error, :not_found}
+ {:ok, %{funnel: [funnel_step()], candidates: [next_step()]}} | {:error, :not_found}
def interesting_funnel(query, opts \\ []) do
max_steps = min(Keyword.get(opts, :max_steps, 6), @max_steps)
max_candidates = min(Keyword.get(opts, :max_candidates, 10), @max_candidates)
@@ -156,22 +156,50 @@ defmodule Plausible.Stats.Exploration do
Keyword.fetch!(@next_steps_defaults, :include_wildcard?)
)
- case build_interesting_journey(query, max_steps, max_candidates, include_wildcard?) do
- [] -> {:error, :not_found}
- journey -> journey_funnel(query, journey)
+ with {:ok, result} <-
+ build_interesting_journey(query, max_steps, max_candidates, include_wildcard?),
+ {:ok, funnel} <- journey_funnel(query, result.journey) do
+ {:ok, %{funnel: funnel, candidates: result.candidates}}
end
end
defp build_interesting_journey(query, max_steps, max_candidates, include_wildcard?) do
- do_build_journey(query, [], MapSet.new(), max_steps, max_candidates, include_wildcard?)
+ case do_build_journey(
+ query,
+ [],
+ [],
+ MapSet.new(),
+ max_steps,
+ max_candidates,
+ include_wildcard?
+ ) do
+ %{journey: []} -> {:error, :not_found}
+ result -> {:ok, result}
+ end
end
- defp do_build_journey(_query, journey, _seen, max_steps, _max_candidates, _include_wildcard?)
+ defp do_build_journey(
+ _query,
+ journey,
+ step_candidates,
+ _seen,
+ max_steps,
+ _max_candidates,
+ _include_wildcard?
+ )
when length(journey) >= max_steps do
- journey
+ %{journey: journey, candidates: step_candidates}
end
- defp do_build_journey(query, journey, seen, max_steps, max_candidates, include_wildcard?) do
+ defp do_build_journey(
+ query,
+ journey,
+ step_candidates,
+ seen,
+ max_steps,
+ max_candidates,
+ include_wildcard?
+ ) do
{:ok, candidates} =
next_steps(query, journey,
max_candidates: max_candidates,
@@ -180,7 +208,7 @@ defmodule Plausible.Stats.Exploration do
case find_unseen_step(candidates, seen) do
nil ->
- journey
+ %{journey: journey, candidates: step_candidates}
step ->
new_seen = MapSet.put(seen, normalize_step_key(step))
@@ -188,6 +216,7 @@ defmodule Plausible.Stats.Exploration do
do_build_journey(
query,
journey ++ [step],
+ step_candidates ++ [candidates],
new_seen,
max_steps,
max_candidates,
diff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.ex
index f7934e14bc..3aeca5b420 100644
--- a/lib/plausible_web/controllers/api/stats_controller.ex
+++ b/lib/plausible_web/controllers/api/stats_controller.ex
@@ -137,6 +137,8 @@ defmodule PlausibleWeb.Api.StatsController do
end
on_ee do
+ alias Plausible.Stats.Exploration
+
@exploration_wildcard_disabled_flag :exploration_wildcard_disabled
def exploration_next(conn, %{"journey" => steps} = params) do
@@ -149,7 +151,7 @@ defmodule PlausibleWeb.Api.StatsController do
include_wildcard? =
not FunWithFlags.enabled?(@exploration_wildcard_disabled_flag, for: site),
{:ok, next_steps} <-
- Plausible.Stats.Exploration.next_steps(query, journey,
+ Exploration.next_steps(query, journey,
search_term: search_term,
direction: direction,
include_wildcard?: include_wildcard?
@@ -168,7 +170,7 @@ defmodule PlausibleWeb.Api.StatsController do
{:ok, direction} <- parse_exploration_direction(params["direction"]),
query = Query.from(site, params, debug_metadata: debug_metadata(conn)),
{:ok, funnel} <-
- Plausible.Stats.Exploration.journey_funnel(query, journey, direction) do
+ Exploration.journey_funnel(query, journey, direction) do
json(conn, funnel)
else
{:error, :empty_journey} ->
@@ -186,12 +188,12 @@ defmodule PlausibleWeb.Api.StatsController do
include_wildcard? =
not FunWithFlags.enabled?(@exploration_wildcard_disabled_flag, for: site)
- case Plausible.Stats.Exploration.interesting_funnel(query,
+ case Exploration.interesting_funnel(query,
max_steps: params["max_steps"],
max_candidates: params["max_candidates"],
include_wildcard?: include_wildcard?
) do
- {:ok, funnel} -> json(conn, funnel)
+ {:ok, funnel_and_candidates} -> json(conn, funnel_and_candidates)
{:error, :not_found} -> json(conn, [])
end
end
@@ -207,7 +209,7 @@ defmodule PlausibleWeb.Api.StatsController do
include_wildcard? =
not FunWithFlags.enabled?(@exploration_wildcard_disabled_flag, for: site),
{:ok, next_steps} <-
- Plausible.Stats.Exploration.next_steps(query, journey,
+ Exploration.next_steps(query, journey,
search_term: search_term,
direction: direction,
include_wildcard?: include_wildcard?
@@ -221,7 +223,7 @@ defmodule PlausibleWeb.Api.StatsController do
end
defp maybe_include_funnel(true, query, journey, direction) do
- case Plausible.Stats.Exploration.journey_funnel(query, journey, direction) do
+ case Exploration.journey_funnel(query, journey, direction) do
{:ok, funnel_data} -> funnel_data
{:error, :empty_journey} -> []
end
@@ -242,7 +244,7 @@ defmodule PlausibleWeb.Api.StatsController do
"includes_subpaths" => includes_subpaths,
"subpaths_count" => subpaths_count
}) do
- Plausible.Stats.Exploration.Journey.Step.new(
+ Exploration.Journey.Step.new(
name,
pathname,
includes_subpaths,
diff --git a/test/plausible/stats/exploration_test.exs b/test/plausible/stats/exploration_test.exs
index c99572f9a8..e2deaf5dbc 100644
--- a/test/plausible/stats/exploration_test.exs
+++ b/test/plausible/stats/exploration_test.exs
@@ -244,7 +244,8 @@ defmodule Plausible.Stats.ExplorationTest do
test "builds a funnel starting with the most visited step", %{site: site} do
query = QueryBuilder.build!(site, input_date_range: :all)
- assert {:ok, [step1, step2, step3, step4]} = Exploration.interesting_funnel(query)
+ assert {:ok, %{funnel: [step1, step2, step3, step4]}} =
+ Exploration.interesting_funnel(query)
assert step1.step.pathname == "/home"
assert step1.visitors == 2
@@ -262,7 +263,8 @@ defmodule Plausible.Stats.ExplorationTest do
test "limits the funnel to max_steps", %{site: site} do
query = QueryBuilder.build!(site, input_date_range: :all)
- assert {:ok, [step1, step2]} = Exploration.interesting_funnel(query, max_steps: 2)
+ assert {:ok, %{funnel: [step1, step2]}} =
+ Exploration.interesting_funnel(query, max_steps: 2)
assert step1.step.pathname == "/home"
assert step2.step.pathname == "/login"
@@ -289,7 +291,7 @@ defmodule Plausible.Stats.ExplorationTest do
query = QueryBuilder.build!(site, input_date_range: :all)
- assert {:ok, [step1]} = Exploration.interesting_funnel(query, max_steps: 6)
+ assert {:ok, %{funnel: [step1]}} = Exploration.interesting_funnel(query, max_steps: 6)
assert step1.step.pathname == "/only-page"
assert step1.visitors == 1
@@ -302,9 +304,9 @@ defmodule Plausible.Stats.ExplorationTest do
filters: [[:is, "visit:browser", ["Firefox"]]]
)
- assert {:ok, funnel} = Exploration.interesting_funnel(query)
+ assert {:ok, result} = Exploration.interesting_funnel(query)
- pathnames = Enum.map(funnel, & &1.step.pathname)
+ pathnames = Enum.map(result.funnel, & &1.step.pathname)
assert pathnames == ["/docs", "/logout"]
end
@@ -359,9 +361,9 @@ defmodule Plausible.Stats.ExplorationTest do
query = QueryBuilder.build!(site, input_date_range: :all)
- assert {:ok, funnel} = Exploration.interesting_funnel(query)
+ assert {:ok, result} = Exploration.interesting_funnel(query)
- pathnames = Enum.map(funnel, & &1.step.pathname)
+ pathnames = Enum.map(result.funnel, & &1.step.pathname)
assert pathnames == ["/a", "/b", "/c"]
end
end