This commit is contained in:
Carl-Gerhard Lindesvärd
2026-01-07 10:04:21 +01:00
parent ba93924d20
commit ca15717885
33 changed files with 2375 additions and 148 deletions

View File

@@ -15,6 +15,7 @@ import { ReportMapChart } from './map';
import { ReportMetricChart } from './metric';
import { ReportPieChart } from './pie';
import { ReportRetentionChart } from './retention';
import { ReportSankeyChart } from './sankey';
export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {
const ref = useRef<HTMLDivElement>(null);
@@ -57,6 +58,8 @@ export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {
return <ReportRetentionChart />;
case 'conversion':
return <ReportConversionChart />;
case 'sankey':
return <ReportSankeyChart />;
default:
return null;
}

View File

@@ -11,7 +11,6 @@ import {
changeStartDate,
ready,
reset,
setName,
setReport,
} from '@/components/report/reportSlice';
import { ReportSidebar } from '@/components/report/sidebar/ReportSidebar';
@@ -20,7 +19,6 @@ import { Button } from '@/components/ui/button';
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
import { useAppParams } from '@/hooks/use-app-params';
import { useDispatch, useSelector } from '@/redux';
import { bind } from 'bind-event-listener';
import { GanttChartSquareIcon } from 'lucide-react';
import { useEffect } from 'react';

View File

@@ -0,0 +1,302 @@
import {
ChartTooltipContainer,
ChartTooltipHeader,
ChartTooltipItem,
} from '@/components/charts/chart-tooltip';
import { useNumber } from '@/hooks/use-numer-formatter';
import { round } from '@/utils/math';
import { ResponsiveSankey } from '@nivo/sankey';
import {
type ReactNode,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import { createPortal } from 'react-dom';
import { useTheme } from '@/components/theme-provider';
import { truncate } from '@/utils/truncate';
import { ArrowRightIcon } from 'lucide-react';
import { AspectContainer } from '../aspect-container';
type PortalTooltipPosition = { left: number; top: number; ready: boolean };
function SankeyPortalTooltip({
children,
offset = 12,
padding = 8,
}: {
children: ReactNode;
offset?: number;
padding?: number;
}) {
const anchorRef = useRef<HTMLSpanElement | null>(null);
const tooltipRef = useRef<HTMLDivElement | null>(null);
const [anchorRect, setAnchorRect] = useState<DOMRect | null>(null);
const [pos, setPos] = useState<PortalTooltipPosition>({
left: 0,
top: 0,
ready: false,
});
const [mounted, setMounted] = useState(false);
useLayoutEffect(() => {
setMounted(true);
}, []);
useLayoutEffect(() => {
const el = anchorRef.current;
if (!el) return;
const wrapper = el.parentElement;
if (!wrapper) return;
const update = () => {
setAnchorRect(wrapper.getBoundingClientRect());
};
update();
const ro = new ResizeObserver(update);
ro.observe(wrapper);
window.addEventListener('scroll', update, true);
window.addEventListener('resize', update);
return () => {
ro.disconnect();
window.removeEventListener('scroll', update, true);
window.removeEventListener('resize', update);
};
}, []);
useLayoutEffect(() => {
if (!mounted) return;
if (!anchorRect) return;
const tooltipEl = tooltipRef.current;
if (!tooltipEl) return;
const rect = tooltipEl.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
let left = anchorRect.left + offset;
let top = anchorRect.top + offset;
left = Math.min(
Math.max(padding, left),
Math.max(padding, vw - rect.width - padding),
);
top = Math.min(
Math.max(padding, top),
Math.max(padding, vh - rect.height - padding),
);
setPos({ left, top, ready: true });
}, [mounted, anchorRect, children, offset, padding]);
if (typeof document === 'undefined') {
return <>{children}</>;
}
return (
<>
<span ref={anchorRef} className="sr-only" />
{mounted &&
createPortal(
<div
ref={tooltipRef}
className="pointer-events-none fixed z-[9999]"
style={{
left: pos.left,
top: pos.top,
visibility: pos.ready ? 'visible' : 'hidden',
}}
>
{children}
</div>,
document.body,
)}
</>
);
}
type SankeyData = {
nodes: Array<{
id: string;
label: string;
nodeColor: string;
percentage?: number;
value?: number;
step?: number;
}>;
links: Array<{ source: string; target: string; value: number }>;
};
export function Chart({ data }: { data: SankeyData }) {
const number = useNumber();
const containerRef = useRef<HTMLDivElement>(null);
const { appTheme } = useTheme();
// Process data for Sankey
const sankeyData = useMemo(() => {
if (!data) return { nodes: [], links: [] };
return {
nodes: data.nodes.map((node) => ({
...node,
label: node.label || node.id,
data: {
percentage: node.percentage,
value: node.value,
step: node.step,
label: node.label || node.id,
},
})),
links: data.links,
};
}, [data]);
const totalSessions = useMemo(() => {
if (!sankeyData.nodes || sankeyData.nodes.length === 0) return 0;
const step1 = sankeyData.nodes.filter((n: any) => n.data?.step === 1);
const base = step1.length > 0 ? step1 : sankeyData.nodes;
return base.reduce((sum: number, n: any) => sum + (n.data?.value ?? 0), 0);
}, [sankeyData.nodes]);
return (
<AspectContainer>
<div
ref={containerRef}
className="w-full relative aspect-square md:aspect-[2]"
>
<ResponsiveSankey
margin={{ top: 20, right: 20, bottom: 20, left: 20 }}
data={sankeyData}
colors={(node: any) => node.nodeColor}
nodeBorderRadius={2}
animate={false}
nodeBorderWidth={0}
nodeOpacity={0.8}
linkContract={1}
linkOpacity={0.3}
linkBlendMode={'normal'}
nodeTooltip={({ node }: any) => {
const label = node?.data?.label ?? node?.label ?? node?.id;
const value = node?.data?.value ?? node?.value ?? 0;
const step = node?.data?.step;
const pct =
typeof node?.data?.percentage === 'number'
? node.data.percentage
: totalSessions > 0
? (value / totalSessions) * 100
: 0;
const color =
node?.color ??
node?.data?.nodeColor ??
node?.data?.color ??
node?.nodeColor ??
'#64748b';
return (
<SankeyPortalTooltip>
<ChartTooltipContainer className="min-w-[250px]">
<ChartTooltipHeader>
<div className="min-w-0 flex-1 font-medium break-words">
{label}
</div>
{typeof step === 'number' && (
<div className="shrink-0 text-muted-foreground">
Step {step}
</div>
)}
</ChartTooltipHeader>
<ChartTooltipItem color={color} innerClassName="gap-2">
<div className="flex items-center justify-between gap-8 font-mono font-medium">
<div className="text-muted-foreground">Sessions</div>
<div>{number.format(value)}</div>
</div>
<div className="flex items-center justify-between gap-8 font-mono font-medium">
<div className="text-muted-foreground">Share</div>
<div>{number.format(round(pct, 1))} %</div>
</div>
</ChartTooltipItem>
</ChartTooltipContainer>
</SankeyPortalTooltip>
);
}}
linkTooltip={({ link }: any) => {
const sourceLabel =
link?.source?.data?.label ??
link?.source?.label ??
link?.source?.id;
const targetLabel =
link?.target?.data?.label ??
link?.target?.label ??
link?.target?.id;
const value = link?.value ?? 0;
const sourceValue =
link?.source?.data?.value ?? link?.source?.value ?? 0;
const pctOfTotal =
totalSessions > 0 ? (value / totalSessions) * 100 : 0;
const pctOfSource =
sourceValue > 0 ? (value / sourceValue) * 100 : 0;
const sourceStep = link?.source?.data?.step;
const targetStep = link?.target?.data?.step;
const color =
link?.color ??
link?.source?.color ??
link?.source?.data?.nodeColor ??
'#64748b';
return (
<SankeyPortalTooltip>
<ChartTooltipContainer>
<ChartTooltipHeader>
<div className="min-w-0 flex-1 font-medium break-words">
{sourceLabel}
<ArrowRightIcon className="size-2 inline-block mx-3" />
{targetLabel}
</div>
{typeof sourceStep === 'number' &&
typeof targetStep === 'number' && (
<div className="shrink-0 text-muted-foreground">
{sourceStep} {targetStep}
</div>
)}
</ChartTooltipHeader>
<ChartTooltipItem color={color} innerClassName="gap-2">
<div className="flex items-center justify-between gap-8 font-mono font-medium">
<div className="text-muted-foreground">Sessions</div>
<div>{number.format(value)}</div>
</div>
<div className="flex items-center justify-between gap-8 font-mono text-sm">
<div className="text-muted-foreground">% of total</div>
<div>{number.format(round(pctOfTotal, 1))} %</div>
</div>
<div className="flex items-center justify-between gap-8 font-mono text-sm">
<div className="text-muted-foreground">% of source</div>
<div>{number.format(round(pctOfSource, 1))} %</div>
</div>
</ChartTooltipItem>
</ChartTooltipContainer>
</SankeyPortalTooltip>
);
}}
label={(node: any) => {
const label = node.data?.label || node.label || node.id;
return truncate(label, 30, 'middle');
}}
labelTextColor={appTheme === 'dark' ? '#e2e8f0' : '#0f172a'}
nodeSpacing={10}
/>
</div>
</AspectContainer>
);
}

View File

@@ -0,0 +1,93 @@
import { useTRPC } from '@/integrations/trpc/react';
import { useQuery } from '@tanstack/react-query';
import type { IChartInput } from '@openpanel/validation';
import { AspectContainer } from '../aspect-container';
import { ReportChartEmpty } from '../common/empty';
import { ReportChartError } from '../common/error';
import { ReportChartLoading } from '../common/loading';
import { useReportChartContext } from '../context';
import { Chart } from './chart';
export function ReportSankeyChart() {
const {
report: {
series,
range,
projectId,
options,
startDate,
endDate,
breakdowns,
},
isLazyLoading,
} = useReportChartContext();
if (!options) {
return <Empty />;
}
const input: IChartInput = {
series,
range,
projectId,
interval: 'day',
chartType: 'sankey',
breakdowns,
options,
metric: 'sum',
startDate,
endDate,
limit: 20,
previous: false,
};
const trpc = useTRPC();
const res = useQuery(
trpc.chart.sankey.queryOptions(input, {
enabled: !isLazyLoading && input.series.length > 0,
}),
);
if (isLazyLoading || res.isLoading) {
return <Loading />;
}
if (res.isError) {
return <Error />;
}
if (!res.data || res.data.nodes.length === 0) {
return <Empty />;
}
return (
<div className="col gap-4">
<Chart data={res.data} />
</div>
);
}
function Loading() {
return (
<AspectContainer>
<ReportChartLoading />
</AspectContainer>
);
}
function Error() {
return (
<AspectContainer>
<ReportChartError />
</AspectContainer>
);
}
function Empty() {
return (
<AspectContainer>
<ReportChartEmpty />
</AspectContainer>
);
}

View File

@@ -5,6 +5,7 @@ import {
ChartColumnIncreasingIcon,
ConeIcon,
GaugeIcon,
GitBranchIcon,
Globe2Icon,
LineChartIcon,
type LucideIcon,
@@ -58,6 +59,7 @@ export function ReportChartType({
retention: UsersIcon,
map: Globe2Icon,
conversion: TrendingUpIcon,
sankey: GitBranchIcon,
};
return (

View File

@@ -1,6 +1,5 @@
import type { PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from '@reduxjs/toolkit';
import { endOfDay, format, isSameDay, isSameMonth, startOfDay } from 'date-fns';
import { shortId } from '@openpanel/common';
import {
@@ -12,12 +11,12 @@ import {
import type {
IChartBreakdown,
IChartEventItem,
IChartFormula,
IChartLineType,
IChartProps,
IChartRange,
IChartType,
IInterval,
IReportOptions,
UnionOmit,
zCriteria,
} from '@openpanel/validation';
@@ -28,6 +27,7 @@ type InitialState = IChartProps & {
ready: boolean;
startDate: string | null;
endDate: string | null;
options?: IReportOptions;
};
// First approach: define the initial state using that type
@@ -53,6 +53,7 @@ const initialState: InitialState = {
criteria: 'on_or_after',
funnelGroup: undefined,
funnelWindow: undefined,
options: undefined,
};
export const reportSlice = createSlice({
@@ -187,6 +188,16 @@ export const reportSlice = createSlice({
state.dirty = true;
state.chartType = action.payload;
// Initialize sankey options if switching to sankey
if (action.payload === 'sankey' && !state.options) {
state.options = {
type: 'sankey',
mode: 'after',
steps: 5,
exclude: [],
};
}
if (
!isMinuteIntervalEnabledByRange(state.range) &&
state.interval === 'minute'
@@ -271,6 +282,66 @@ export const reportSlice = createSlice({
state.dirty = true;
state.funnelWindow = action.payload || undefined;
},
changeOptions(state, action: PayloadAction<IReportOptions | undefined>) {
state.dirty = true;
state.options = action.payload || undefined;
},
changeSankeyMode(
state,
action: PayloadAction<'between' | 'after' | 'before'>,
) {
state.dirty = true;
if (!state.options) {
state.options = {
type: 'sankey',
mode: action.payload,
steps: 5,
exclude: [],
};
} else if (state.options.type === 'sankey') {
state.options.mode = action.payload;
}
},
changeSankeySteps(state, action: PayloadAction<number>) {
state.dirty = true;
if (!state.options) {
state.options = {
type: 'sankey',
mode: 'after',
steps: action.payload,
exclude: [],
};
} else if (state.options.type === 'sankey') {
state.options.steps = action.payload;
}
},
changeSankeyExclude(state, action: PayloadAction<string[]>) {
state.dirty = true;
if (!state.options) {
state.options = {
type: 'sankey',
mode: 'after',
steps: 5,
exclude: action.payload,
};
} else if (state.options.type === 'sankey') {
state.options.exclude = action.payload;
}
},
changeSankeyInclude(state, action: PayloadAction<string[] | undefined>) {
state.dirty = true;
if (!state.options) {
state.options = {
type: 'sankey',
mode: 'after',
steps: 5,
exclude: [],
include: action.payload,
};
} else if (state.options.type === 'sankey') {
state.options.include = action.payload;
}
},
reorderEvents(
state,
action: PayloadAction<{ fromIndex: number; toIndex: number }>,
@@ -311,6 +382,11 @@ export const {
changeUnit,
changeFunnelGroup,
changeFunnelWindow,
changeOptions,
changeSankeyMode,
changeSankeySteps,
changeSankeyExclude,
changeSankeyInclude,
reorderEvents,
} = reportSlice.actions;

View File

@@ -23,15 +23,13 @@ import {
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { shortId } from '@openpanel/common';
import { alphabetIds } from '@openpanel/constants';
import type {
IChartEvent,
IChartEventItem,
IChartFormula,
} from '@openpanel/validation';
import { FilterIcon, HandIcon, PiIcon } from 'lucide-react';
import { ReportSegment } from '../ReportSegment';
import { HandIcon, PiIcon, PlusIcon } from 'lucide-react';
import {
addSerie,
changeEvent,
@@ -39,27 +37,21 @@ import {
removeEvent,
reorderEvents,
} from '../reportSlice';
import { EventPropertiesCombobox } from './EventPropertiesCombobox';
import { PropertiesCombobox } from './PropertiesCombobox';
import type { ReportEventMoreProps } from './ReportEventMore';
import { ReportEventMore } from './ReportEventMore';
import { FiltersList } from './filters/FiltersList';
import {
ReportSeriesItem,
type ReportSeriesItemProps,
} from './ReportSeriesItem';
function SortableSeries({
function SortableReportSeriesItem({
event,
index,
showSegment,
showAddFilter,
isSelectManyEvents,
...props
}: {
event: IChartEventItem | IChartEvent;
index: number;
showSegment: boolean;
showAddFilter: boolean;
isSelectManyEvents: boolean;
} & React.HTMLAttributes<HTMLDivElement>) {
const dispatch = useDispatch();
}: Omit<ReportSeriesItemProps, 'renderDragHandle'>) {
const eventId = 'type' in event ? event.id : (event as IChartEvent).id;
const { attributes, listeners, setNodeRef, transform, transition } =
useSortable({ id: eventId ?? '' });
@@ -69,85 +61,26 @@ function SortableSeries({
transition,
};
// Normalize event to have type field
const normalizedEvent: IChartEventItem =
'type' in event ? event : { ...event, type: 'event' as const };
const isFormula = normalizedEvent.type === 'formula';
const chartEvent = isFormula
? null
: (normalizedEvent as IChartEventItem & { type: 'event' });
return (
<div ref={setNodeRef} style={style} {...attributes} {...props}>
<div className="flex items-center gap-2 p-2 group">
<button className="cursor-grab active:cursor-grabbing" {...listeners}>
<ColorSquare className="relative">
<HandIcon className="size-3 opacity-0 scale-50 group-hover:opacity-100 group-hover:scale-100 transition-all absolute inset-1" />
<span className="block group-hover:opacity-0 group-hover:scale-0 transition-all">
{alphabetIds[index]}
</span>
</ColorSquare>
</button>
{props.children}
</div>
{/* Segment and Filter buttons - only for events */}
{chartEvent && (showSegment || showAddFilter) && (
<div className="flex gap-2 p-2 pt-0">
{showSegment && (
<ReportSegment
value={chartEvent.segment}
onChange={(segment) => {
dispatch(
changeEvent({
...chartEvent,
segment,
}),
);
}}
/>
)}
{showAddFilter && (
<PropertiesCombobox
event={chartEvent}
onSelect={(action) => {
dispatch(
changeEvent({
...chartEvent,
filters: [
...chartEvent.filters,
{
id: shortId(),
name: action.value,
operator: 'is',
value: [],
},
],
}),
);
}}
>
{(setOpen) => (
<button
onClick={() => setOpen((p) => !p)}
type="button"
className="flex items-center gap-1 rounded-md border border-border bg-card p-1 px-2 text-sm font-medium leading-none"
>
<FilterIcon size={12} /> Add filter
</button>
)}
</PropertiesCombobox>
)}
{showSegment && chartEvent.segment.startsWith('property_') && (
<EventPropertiesCombobox event={chartEvent} />
)}
</div>
)}
{/* Filters - only for events */}
{chartEvent && !isSelectManyEvents && <FiltersList event={chartEvent} />}
<div ref={setNodeRef} style={style} {...attributes}>
<ReportSeriesItem
event={event}
index={index}
showSegment={showSegment}
showAddFilter={showAddFilter}
isSelectManyEvents={isSelectManyEvents}
renderDragHandle={(index) => (
<button className="cursor-grab active:cursor-grabbing" {...listeners}>
<ColorSquare className="relative">
<HandIcon className="size-3 opacity-0 scale-50 group-hover:opacity-100 group-hover:scale-100 transition-all absolute inset-1" />
<span className="block group-hover:opacity-0 group-hover:scale-0 transition-all">
{alphabetIds[index]}
</span>
</ColorSquare>
</button>
)}
{...props}
/>
</div>
);
}
@@ -161,12 +94,23 @@ export function ReportSeries() {
projectId,
});
const showSegment = !['retention', 'funnel'].includes(chartType);
const showAddFilter = !['retention'].includes(chartType);
const showDisplayNameInput = !['retention'].includes(chartType);
const showSegment = !['retention', 'funnel', 'sankey'].includes(chartType);
const showAddFilter = !['retention', 'sankey'].includes(chartType);
const showDisplayNameInput = !['retention', 'sankey'].includes(chartType);
const options = useSelector((state) => state.report.options);
const isSankey = chartType === 'sankey';
const isAddEventDisabled =
(chartType === 'retention' || chartType === 'conversion') &&
selectedSeries.length >= 2;
const isSankeyEventLimitReached =
isSankey &&
options &&
((options.type === 'sankey' &&
options.mode === 'between' &&
selectedSeries.length >= 2) ||
(options.type === 'sankey' &&
options.mode !== 'between' &&
selectedSeries.length >= 1));
const dispatchChangeEvent = useDebounceFn((event: IChartEventItem) => {
dispatch(changeEvent(event));
});
@@ -218,7 +162,8 @@ export function ReportSeries() {
const showFormula =
chartType !== 'conversion' &&
chartType !== 'funnel' &&
chartType !== 'retention';
chartType !== 'retention' &&
chartType !== 'sankey';
return (
<div>
@@ -239,7 +184,7 @@ export function ReportSeries() {
const isFormula = event.type === 'formula';
return (
<SortableSeries
<SortableReportSeriesItem
key={event.id}
event={event}
index={index}
@@ -348,13 +293,14 @@ export function ReportSeries() {
<ReportEventMore onClick={handleMore(event)} />
</>
)}
</SortableSeries>
</SortableReportSeriesItem>
);
})}
<div className="flex gap-2">
<ComboboxEvents
disabled={isAddEventDisabled}
className="flex-1"
disabled={isAddEventDisabled || isSankeyEventLimitReached}
value={''}
searchable
onChange={(value) => {
@@ -393,6 +339,7 @@ export function ReportSeries() {
type="button"
variant="outline"
icon={PiIcon}
className="flex-1 justify-start text-left"
onClick={() => {
dispatch(
addSerie({
@@ -405,6 +352,7 @@ export function ReportSeries() {
className="px-4"
>
Add Formula
<PlusIcon className="size-4 ml-auto text-muted-foreground" />
</Button>
)}
</div>

View File

@@ -0,0 +1,114 @@
import { ColorSquare } from '@/components/color-square';
import { useDispatch } from '@/redux';
import { shortId } from '@openpanel/common';
import { alphabetIds } from '@openpanel/constants';
import type { IChartEvent, IChartEventItem } from '@openpanel/validation';
import { FilterIcon } from 'lucide-react';
import { ReportSegment } from '../ReportSegment';
import { changeEvent } from '../reportSlice';
import { EventPropertiesCombobox } from './EventPropertiesCombobox';
import { PropertiesCombobox } from './PropertiesCombobox';
import { FiltersList } from './filters/FiltersList';
export interface ReportSeriesItemProps
extends React.HTMLAttributes<HTMLDivElement> {
event: IChartEventItem | IChartEvent;
index: number;
showSegment: boolean;
showAddFilter: boolean;
isSelectManyEvents: boolean;
renderDragHandle?: (index: number) => React.ReactNode;
}
export function ReportSeriesItem({
event,
index,
showSegment,
showAddFilter,
isSelectManyEvents,
renderDragHandle,
...props
}: ReportSeriesItemProps) {
const dispatch = useDispatch();
// Normalize event to have type field
const normalizedEvent: IChartEventItem =
'type' in event ? event : { ...event, type: 'event' as const };
const isFormula = normalizedEvent.type === 'formula';
const chartEvent = isFormula
? null
: (normalizedEvent as IChartEventItem & { type: 'event' });
return (
<div {...props}>
<div className="flex items-center gap-2 p-2 group">
{renderDragHandle ? (
renderDragHandle(index)
) : (
<ColorSquare>
<span className="block">{alphabetIds[index]}</span>
</ColorSquare>
)}
{props.children}
</div>
{/* Segment and Filter buttons - only for events */}
{chartEvent && (showSegment || showAddFilter) && (
<div className="flex gap-2 p-2 pt-0">
{showSegment && (
<ReportSegment
value={chartEvent.segment}
onChange={(segment) => {
dispatch(
changeEvent({
...chartEvent,
segment,
}),
);
}}
/>
)}
{showAddFilter && (
<PropertiesCombobox
event={chartEvent}
onSelect={(action) => {
dispatch(
changeEvent({
...chartEvent,
filters: [
...chartEvent.filters,
{
id: shortId(),
name: action.value,
operator: 'is',
value: [],
},
],
}),
);
}}
>
{(setOpen) => (
<button
onClick={() => setOpen((p) => !p)}
type="button"
className="flex items-center gap-1 rounded-md border border-border bg-card p-1 px-2 text-sm font-medium leading-none"
>
<FilterIcon size={12} /> Add filter
</button>
)}
</PropertiesCombobox>
)}
{showSegment && chartEvent.segment.startsWith('property_') && (
<EventPropertiesCombobox event={chartEvent} />
)}
</div>
)}
{/* Filters - only for events */}
{chartEvent && !isSelectManyEvents && <FiltersList event={chartEvent} />}
</div>
);
}

View File

@@ -1,15 +1,22 @@
import { Combobox } from '@/components/ui/combobox';
import { useDispatch, useSelector } from '@/redux';
import { ComboboxEvents } from '@/components/ui/combobox-events';
import { InputEnter } from '@/components/ui/input-enter';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { useAppParams } from '@/hooks/use-app-params';
import { useEventNames } from '@/hooks/use-event-names';
import { useMemo } from 'react';
import {
changeCriteria,
changeFunnelGroup,
changeFunnelWindow,
changePrevious,
changeSankeyExclude,
changeSankeyInclude,
changeSankeyMode,
changeSankeySteps,
changeUnit,
} from '../reportSlice';
@@ -20,13 +27,16 @@ export function ReportSettings() {
const unit = useSelector((state) => state.report.unit);
const funnelGroup = useSelector((state) => state.report.funnelGroup);
const funnelWindow = useSelector((state) => state.report.funnelWindow);
const options = useSelector((state) => state.report.options);
const dispatch = useDispatch();
const { projectId } = useAppParams();
const eventNames = useEventNames({ projectId });
const fields = useMemo(() => {
const fields = [];
if (chartType !== 'retention') {
if (chartType !== 'retention' && chartType !== 'sankey') {
fields.push('previous');
}
@@ -40,6 +50,13 @@ export function ReportSettings() {
fields.push('funnelWindow');
}
if (chartType === 'sankey') {
fields.push('sankeyMode');
fields.push('sankeySteps');
fields.push('sankeyExclude');
fields.push('sankeyInclude');
}
return fields;
}, [chartType]);
@@ -149,6 +166,89 @@ export function ReportSettings() {
/>
</div>
)}
{fields.includes('sankeyMode') && options?.type === 'sankey' && (
<div className="flex items-center justify-between gap-4">
<span className="whitespace-nowrap font-medium">Mode</span>
<Combobox
align="end"
placeholder="Select mode"
value={options?.mode || 'after'}
onChange={(val) => {
dispatch(
changeSankeyMode(val as 'between' | 'after' | 'before'),
);
}}
items={[
{
label: 'After',
value: 'after',
},
{
label: 'Before',
value: 'before',
},
{
label: 'Between',
value: 'between',
},
]}
/>
</div>
)}
{fields.includes('sankeySteps') && options?.type === 'sankey' && (
<div className="flex items-center justify-between gap-4">
<span className="whitespace-nowrap font-medium">Steps</span>
<InputEnter
type="number"
value={options?.steps ? String(options.steps) : '5'}
placeholder="Default: 5"
onChangeValue={(value) => {
const parsed = Number.parseInt(value, 10);
if (Number.isNaN(parsed) || parsed < 2 || parsed > 10) {
dispatch(changeSankeySteps(5));
} else {
dispatch(changeSankeySteps(parsed));
}
}}
/>
</div>
)}
{fields.includes('sankeyExclude') && options?.type === 'sankey' && (
<div className="flex flex-col gap-2">
<span className="whitespace-nowrap font-medium">
Exclude Events
</span>
<ComboboxEvents
multiple
searchable
value={options?.exclude || []}
onChange={(value) => {
dispatch(changeSankeyExclude(value));
}}
items={eventNames.filter((item) => item.name !== '*')}
placeholder="Select events to exclude"
/>
</div>
)}
{fields.includes('sankeyInclude') && options?.type === 'sankey' && (
<div className="flex flex-col gap-2">
<span className="whitespace-nowrap font-medium">
Include events
</span>
<ComboboxEvents
multiple
searchable
value={options?.include || []}
onChange={(value) => {
dispatch(
changeSankeyInclude(value.length > 0 ? value : undefined),
);
}}
items={eventNames.filter((item) => item.name !== '*')}
placeholder="Leave empty to include all"
/>
</div>
)}
</div>
</div>
);

View File

@@ -5,14 +5,24 @@ import { useSelector } from '@/redux';
import { ReportBreakdowns } from './ReportBreakdowns';
import { ReportSeries } from './ReportSeries';
import { ReportSettings } from './ReportSettings';
import { ReportFixedEvents } from './report-fixed-events';
export function ReportSidebar() {
const { chartType } = useSelector((state) => state.report);
const showBreakdown = chartType !== 'retention';
const { chartType, options } = useSelector((state) => state.report);
const showBreakdown = chartType !== 'retention' && chartType !== 'sankey';
const showFixedEvents = chartType === 'sankey';
return (
<>
<div className="flex flex-col gap-8">
<ReportSeries />
{showFixedEvents ? (
<ReportFixedEvents
numberOfEvents={
options?.type === 'sankey' && options.mode === 'between' ? 2 : 1
}
/>
) : (
<ReportSeries />
)}
{showBreakdown && <ReportBreakdowns />}
<ReportSettings />
</div>

View File

@@ -0,0 +1,223 @@
import { ColorSquare } from '@/components/color-square';
import { ComboboxEvents } from '@/components/ui/combobox-events';
import { Input } from '@/components/ui/input';
import { InputEnter } from '@/components/ui/input-enter';
import { useAppParams } from '@/hooks/use-app-params';
import { useDebounceFn } from '@/hooks/use-debounce-fn';
import { useEventNames } from '@/hooks/use-event-names';
import { useDispatch, useSelector } from '@/redux';
import { alphabetIds } from '@openpanel/constants';
import type {
IChartEvent,
IChartEventItem,
IChartFormula,
} from '@openpanel/validation';
import {
addSerie,
changeEvent,
duplicateEvent,
removeEvent,
} from '../reportSlice';
import type { ReportEventMoreProps } from './ReportEventMore';
import { ReportEventMore } from './ReportEventMore';
import { ReportSeriesItem } from './ReportSeriesItem';
export function ReportFixedEvents({
numberOfEvents,
}: {
numberOfEvents: number;
}) {
const selectedSeries = useSelector((state) => state.report.series);
const chartType = useSelector((state) => state.report.chartType);
const dispatch = useDispatch();
const { projectId } = useAppParams();
const eventNames = useEventNames({
projectId,
});
const showSegment = !['retention', 'funnel', 'sankey'].includes(chartType);
const showAddFilter = !['retention'].includes(chartType);
const showDisplayNameInput = !['retention', 'sankey'].includes(chartType);
const dispatchChangeEvent = useDebounceFn((event: IChartEventItem) => {
dispatch(changeEvent(event));
});
const isSelectManyEvents = chartType === 'retention';
const handleMore = (event: IChartEventItem | IChartEvent) => {
const callback: ReportEventMoreProps['onClick'] = (action) => {
switch (action) {
case 'remove': {
return dispatch(
removeEvent({
id: 'type' in event ? event.id : (event as IChartEvent).id,
}),
);
}
case 'duplicate': {
const normalized =
'type' in event ? event : { ...event, type: 'event' as const };
return dispatch(duplicateEvent(normalized));
}
}
};
return callback;
};
const dispatchChangeFormula = useDebounceFn((formula: IChartFormula) => {
dispatch(changeEvent(formula));
});
const showFormula =
chartType !== 'conversion' &&
chartType !== 'funnel' &&
chartType !== 'retention' &&
chartType !== 'sankey';
return (
<div>
<h3 className="mb-2 font-medium">Metrics</h3>
<div className="flex flex-col gap-4">
{Array.from({ length: numberOfEvents }, (_, index) => ({
slotId: `fixed-event-slot-${index}`,
index,
})).map(({ slotId, index }) => {
const event = selectedSeries[index];
// If no event exists at this index, render an empty slot
if (!event) {
return (
<div key={slotId} className="rounded-lg border bg-def-100">
<div className="flex items-center gap-2 p-2">
<ColorSquare>
<span className="block">{alphabetIds[index]}</span>
</ColorSquare>
<ComboboxEvents
className="flex-1"
searchable
multiple={isSelectManyEvents as false}
value={''}
onChange={(value) => {
if (isSelectManyEvents) {
dispatch(
addSerie({
type: 'event',
segment: 'user',
name: value,
filters: [
{
name: 'name',
operator: 'is',
value: [value],
},
],
}),
);
} else {
dispatch(
addSerie({
type: 'event',
name: value,
segment: 'event',
filters: [],
}),
);
}
}}
items={eventNames}
placeholder="Select event"
/>
</div>
</div>
);
}
const isFormula = event.type === 'formula';
if (isFormula) {
return null;
}
return (
<ReportSeriesItem
key={event.id}
event={event}
index={index}
showSegment={showSegment}
showAddFilter={showAddFilter}
isSelectManyEvents={isSelectManyEvents}
className="rounded-lg border bg-def-100"
>
<ComboboxEvents
className="flex-1"
searchable
multiple={isSelectManyEvents as false}
value={
(isSelectManyEvents
? ((
event as IChartEventItem & {
type: 'event';
}
).filters[0]?.value ?? [])
: (
event as IChartEventItem & {
type: 'event';
}
).name) as any
}
onChange={(value) => {
dispatch(
changeEvent(
Array.isArray(value)
? {
id: event.id,
type: 'event',
segment: 'user',
filters: [
{
name: 'name',
operator: 'is',
value: value,
},
],
name: '*',
}
: {
...event,
type: 'event',
name: value,
filters: [],
},
),
);
}}
items={eventNames}
placeholder="Select event"
/>
{showDisplayNameInput && (
<Input
placeholder={
(event as IChartEventItem & { type: 'event' }).name
? `${(event as IChartEventItem & { type: 'event' }).name} (${alphabetIds[index]})`
: 'Display name'
}
defaultValue={
(event as IChartEventItem & { type: 'event' }).displayName
}
onChange={(e) => {
dispatchChangeEvent({
...(event as IChartEventItem & {
type: 'event';
}),
displayName: e.target.value,
});
}}
/>
)}
<ReportEventMore onClick={handleMore(event)} />
</ReportSeriesItem>
);
})}
</div>
</div>
);
}

View File

@@ -178,7 +178,7 @@ export function ComboboxEvents<
<CommandEmpty>Nothing selected</CommandEmpty>
<VirtualList
height={400}
height={300}
data={items.filter((item) => {
if (search === '') return true;
return item.name.toLowerCase().includes(search.toLowerCase());

View File

@@ -12,6 +12,7 @@ import {
BarChartHorizontalIcon,
ChartScatterIcon,
ConeIcon,
GitBranchIcon,
Globe2Icon,
HashIcon,
LayoutPanelTopIcon,
@@ -153,6 +154,7 @@ function Component() {
area: AreaChartIcon,
retention: ChartScatterIcon,
conversion: TrendingUpIcon,
sankey: GitBranchIcon,
}[report.chartType];
return (

View File

@@ -36,5 +36,6 @@ function Component() {
const { reportId } = Route.useParams();
const trpc = useTRPC();
const query = useSuspenseQuery(trpc.report.get.queryOptions({ reportId }));
console.log(query.data);
return <ReportEditor report={query.data} />;
}