OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { AspectContainer } from '../aspect-container';
import { ChartWithTable, TableCard } from '../common/chart-with-table';
import { ReportChartEmpty } from '../common/empty';
import { ReportChartError } from '../common/error';
import { ReportChartLoading } from '../common/loading';
import { useReportChartContext } from '../context';
import { Chart } from './chart';
import { CohortTable } from './table';
import { useTRPC } from '@/integrations/trpc/react';
export function ReportRetentionChart() {
const { isLazyLoading, report, shareId } = useReportChartContext();
const eventSeries = report.series.filter((item) => item.type === 'event');
const firstEvent = (eventSeries[0]?.filters?.[0]?.value ?? []).map(String);
const secondEvent = (eventSeries[1]?.filters?.[0]?.value ?? []).map(String);
// filters[0] on each retention series is the event-name selector; everything
// else is an audience filter (property or cohort) applied to the cohort.
// Report-level global filters apply to the whole retention audience too.
const filters = [
...(report.globalFilters ?? []),
...eventSeries.flatMap((item) =>
(item.filters ?? []).filter((filter) => filter.name !== 'name')
),
];
const hasEvents = firstEvent.length > 0 && secondEvent.length > 0;
const retentionOptions =
report.options?.type === 'retention' ? report.options : undefined;
const criteria = retentionOptions?.criteria ?? 'on_or_after';
const trpc = useTRPC();
const res = useQuery(
trpc.chart.cohort.queryOptions(
{
firstEvent,
secondEvent,
filters,
projectId: report.projectId,
range: report.range,
startDate: report.startDate,
endDate: report.endDate,
criteria,
interval: report.interval,
shareId,
id: 'id' in report ? report.id : undefined,
},
{
placeholderData: keepPreviousData,
enabled: hasEvents && !isLazyLoading,
}
)
);
if (!hasEvents) {
return <Disabled />;
}
if (isLazyLoading || res.isLoading) {
return <Loading />;
}
if (res.isError) {
return <Error />;
}
if (!res.data || res.data?.length === 0) {
return <Empty />;
}
return (
<ChartWithTable
chart={<Chart data={res.data} />}
tables={
<TableCard>
<CohortTable data={res.data} />
</TableCard>
}
/>
);
}
function Loading() {
return (
<AspectContainer>
<ReportChartLoading />
</AspectContainer>
);
}
function Error() {
return (
<AspectContainer>
<ReportChartError />
</AspectContainer>
);
}
function Empty() {
return (
<AspectContainer>
<ReportChartEmpty />
</AspectContainer>
);
}
function Disabled() {
return (
<AspectContainer>
<ReportChartEmpty title="Select 2 events">
We need two events to determine the retention rate.
</ReportChartEmpty>
</AspectContainer>
);
}