Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

improve sankey (#820)

Goldflagb35fde8c809b
diff --git a/client/src/app/[site]/journeys/components/SankeyDiagram.tsx b/client/src/app/[site]/journeys/components/SankeyDiagram.tsx
index 1c2381db4..dade064ac 100644
--- a/client/src/app/[site]/journeys/components/SankeyDiagram.tsx
+++ b/client/src/app/[site]/journeys/components/SankeyDiagram.tsx
@@ -4,7 +4,9 @@ import * as d3 from "d3";
import { useTheme } from "next-themes";
import { useEffect, useRef } from "react";
+const MIN_LINK_HEIGHT = 0;
const MAX_LINK_HEIGHT = 100;
+const MIN_NODE_HEIGHT = 2;
interface Journey {
path: string[];
@@ -29,10 +31,7 @@ export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDi
// Define theme-based colors
const isDark = theme === "dark";
const linkColor = isDark ? "hsl(var(--neutral-500))" : "hsl(var(--neutral-400))";
- const nodeBubbleBg = isDark ? "hsl(var(--neutral-850))" : "hsl(var(--neutral-100))";
- const nodeBubbleBorder = isDark ? "hsl(var(--neutral-700))" : "hsl(var(--neutral-200))";
const pathTextColor = isDark ? "white" : "hsl(var(--neutral-900))";
- const countTextColor = isDark ? "hsl(var(--neutral-300))" : "hsl(var(--neutral-600))";
const svg = d3.select(svgRef.current);
svg.selectAll("*").remove();
@@ -77,27 +76,8 @@ export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDi
}
});
- // Calculate dimensions
+ // Group nodes by step
const nodesByStep = d3.group(nodes, d => d.step);
- const maxNodesInAnyStep = Math.max(...Array.from(nodesByStep.values()).map(stepNodes => stepNodes.length));
-
- const nodeWidth = 30;
- const width = containerWidth;
- const stepWidth = width / steps;
- const stepSpacing = stepWidth - nodeWidth;
- const minHeight = 500;
- const baseNodeHeight = 60;
- const nodeSpacing = 20;
- const height = Math.max(minHeight, (baseNodeHeight + nodeSpacing) * maxNodesInAnyStep + 100);
-
- const margin = { top: 30, right: 0, bottom: 30, left: 0 };
- const innerHeight = height - margin.top - margin.bottom;
-
- const g = svg
- .attr("width", width)
- .attr("height", height)
- .append("g")
- .attr("transform", `translate(${margin.left},${margin.top})`);
// Track incoming and outgoing links for each node
links.forEach(link => {
@@ -108,65 +88,82 @@ export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDi
if (targetNode) targetNode.incomingLinks.push(link);
});
- // Position nodes
- nodesByStep.forEach((stepNodes, step) => {
- const stepX = step * stepWidth;
- const stepHeight = innerHeight / stepNodes.length;
-
- stepNodes.forEach((node, i) => {
- node.x = stepX;
- node.y = i * stepHeight + stepHeight / 2;
- });
- });
-
- // Calculate node heights and metadata
+ // Calculate node heights and metadata first (before positioning)
const maxLinkValue = d3.max(links, link => link.value) || 1;
- const linkWidthScale = d3.scaleLinear().domain([0, maxLinkValue]).range([1, MAX_LINK_HEIGHT]);
+ const linkWidthScale = d3.scaleLinear().domain([0, maxLinkValue]).range([MIN_LINK_HEIGHT, MAX_LINK_HEIGHT]);
nodes.forEach(node => {
const incomingValue = node.incomingLinks.reduce((sum: number, link: any) => sum + link.value, 0);
const outgoingValue = node.outgoingLinks.reduce((sum: number, link: any) => sum + link.value, 0);
const maxValue = Math.max(incomingValue, outgoingValue);
- node.height = linkWidthScale(maxValue);
+ // Apply minimum height to nodes (but not to links/connections)
+ node.height = Math.max(linkWidthScale(maxValue), MIN_NODE_HEIGHT);
node.count = node.step === 0 ? outgoingValue : incomingValue;
const matchingJourney = journeys.find(journey => journey.path[node.step] === node.name);
node.percentage = matchingJourney ? matchingJourney.percentage : 0;
});
- // Calculate link positions
+ // Calculate dimensions based on actual node heights
+ const nodeWidth = 30;
+ const width = containerWidth;
+ const stepWidth = width / steps;
+ const stepSpacing = stepWidth - nodeWidth;
+ const nodeGap = 20; // Gap between nodes
+ const minHeight = 200;
+ const verticalPadding = 10;
+
+ // Calculate the total height needed for each step column
+ const stepHeights = Array.from(nodesByStep.values()).map(stepNodes => {
+ return stepNodes.reduce((sum, node) => sum + node.height, 0) + (stepNodes.length - 1) * nodeGap;
+ });
+ const maxStepHeight = Math.max(...stepHeights);
+ const height = Math.max(minHeight, maxStepHeight + verticalPadding * 2);
+
+ const margin = { top: 0, right: 0, bottom: verticalPadding, left: 0 };
+
+ const g = svg
+ .attr("width", width)
+ .attr("height", height)
+ .append("g")
+ .attr("transform", `translate(${margin.left},${margin.top})`);
+
+ // Position nodes - align from top so first node of each step is at same height
+ nodesByStep.forEach((stepNodes, step) => {
+ const stepX = step * stepWidth;
+ let currentY = 0;
+
+ stepNodes.forEach(node => {
+ node.x = stepX;
+ // Position node center based on accumulated height
+ node.y = currentY + node.height / 2;
+ currentY += node.height + nodeGap;
+ });
+ });
+
+ // Calculate link positions - stack links within each node, aligned to top
nodes.forEach(node => {
node.incomingLinks.sort((a: any, b: any) => b.value - a.value);
node.outgoingLinks.sort((a: any, b: any) => b.value - a.value);
- let currentOutY = 0;
+ // Start outgoing links from top of node
+ const outStartY = node.y - node.height / 2;
+ let currentOutY = outStartY;
node.outgoingLinks.forEach((link: any) => {
const linkHeight = linkWidthScale(link.value);
link.sourceY = currentOutY + linkHeight / 2;
currentOutY += linkHeight;
});
- if (currentOutY > 0 && node.outgoingLinks.length > 0) {
- node.outgoingLinks.forEach((link: any) => {
- link.sourceY = (link.sourceY / currentOutY) * node.height - node.height / 2;
- link.sourceY += node.y;
- });
- }
-
- let currentInY = 0;
+ // Start incoming links from top of node
+ const inStartY = node.y - node.height / 2;
+ let currentInY = inStartY;
node.incomingLinks.forEach((link: any) => {
const linkHeight = linkWidthScale(link.value);
link.targetY = currentInY + linkHeight / 2;
currentInY += linkHeight;
});
-
- if (currentInY > 0 && node.incomingLinks.length > 0) {
- node.incomingLinks.forEach((link: any) => {
- link.targetY = (link.targetY / currentInY) * node.height - node.height / 2;
- link.targetY += node.y;
- });
- }
});
// Helper function to find all connected paths (all reachable nodes/edges)
@@ -201,88 +198,106 @@ export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDi
return connectedLinks;
};
- // Draw links
- const linkElements = g
- .selectAll(".link")
- .data(links)
- .join("path")
- .attr("class", "link")
- .attr("d", d => {
- const source = nodes.find(n => n.id === d.source);
- const target = nodes.find(n => n.id === d.target);
+ // Helper to generate link path
+ const getLinkPath = (d: any) => {
+ const source = nodes.find(n => n.id === d.source);
+ const target = nodes.find(n => n.id === d.target);
- if (!source || !target) return "";
+ if (!source || !target) return "";
- const sourceY = d.sourceY || source.y;
- const targetY = d.targetY || target.y;
- const sourceX = source.x + nodeWidth;
- const targetX = target.x;
+ const sourceY = d.sourceY || source.y;
+ const targetY = d.targetY || target.y;
+ const sourceX = source.x + nodeWidth;
+ const targetX = target.x;
- const controlPoint1X = sourceX + stepSpacing / 3;
- const controlPoint2X = targetX - stepSpacing / 3;
+ const controlPoint1X = sourceX + stepSpacing / 3;
+ const controlPoint2X = targetX - stepSpacing / 3;
- return `M ${sourceX},${sourceY}
- C ${controlPoint1X},${sourceY}
- ${controlPoint2X},${targetY}
- ${targetX},${targetY}`;
- })
- .attr("fill", "none")
- .attr("stroke", linkColor)
- .attr("stroke-width", d => linkWidthScale(d.value))
- .attr("opacity", 0.2)
- .attr("data-source", d => d.source)
- .attr("data-target", d => d.target)
- .style("cursor", "pointer")
- .style("pointer-events", "visibleStroke")
- .on("mouseenter", function (event, d) {
- const forwardPaths = findAllConnectedPaths(d, "forward");
- const backwardPaths = findAllConnectedPaths(d, "backward");
- const allConnectedLinks = [d, ...forwardPaths, ...backwardPaths];
+ return `M ${sourceX},${sourceY}
+ C ${controlPoint1X},${sourceY}
+ ${controlPoint2X},${targetY}
+ ${targetX},${targetY}`;
+ };
- const connectedLinkIds = new Set<string>();
- const connectedNodeIds = new Set<string>();
+ // Calculate node colors based on first path segment
+ const getFirstSegment = (path: string) => {
+ // Split path and get first non-empty segment
+ const segments = path.split("/").filter(Boolean);
+ return segments.length > 0 ? `/${segments[0]}` : path;
+ };
- allConnectedLinks.forEach(link => {
- const linkId = `${link.source}|||${link.target}`;
- connectedLinkIds.add(linkId);
- connectedNodeIds.add(link.source);
- connectedNodeIds.add(link.target);
- });
+ // Count occurrences of each first segment
+ const segmentCounts = new Map<string, number>();
+ nodes.forEach(node => {
+ const segment = getFirstSegment(node.name);
+ segmentCounts.set(segment, (segmentCounts.get(segment) || 0) + 1);
+ });
- d3.selectAll(".link")
- .attr("opacity", function () {
- const linkSource = d3.select(this).attr("data-source");
- const linkTarget = d3.select(this).attr("data-target");
- const thisLinkId = `${linkSource}|||${linkTarget}`;
- return connectedLinkIds.has(thisLinkId) ? 0.5 : 0.1;
- })
- .attr("stroke", function () {
- const linkSource = d3.select(this).attr("data-source");
- const linkTarget = d3.select(this).attr("data-target");
- const thisLinkId = `${linkSource}|||${linkTarget}`;
- return connectedLinkIds.has(thisLinkId) ? "hsl(var(--emerald-600))" : linkColor;
- });
+ // Color palette for repeated segments
+ const colorPalette = [
+ "hsl(160, 45%, 40%)", // teal
+ "hsl(220, 45%, 50%)", // blue
+ "hsl(270, 40%, 50%)", // purple
+ "hsl(25, 50%, 50%)", // orange
+ "hsl(340, 40%, 50%)", // pink
+ "hsl(190, 45%, 45%)", // cyan
+ "hsl(45, 45%, 50%)", // yellow
+ "hsl(0, 45%, 50%)", // red
+ ];
+ const defaultColor = "hsl(0, 0%, 50%)";
+
+ // Assign colors to repeated segments
+ const segmentColors = new Map<string, string>();
+ let colorIndex = 0;
+ segmentCounts.forEach((count, segment) => {
+ if (count > 1) {
+ segmentColors.set(segment, colorPalette[colorIndex % colorPalette.length]);
+ colorIndex++;
+ }
+ });
- d3.selectAll(".node-rect").attr("opacity", function (nodeData: any) {
- return connectedNodeIds.has(nodeData.id) ? 1 : 0.2;
- });
+ // Get color for a node
+ const getNodeColor = (node: any) => {
+ const segment = getFirstSegment(node.name);
+ return segmentColors.get(segment) || defaultColor;
+ };
- d3.selectAll(".node-bubble").attr("opacity", function (nodeData: any) {
- return connectedNodeIds.has(nodeData.id) ? 1 : 0.2;
- });
+ // Get color for a link (based on source node)
+ const getLinkColor = (d: any) => {
+ const sourceNode = nodes.find(n => n.id === d.source);
+ return sourceNode ? getNodeColor(sourceNode) : linkColor;
+ };
- d3.selectAll(".node-text").attr("opacity", function (nodeData: any) {
- return connectedNodeIds.has(nodeData.id) ? 1 : 0.3;
- });
- })
- .on("mouseleave", function () {
- d3.selectAll(".link").attr("opacity", 0.2).attr("stroke", linkColor);
- d3.selectAll(".node-rect").attr("opacity", 1);
- d3.selectAll(".node-bubble").attr("opacity", 1);
- d3.selectAll(".node-text").attr("opacity", 1);
- })
- .append("title")
- .text(d => `Count: ${d.value}`);
+ // Draw links (visual only, events handled by hit areas)
+ g.selectAll(".link")
+ .data(links)
+ .join("path")
+ .attr("class", "link")
+ .attr("d", getLinkPath)
+ .attr("fill", "none")
+ .attr("stroke", d => getLinkColor(d))
+ .attr("stroke-width", d => linkWidthScale(d.value))
+ .attr("opacity", 0.3)
+ .attr("data-source", d => d.source)
+ .attr("data-target", d => d.target)
+ .style("pointer-events", "none");
+
+ // Add tooltip for links
+ const tooltip = d3
+ .select("body")
+ .append("div")
+ .attr("class", "sankey-tooltip")
+ .style("position", "absolute")
+ .style("visibility", "hidden")
+ .style("background", isDark ? "hsl(var(--neutral-800))" : "hsl(var(--neutral-100))")
+ .style("border", `1px solid ${isDark ? "hsl(var(--neutral-700))" : "hsl(var(--neutral-200))"}`)
+ .style("border-radius", "6px")
+ .style("padding", "8px 12px")
+ .style("font-size", "12px")
+ .style("color", isDark ? "white" : "hsl(var(--neutral-900))")
+ .style("pointer-events", "none")
+ .style("z-index", "1000")
+ .style("box-shadow", "0 2px 8px rgba(0,0,0,0.15)");
// Draw nodes
const nodeGroups = g
@@ -298,31 +313,10 @@ export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDi
.attr("class", "node-rect")
.attr("width", nodeWidth)
.attr("height", d => d.height)
- .attr("fill", "hsl(var(--emerald-600))")
+ .attr("fill", d => getNodeColor(d))
.attr("rx", 2)
.attr("ry", 2);
- // Bubble background
- nodeGroups
- .append("rect")
- .attr("class", "node-bubble")
- .attr("x", 12)
- .attr("y", 4)
- .attr("width", d => {
- const pathText = d.name;
- const statsText = `${d.count.toLocaleString()} (${d.percentage.toFixed(1)}%)`;
- const maxLength = Math.max(pathText.length, statsText.length);
- const textWidth = maxLength * 6.5;
- return textWidth + 10;
- })
- .attr("height", 41)
- .attr("fill", nodeBubbleBg)
- .attr("stroke", nodeBubbleBorder)
- .attr("stroke-width", 1)
- .attr("rx", 4)
- .attr("ry", 4)
- .attr("opacity", 1);
-
// Path text (clickable)
const pathLinks = nodeGroups
.append("a")
@@ -333,8 +327,8 @@ export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDi
pathLinks
.append("text")
.attr("class", "node-text node-link-text")
- .attr("x", 19)
- .attr("y", 21)
+ .attr("x", 36)
+ .attr("y", d => d.height / 2 + 4)
.text(d => d.name)
.attr("font-size", "12px")
.attr("fill", pathTextColor)
@@ -343,30 +337,46 @@ export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDi
// Add hover effect to show underline on link text
pathLinks
- .on("mouseenter", function () {
+ .on("mouseenter", function (event, d) {
d3.select(this).select(".node-link-text").style("text-decoration", "underline");
+ // Show tooltip
+ tooltip
+ .style("visibility", "visible")
+ .html(
+ `<div style="font-weight: 500; margin-bottom: 4px;">${d.name}</div>` +
+ `<div style="color: ${isDark ? "hsl(var(--neutral-300))" : "hsl(var(--neutral-600))"};">` +
+ `${d.count.toLocaleString()} visits (${d.percentage.toFixed(1)}%)</div>`
+ )
+ .style("top", event.pageY - 10 + "px")
+ .style("left", event.pageX + 10 + "px");
+ // Stop event propagation to prevent nodeGroups handler from firing
+ event.stopPropagation();
+ })
+ .on("mousemove", function (event) {
+ tooltip.style("top", event.pageY - 10 + "px").style("left", event.pageX + 10 + "px");
})
.on("mouseleave", function () {
d3.select(this).select(".node-link-text").style("text-decoration", "none");
+ tooltip.style("visibility", "hidden");
});
- // Count text
- nodeGroups
- .append("text")
- .attr("class", "node-text")
- .attr("x", 19)
- .attr("y", 37)
- .text(d => `${d.count.toLocaleString()} (${d.percentage.toFixed(1)}%)`)
- .attr("font-size", "11px")
- .attr("fill", countTextColor)
- .attr("text-anchor", "start");
-
// Node hover effects
nodeGroups
.on("mouseenter", function (event, d) {
const nodeId = d.id;
const connectedNodeIds = new Set<string>([nodeId]);
+ // Show tooltip with node info
+ tooltip
+ .style("visibility", "visible")
+ .html(
+ `<div style="font-weight: 500; margin-bottom: 4px;">${d.name}</div>` +
+ `<div style="color: ${isDark ? "hsl(var(--neutral-300))" : "hsl(var(--neutral-600))"};">` +
+ `${d.count.toLocaleString()} visits (${d.percentage.toFixed(1)}%)</div>`
+ )
+ .style("top", event.pageY - 10 + "px")
+ .style("left", event.pageX + 10 + "px");
+
// Find all directly connected links
const directLinks = links.filter(link => link.source === nodeId || link.target === nodeId);
@@ -393,38 +403,114 @@ export function SankeyDiagram({ journeys, steps, maxJourneys, domain }: SankeyDi
connectedNodeIds.add(link.target);
});
+ d3.selectAll(".link").attr("opacity", function () {
+ const linkSource = d3.select(this).attr("data-source");
+ const linkTarget = d3.select(this).attr("data-target");
+ const thisLinkId = `${linkSource}|||${linkTarget}`;
+ return connectedLinkIds.has(thisLinkId) ? 0.6 : 0.1;
+ });
+
+ d3.selectAll(".node-rect").attr("opacity", function (nodeData: any) {
+ return connectedNodeIds.has(nodeData.id) ? 1 : 0.2;
+ });
+
+ d3.selectAll(".node-text").attr("opacity", function (nodeData: any) {
+ return connectedNodeIds.has(nodeData.id) ? 1 : 0.3;
+ });
+ })
+ .on("mousemove", function (event) {
+ tooltip.style("top", event.pageY - 10 + "px").style("left", event.pageX + 10 + "px");
+ })
+ .on("mouseleave", function () {
d3.selectAll(".link")
- .attr("opacity", function () {
- const linkSource = d3.select(this).attr("data-source");
- const linkTarget = d3.select(this).attr("data-target");
- const thisLinkId = `${linkSource}|||${linkTarget}`;
- return connectedLinkIds.has(thisLinkId) ? 0.5 : 0.1;
- })
+ .attr("opacity", 0.3)
.attr("stroke", function () {
const linkSource = d3.select(this).attr("data-source");
- const linkTarget = d3.select(this).attr("data-target");
- const thisLinkId = `${linkSource}|||${linkTarget}`;
- return connectedLinkIds.has(thisLinkId) ? "hsl(var(--emerald-600))" : linkColor;
+ const link = links.find(l => l.source === linkSource);
+ return link ? getLinkColor(link) : linkColor;
});
+ d3.selectAll(".node-rect").attr("opacity", 1);
+ d3.selectAll(".node-text").attr("opacity", 1);
+ tooltip.style("visibility", "hidden");
+ });
- d3.selectAll(".node-rect").attr("opacity", function (nodeData: any) {
- return connectedNodeIds.has(nodeData.id) ? 1 : 0.2;
+ // Invisible wider hit area for easier hovering on thin links (drawn last to be on top)
+ g.selectAll(".link-hit-area")
+ .data(links)
+ .join("path")
+ .attr("class", "link-hit-area")
+ .attr("d", getLinkPath)
+ .attr("fill", "none")
+ .attr("stroke", "transparent")
+ .attr("stroke-width", d => Math.max(linkWidthScale(d.value), 16))
+ .attr("data-source", d => d.source)
+ .attr("data-target", d => d.target)
+ .style("cursor", "pointer")
+ .on("mouseenter", function (event, d) {
+ const sourceNode = nodes.find(n => n.id === d.source);
+ const targetNode = nodes.find(n => n.id === d.target);
+ const totalValue = d3.sum(links, (l: any) => l.value);
+ const percentage = ((d.value / totalValue) * 100).toFixed(1);
+
+ tooltip
+ .style("visibility", "visible")
+ .html(
+ `<div style="font-weight: 500; margin-bottom: 4px;">${sourceNode?.name} → ${targetNode?.name}</div>` +
+ `<div style="color: ${isDark ? "hsl(var(--neutral-300))" : "hsl(var(--neutral-600))"};">` +
+ `${d.value.toLocaleString()} visits (${percentage}%)</div>`
+ );
+
+ const forwardPaths = findAllConnectedPaths(d, "forward");
+ const backwardPaths = findAllConnectedPaths(d, "backward");
+ const allConnectedLinks = [d, ...forwardPaths, ...backwardPaths];
+
+ const connectedLinkIds = new Set<string>();
+ const connectedNodeIds = new Set<string>();
+
+ allConnectedLinks.forEach(link => {
+ const linkId = `${link.source}|||${link.target}`;
+ connectedLinkIds.add(linkId);
+ connectedNodeIds.add(link.source);
+ connectedNodeIds.add(link.target);
+ });
+
+ d3.selectAll(".link").attr("opacity", function () {
+ const linkSource = d3.select(this).attr("data-source");
+ const linkTarget = d3.select(this).attr("data-target");
+ const thisLinkId = `${linkSource}|||${linkTarget}`;
+ return connectedLinkIds.has(thisLinkId) ? 0.6 : 0.1;
});
- d3.selectAll(".node-bubble").attr("opacity", function (nodeData: any) {
+ d3.selectAll(".node-rect").attr("opacity", function (nodeData: any) {
return connectedNodeIds.has(nodeData.id) ? 1 : 0.2;
});
d3.selectAll(".node-text").attr("opacity", function (nodeData: any) {
return connectedNodeIds.has(nodeData.id) ? 1 : 0.3;
});
+
+ tooltip.style("top", event.pageY - 10 + "px").style("left", event.pageX + 10 + "px");
+ })
+ .on("mousemove", function (event) {
+ tooltip.style("top", event.pageY - 10 + "px").style("left", event.pageX + 10 + "px");
})
.on("mouseleave", function () {
- d3.selectAll(".link").attr("opacity", 0.2).attr("stroke", linkColor);
+ d3.selectAll(".link")
+ .attr("opacity", 0.3)
+ .attr("stroke", function () {
+ const linkSource = d3.select(this).attr("data-source");
+ const link = links.find(l => l.source === linkSource);
+ return link ? getLinkColor(link) : linkColor;
+ });
d3.selectAll(".node-rect").attr("opacity", 1);
- d3.selectAll(".node-bubble").attr("opacity", 1);
d3.selectAll(".node-text").attr("opacity", 1);
+ tooltip.style("visibility", "hidden");
});
+
+ // Cleanup tooltip on unmount
+ return () => {
+ tooltip.remove();
+ };
}, [journeys, steps, maxJourneys, domain, theme]);
return (
diff --git a/client/src/app/[site]/journeys/page.tsx b/client/src/app/[site]/journeys/page.tsx
index 954243ba1..b74263011 100644
--- a/client/src/app/[site]/journeys/page.tsx
+++ b/client/src/app/[site]/journeys/page.tsx
@@ -2,10 +2,7 @@
import { useJourneys } from "@/api/analytics/hooks/useGetJourneys";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
-import {
- InputWithSuggestions,
- SuggestionOption,
-} from "@/components/ui/input-with-suggestions";
+import { InputWithSuggestions, SuggestionOption } from "@/components/ui/input-with-suggestions";
import { Slider } from "@/components/ui/slider";
import { AlertCircle } from "lucide-react";
import { useState } from "react";
@@ -22,8 +19,8 @@ import { SankeyDiagram } from "./components/SankeyDiagram";
export default function JourneysPage() {
useSetPageTitle("Rybbit · Journeys");
- const [steps, setSteps] = useState<number>(3);
- const [maxJourneys, setMaxJourneys] = useState<number>(25);
+ const [steps, setSteps] = useState<number>(4);
+ const [maxJourneys, setMaxJourneys] = useState<number>(70);
const [stepFilters, setStepFilters] = useState<Record<number, string>>({});
const { data: siteMetadata } = useGetSite();
@@ -37,7 +34,7 @@ export default function JourneysPage() {
});
const pathSuggestions: SuggestionOption[] =
- pathsData?.data?.map((item) => ({
+ pathsData?.data?.map(item => ({
value: item.value,
label: item.value,
})) ?? [];
@@ -55,7 +52,7 @@ export default function JourneysPage() {
<DisabledOverlay message="User Journeys" featurePath="journeys">
<div className="container mx-auto p-2 md:p-4">
<SubHeader availableFilters={JOURNEY_PAGE_FILTERS} />
- <div className="flex items-center gap-6 mb-2">
+ <div className="flex items-center gap-6 my-2">
<div className="flex items-center gap-3 w-[180px]">
<span className="text-sm text-neutral-600 dark:text-neutral-300 whitespace-nowrap">{steps} steps</span>
<Slider
@@ -92,33 +89,38 @@ export default function JourneysPage() {
</div>
</div>
)}
- <div className="flex gap-1 mb-4 mt-4">
- {Array.from({ length: steps }, (_, i) => (
- <div
- key={i}
- className="flex-1 h-10 bg-neutral-100 dark:bg-neutral-800 flex items-center text-neutral-900 dark:text-white text-sm relative px-3"
- style={{
- clipPath: "polygon(0 0, 10px 50%, 0 100%, calc(100% - 10px) 100%, 100% 50%, calc(100% - 10px) 0)",
- }}
- >
- <span className="ml-2 whitespace-nowrap text-neutral-700 dark:text-neutral-200">Step {i + 1}</span>
- <InputWithSuggestions
- suggestions={pathSuggestions}
- placeholder="Path filter"
- value={stepFilters[i] || ""}
- onChange={(e) => {
- const newFilters = { ...stepFilters };
- if (e.target.value) {
- newFilters[i] = e.target.value;
- } else {
- delete newFilters[i];
- }
- setStepFilters(newFilters);
+ <div className="flex flex-col gap-1 mb-4 mt-4">
+ <div className="flex gap-1">
+ {Array.from({ length: steps }, (_, i) => (
+ <div
+ key={i}
+ className="flex-1 h-10 bg-neutral-50 dark:bg-neutral-850 flex items-center text-neutral-900 dark:text-white text-sm relative px-3"
+ style={{
+ clipPath: "polygon(0 0, 10px 50%, 0 100%, calc(100% - 10px) 100%, 100% 50%, calc(100% - 10px) 0)",
}}
- className="h-7 bg-white bg-neutral-50 dark:bg-neutral-850 border-neutral-200 dark:border-neutral-700 text-neutral-900 dark:text-white placeholder:text-neutral-400 dark:placeholder:text-neutral-500 ml-3 mr-3"
- />
- </div>
- ))}
+ >
+ <span className="ml-2 whitespace-nowrap text-neutral-700 dark:text-neutral-200">Step {i + 1}</span>
+ <InputWithSuggestions
+ suggestions={pathSuggestions}
+ placeholder="Path filter"
+ value={stepFilters[i] || ""}
+ onChange={e => {
+ const newFilters = { ...stepFilters };
+ if (e.target.value) {
+ newFilters[i] = e.target.value;
+ } else {
+ delete newFilters[i];
+ }
+ setStepFilters(newFilters);
+ }}
+ className="h-7 bg-white dark:bg-neutral-900 border-neutral-100 dark:border-neutral-800 text-neutral-900 dark:text-white placeholder:text-neutral-400 dark:placeholder:text-neutral-500 ml-3 mr-3"
+ />
+ </div>
+ ))}
+ </div>
+ <div className="text-xs text-neutral-500">
+ Use * to match a single path segment, ** to match multiple segments
+ </div>
</div>
{data?.journeys?.length && data?.journeys?.length > 0 ? (
<SankeyDiagram
diff --git a/client/src/components/ui/input-with-suggestions.tsx b/client/src/components/ui/input-with-suggestions.tsx
index 42efddf96..24e412b10 100644
--- a/client/src/components/ui/input-with-suggestions.tsx
+++ b/client/src/components/ui/input-with-suggestions.tsx
@@ -112,7 +112,7 @@ export const InputWithSuggestions = React.forwardRef<HTMLInputElement, InputWith
return (
<div ref={wrapperRef} className="relative">
<Input
- ref={(node) => {
+ ref={node => {
inputRef.current = node;
if (typeof ref === "function") {
ref(node);
@@ -134,18 +134,18 @@ export const InputWithSuggestions = React.forwardRef<HTMLInputElement, InputWith
createPortal(
<div
ref={dropdownRef}
- className="absolute z-[100] max-h-60 overflow-auto rounded-md border border-neutral-150 bg-white shadow-md dark:border-neutral-800 dark:bg-neutral-900"
+ className="absolute z-[100] max-h-60 overflow-y-auto overflow-x-hidden rounded-lg border border-neutral-150 bg-white shadow-md dark:border-neutral-800 dark:bg-neutral-900"
style={{
top: dropdownStyle.top,
left: dropdownStyle.left,
width: dropdownStyle.width,
}}
>
- {filteredSuggestions.map((suggestion) => (
+ {filteredSuggestions.map(suggestion => (
<div
key={suggestion.value}
- className="relative cursor-pointer px-3 py-2 text-sm hover:bg-neutral-100 dark:hover:bg-neutral-800"
- onMouseDown={(e) => e.preventDefault()}
+ className="relative cursor-pointer mx-1 px-2 py-2 text-sm hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-md"
+ onMouseDown={e => e.preventDefault()}
onClick={() => handleSuggestionClick(suggestion.value)}
>
{suggestion.label || suggestion.value}
diff --git a/server/src/api/analytics/getJourneys.ts b/server/src/api/analytics/getJourneys.ts
index c10024bab..97efc086a 100644
--- a/server/src/api/analytics/getJourneys.ts
+++ b/server/src/api/analytics/getJourneys.ts
@@ -2,7 +2,7 @@ import { FilterParams } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { getFilterStatement } from "./utils/getFilterStatement.js";
-import { getTimeStatement } from "./utils/utils.js";
+import { getTimeStatement, patternToRegex } from "./utils/utils.js";
export const getJourneys = async (
request: FastifyRequest<{
@@ -51,9 +51,16 @@ export const getJourneys = async (
}
// Build step filter conditions for the HAVING clause
+ // Supports wildcard patterns: * matches single segment, ** matches multiple segments
const stepFilterConditions = Object.entries(parsedStepFilters)
.map(([step, path]) => {
const stepIndex = parseInt(step, 10) + 1; // ClickHouse arrays are 1-indexed
+ if (path.includes("*")) {
+ // Use regex matching for wildcard patterns
+ const regex = patternToRegex(path);
+ return `match(journey[${stepIndex}], '${regex.replace(/'/g, "\\'")}')`;
+ }
+ // Use exact match for non-wildcard patterns (more efficient)
return `journey[${stepIndex}] = '${path.replace(/'/g, "''")}'`;
})
.join(" AND ");