OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): events stats has range, interval and event pickers, with stacked bars per event (#554)
Carl-Gerhard Lindesvärd615b65da706f
diff --git a/apps/start/e2e/data-events.spec.ts b/apps/start/e2e/data-events.spec.tsindex 9f27b0567..1320adb12 100644--- a/apps/start/e2e/data-events.spec.ts+++ b/apps/start/e2e/data-events.spec.ts@@ -366,20 +366,77 @@ test.describe('events list', () => {test('stats tab renders its four charts', async ({ page }) => {await open(page, `${SHOP}/events/stats`);for (const title of [- 'Events per day',+ 'Events over time','Share of events','Events by name',- 'Events over time',+ 'Trend by event',]) {await expect(page.getByText(title, { exact: true })).toBeVisible();}await expect(page.getByText('screen_view').first()).toBeVisible();+ // The toolbar carries its own range, interval and event pickers.+ await expect(+ page.getByRole('button', { name: 'Day', exact: true })+ ).toBeVisible();+ await expect(+ page.getByRole('combobox').filter({ hasText: 'All events' })+ ).toBeVisible();await page.screenshot({path: `${SHOTS}/events-stats.png`,fullPage: true,});});+ test('stats tab follows the range, interval and event pickers', async ({+ page,+ }) => {+ const problems = watch(page);+ await open(+ page,+ `${SHOP}/events/stats?range=today&overrideInterval=hour&events=add_to_cart,search`+ );+ await expect(+ page.getByRole('button', { name: 'Today', exact: true })+ ).toBeVisible();+ await expect(+ page.getByRole('button', { name: 'Hour', exact: true })+ ).toBeVisible();+ await expect(+ page.getByRole('combobox').filter({ hasText: 'add_to_cart' })+ ).toBeVisible();+ for (const event of ['add_to_cart', 'search']) {+ await expect(+ page.getByRole('button', { name: event, exact: true })+ ).toBeVisible();+ }+ // Every widget (time series and aggregates alike) shows exactly the+ // picked events (two, so the time series render a legend), and both+ // time series are bucketed by hour.+ const card = (title: string) =>+ page+ .locator('div.card')+ .filter({ has: page.locator('.title', { hasText: title }) });+ for (const title of [+ 'Events over time',+ 'Share of events',+ 'Events by name',+ 'Trend by event',+ ]) {+ for (const event of ['add_to_cart', 'search']) {+ await expect(card(title).getByText(event).first()).toBeVisible();+ }+ await expect(card(title).getByText('screen_view')).toHaveCount(0);+ }+ for (const title of ['Events over time', 'Trend by event']) {+ await expect(card(title).getByText('00:00').first()).toBeVisible();+ }+ await page.screenshot({+ path: `${SHOTS}/events-stats-filtered.png`,+ fullPage: true,+ });+ expect(problems).toEqual([]);+ });+test('mobile viewport has no horizontal page scroll', async ({ page }) => {await page.setViewportSize({ width: 390, height: 844 });await open(page, `${SHOP}/events`);diff --git a/apps/start/src/components/charts/time-series-chart-shell.tsx b/apps/start/src/components/charts/time-series-chart-shell.tsxindex aa3a26896..013420db0 100644--- a/apps/start/src/components/charts/time-series-chart-shell.tsx+++ b/apps/start/src/components/charts/time-series-chart-shell.tsx@@ -316,6 +316,16 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({[children]);+ const slotCount =+ xDomain && xDomainSlotCount != null+ ? xDomainSlotCount+ : visiblePlotData.length;+ // Bars are centred on their x, so with a range that starts at 0 the first+ // and last bar spill into the margins and over the y-axis labels. Start the+ // range half a slot in, like a band scale, whenever bars are drawn.+ const hasBars = (composedBarDataKeys?.length ?? 0) > 0;+ const xInset = hasBars && slotCount > 0 ? innerWidth / slotCount / 2 : 0;+const xScale = useMemo(() => {const minTime = xDomain? xDomain[0].getTime()@@ -330,10 +340,10 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({}return scaleTime({- range: [0, innerWidth],+ range: [xInset, innerWidth - xInset],domain: [minTime, maxTime],});- }, [innerWidth, plotData, projectionConfigs, xAccessor, xDomain]);+ }, [innerWidth, xInset, plotData, projectionConfigs, xAccessor, xDomain]);// When brushing, keep the full series for path rendering so edge fades stay// anchored to the viewport while the line pans through them. Y-domain and@@ -350,15 +360,11 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({}, [seriesSourceData, innerWidth, lines]);const columnWidth = useMemo(() => {- const slotCount =- xDomain && xDomainSlotCount != null- ? xDomainSlotCount- : visiblePlotData.length;if (slotCount < 2) {return 0;}- return innerWidth / (slotCount - 1);- }, [innerWidth, visiblePlotData.length, xDomain, xDomainSlotCount]);+ return (innerWidth - 2 * xInset) / (slotCount - 1);+ }, [innerWidth, xInset, slotCount]);const yDomainSkeletonByAxis = useMemo(() =>diff --git a/apps/start/src/components/report-chart/shortcut.tsx b/apps/start/src/components/report-chart/shortcut.tsxindex cdf95ffe4..ed3f6f36d 100644--- a/apps/start/src/components/report-chart/shortcut.tsx+++ b/apps/start/src/components/report-chart/shortcut.tsx@@ -4,23 +4,30 @@ import type { ReportChartProps } from './context';type ChartRootShortcutProps = Omit<ReportChartProps, 'report'> & {projectId: ReportChartProps['report']['projectId'];range?: ReportChartProps['report']['range'];+ startDate?: ReportChartProps['report']['startDate'];+ endDate?: ReportChartProps['report']['endDate'];previous?: ReportChartProps['report']['previous'];chartType?: ReportChartProps['report']['chartType'];interval?: ReportChartProps['report']['interval'];series: ReportChartProps['report']['series'];breakdowns?: ReportChartProps['report']['breakdowns'];lineType?: ReportChartProps['report']['lineType'];+ /** Chart-type specific report options (stacked histogram, funnel mode…), as opposed to display `options`. */+ reportOptions?: ReportChartProps['report']['options'];};export const ReportChartShortcut = ({projectId,range = '7d',+ startDate,+ endDate,previous = false,chartType = 'linear',interval = 'day',series,breakdowns,lineType = 'monotone',+ reportOptions,options,}: ChartRootShortcutProps) => {return (@@ -29,6 +36,8 @@ export const ReportChartShortcut = ({report={{projectId,range,+ startDate,+ endDate,breakdowns: breakdowns ?? [],previous,chartType,@@ -36,6 +45,7 @@ export const ReportChartShortcut = ({series,lineType,metric: 'sum',+ options: reportOptions,}}/>);diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsxindex 621760c86..24c9c1932 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx@@ -1,11 +1,21 @@-import type { IChartEventItem } from '@openpanel/core/modules/report/report.constants';+import type {+ IChartBreakdown,+ IChartEventItem,+ IHistogramOptions,+} from '@openpanel/core/modules/report/report.constants';import { createFileRoute } from '@tanstack/react-router';+import { useMemo } from 'react';import {OverviewFilterButton,OverviewFiltersButtons,} from '@/components/overview/filters/overview-filters-buttons';+import { OverviewInterval } from '@/components/overview/overview-interval';+import { OverviewRange } from '@/components/overview/overview-range';+import { useOverviewOptions } from '@/components/overview/useOverviewOptions';import { ReportChartShortcut } from '@/components/report-chart/shortcut';+import { ComboboxEvents } from '@/components/ui/combobox-events';import { Widget, WidgetBody, WidgetHead } from '@/components/widget';+import { useEventNames } from '@/hooks/use-event-names';import {useEventQueryFilters,useEventQueryNamesFilter,@@ -17,53 +27,76 @@ export const Route = createFileRoute(component: Component,});+const BREAKDOWN_BY_EVENT_NAME: IChartBreakdown[] = [{ id: 'A', name: 'name' }];+const STACKED_HISTOGRAM: IHistogramOptions = {+ type: 'histogram',+ stacked: true,+};+// Breaking down by `name` nests the event under itself; show only the event.+const breakdownChartOptions = {+ hideTable: true,+ renderSerieName(names: string[]) {+ return names.at(-1);+ },+};+function Component() {const { projectId } = Route.useParams();+ const { range, startDate, endDate, interval } = useOverviewOptions();const [filters] = useEventQueryFilters();- const [events] = useEventQueryNamesFilter();- const fallback: IChartEventItem[] = [- {- id: 'A',- name: '*',- displayName: 'All events',+ const [eventNames, setEventNames] = useEventQueryNamesFilter();+ const availableEvents = useEventNames({ projectId, anyEvents: false });++ const series = useMemo<IChartEventItem[]>(() => {+ const names = eventNames.length > 0 ? eventNames : ['*'];+ return names.map((name) => ({+ id: name,+ name,+ displayName: name === '*' ? 'All events' : name,segment: 'event',filters: filters ?? [],type: 'event',- },- ];+ }));+ }, [eventNames, filters]);++ const timeWindow = { range, startDate, endDate, interval };return (<div>- <div className="mb-2 flex items-center gap-2">- <OverviewFilterButton enableEventsFilter />+ <div className="col mb-2 gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <OverviewRange />+ <OverviewInterval />+ <ComboboxEvents+ items={availableEvents}+ maxDisplayItems={2}+ multiple+ onChange={setEventNames}+ placeholder="All events"+ searchable+ value={eventNames}+ />+ <OverviewFilterButton enableEventsFilter />+ </div><OverviewFiltersButtons- className="justify-end p-0"+ className="p-0"filterModal={{ enableEventsFilter: true }}/></div><div className="grid grid-cols-1 gap-2 md:grid-cols-2"><Widget className="w-full"><WidgetHead>- <span className="title">Events per day</span>+ <span className="title">Events over time</span></WidgetHead><WidgetBody><ReportChartShortcut+ breakdowns={BREAKDOWN_BY_EVENT_NAME}chartType="histogram"- options={{ hideTable: true }}+ options={breakdownChartOptions}projectId={projectId}- range="30d"- series={- events && events.length > 0- ? events.map((name) => ({- id: name,- name,- displayName: name,- segment: 'event',- filters: filters ?? [],- type: 'event',- }))- : fallback- }+ reportOptions={STACKED_HISTOGRAM}+ series={series}+ {...timeWindow}/></WidgetBody></Widget>@@ -73,42 +106,12 @@ function Component() {</WidgetHead><WidgetBody><ReportChartShortcut- breakdowns={[- {- id: 'A',- name: 'name',- },- ]}+ breakdowns={BREAKDOWN_BY_EVENT_NAME}chartType="pie"- options={{- hideTable: true,- renderSerieName(names) {- return names.at(-1);- },- }}+ options={breakdownChartOptions}projectId={projectId}- range="30d"- series={- events && events.length > 0- ? events.map((name) => ({- id: name,- name,- displayName: name,- segment: 'event',- filters: filters ?? [],- type: 'event',- }))- : [- {- id: 'A',- name: '*',- displayName: 'All events',- segment: 'event',- filters: filters ?? [],- type: 'event',- },- ]- }+ series={series}+ {...timeWindow}/></WidgetBody></Widget>@@ -118,87 +121,27 @@ function Component() {</WidgetHead><WidgetBody><ReportChartShortcut- breakdowns={[- {- id: 'A',- name: 'name',- },- ]}+ breakdowns={BREAKDOWN_BY_EVENT_NAME}chartType="bar"- options={{- hideTable: true,- renderSerieName(names) {- return names.at(-1);- },- }}+ options={breakdownChartOptions}projectId={projectId}- range="30d"- series={- events && events.length > 0- ? events.map((name) => ({- id: name,- name,- displayName: name,- segment: 'event',- filters: filters ?? [],- type: 'event',- }))- : [- {- id: 'A',- name: '*',- displayName: 'All events',- segment: 'event',- filters: filters ?? [],- type: 'event',- },- ]- }+ series={series}+ {...timeWindow}/></WidgetBody></Widget><Widget className="w-full"><WidgetHead>- <span className="title">Events over time</span>+ <span className="title">Trend by event</span></WidgetHead><WidgetBody><ReportChartShortcut- breakdowns={[- {- id: 'A',- name: 'name',- },- ]}+ breakdowns={BREAKDOWN_BY_EVENT_NAME}chartType="linear"- options={{- hideTable: true,- renderSerieName(names) {- return names.at(-1);- },- }}+ options={breakdownChartOptions}projectId={projectId}- range="30d"- series={- events && events.length > 0- ? events.map((name) => ({- id: name,- name,- displayName: name,- segment: 'event',- filters: filters ?? [],- type: 'event',- }))- : [- {- id: 'A',- name: '*',- displayName: 'All events',- segment: 'event',- filters: filters ?? [],- type: 'event',- },- ]- }+ series={series}+ {...timeWindow}/></WidgetBody></Widget>