refactor Property components to be resused for both session/event data. Implement session-data screens + filtering. Remove all event-data specific compoenents/queries

This commit is contained in:
Francis Cao committed 2026-04-29 13:11:03 -07:00
1 parent 9da332c489
commit 680a1ca1a2
71 files changed
+2814 -958

No files matched your search

@@ -1,402 +0,0 @@
'use client';
import { Column, Grid, Text, useTheme } from '@umami/react-zen';
import { colord } from 'colord';
import {
differenceInCalendarDays,
format,
formatDistance,
isValid,
startOfDay,
startOfMonth,
startOfWeek,
startOfYear,
type Locale,
} from 'date-fns';
import { toZonedTime } from 'date-fns-tz';
import { type ReactNode, useCallback, useMemo } from 'react';
import { BarChart } from '@/components/charts/BarChart';
import { PieChart } from '@/components/charts/PieChart';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import { useEventDataDateSeriesQuery, useLocale, useMessages, useTimezone } from '@/components/hooks';
import { ListTable } from '@/components/metrics/ListTable';
import { MetricsBar } from '@/components/metrics/MetricsBar';
import { renderDateLabels } from '@/lib/charts';
import { getThemeColors } from '@/lib/colors';
import { CHART_COLORS } from '@/lib/constants';
import { formatDate, generateTimeSeries } from '@/lib/date';
import { formatLongNumber } from '@/lib/format';
import type { EventDataDateSeriesPoint, EventPropertyFilter } from '@/lib/types';
type DateChartUnit = 'day' | 'week' | 'month' | 'year';
type ParsedDateRow = EventDataDateSeriesPoint & { date: Date };
function parseDateValue(value: string) {
const normalized = value?.trim().replace(' ', 'T').replace(/Z$/, '').replace(/\.\d+$/, '');
const [datePart = '', timePart = '00:00:00'] = normalized.split('T');
const [year = 0, month = 1, day = 1] = datePart.split('-').map(Number);
const [hour = 0, minute = 0, second = 0] = timePart.split(':').map(Number);
const date = new Date(year, month - 1, day, hour, minute, second);
return isValid(date) ? date : null;
}
function InsightCard({
label,
value,
hint,
}: {
label: string;
value: string;
hint?: ReactNode;
}) {
return (
<Column
justifyContent="center"
paddingX="6"
paddingY="4"
borderRadius
backgroundColor="surface-base"
border
gap="2"
height="100%"
style={{ minWidth: 0 }}
>
<Text weight="bold" style={{ overflowWrap: 'anywhere' }}>
{label}
</Text>
<Text weight="bold" style={{ overflowWrap: 'anywhere' }}>
{value}
</Text>
{hint && (
<Text color="muted" style={{ overflowWrap: 'anywhere' }}>
{hint}
</Text>
)}
</Column>
);
}
function getChartUnit(minDate: Date, maxDate: Date): DateChartUnit {
const spanDays = differenceInCalendarDays(maxDate, minDate);
if (spanDays <= 45) return 'day';
if (spanDays <= 180) return 'week';
if (spanDays <= 730) return 'month';
return 'year';
}
function getBucketStart(date: Date, unit: DateChartUnit, dateLocale: Locale) {
switch (unit) {
case 'week':
return startOfWeek(date, { locale: dateLocale });
case 'month':
return startOfMonth(date);
case 'year':
return startOfYear(date);
default:
return startOfDay(date);
}
}
export function EventDataDateChart({
websiteId,
eventName,
propertyName,
eventFilters = [],
}: {
websiteId: string;
eventName: string;
propertyName: string;
eventFilters?: EventPropertyFilter[];
}) {
const { theme } = useTheme();
const { t, labels } = useMessages();
const { locale, dateLocale } = useLocale();
const { timezone } = useTimezone();
const { colors } = useMemo(() => getThemeColors(theme), [theme]);
const query = useEventDataDateSeriesQuery(websiteId, eventName, propertyName, eventFilters);
const rows = useMemo(() => query.data ?? [], [query.data]);
const total = useMemo(() => rows.reduce((sum, { y }) => sum + y, 0), [rows]);
const zonedNow = useMemo(() => toZonedTime(new Date(), timezone), [timezone]);
const exactDateRows = useMemo(() => {
return rows
.map(row => {
const date = parseDateValue(row.t);
return date ? { ...row, date } : null;
})
.filter((row): row is ParsedDateRow => row !== null)
.sort((a, b) => a.date.getTime() - b.date.getTime());
}, [rows]);
const minPropertyDate = exactDateRows[0]?.date ?? null;
const lastExactDateRow = exactDateRows[exactDateRows.length - 1];
const maxPropertyDate = lastExactDateRow?.date ?? null;
const chartUnit = useMemo(
() =>
minPropertyDate && maxPropertyDate
? getChartUnit(minPropertyDate, maxPropertyDate)
: 'day',
[minPropertyDate, maxPropertyDate],
);
const chartRows = useMemo(() => {
if (!exactDateRows.length) return [];
const buckets = exactDateRows.reduce(
(obj, row) => {
const bucketStart = getBucketStart(row.date, chartUnit, dateLocale);
const bucketKey = format(bucketStart, "yyyy-MM-dd'T'HH:mm:ss");
const existing = obj[bucketKey];
obj[bucketKey] = {
t: bucketKey,
y: (existing?.y ?? 0) + row.y,
};
return obj;
},
{} as Record<string, EventDataDateSeriesPoint>,
);
return Object.values(buckets).sort(
(a, b) => (parseDateValue(a.t)?.getTime() ?? 0) - (parseDateValue(b.t)?.getTime() ?? 0),
);
}, [exactDateRows, chartUnit, dateLocale]);
const chartData: any = useMemo(() => {
if (!minPropertyDate || !maxPropertyDate) {
return {
datasets: [
{
label: t(labels.count),
data: [],
barPercentage: 0.9,
categoryPercentage: 0.9,
...colors.chart.visitors,
borderWidth: 1,
},
],
};
}
return {
datasets: [
{
label: t(labels.count),
data: generateTimeSeries(
chartRows.map(({ t, y }) => ({ x: t, y })),
minPropertyDate,
maxPropertyDate,
chartUnit,
dateLocale,
),
barPercentage: 0.9,
categoryPercentage: 0.9,
...colors.chart.visitors,
borderWidth: 1,
},
],
};
}, [
rows,
minPropertyDate,
maxPropertyDate,
chartRows,
chartUnit,
dateLocale,
colors,
t,
labels.count,
]);
const renderXLabel = useCallback(renderDateLabels(chartUnit, locale), [chartUnit, locale]);
const weekdayTableData = useMemo(() => {
if (!exactDateRows.length || total === 0) return [];
const weekStartsOn = dateLocale.options?.weekStartsOn ?? 0;
const weekdayOrder = Array.from(
{ length: 7 },
(_, index) => (weekStartsOn + index) % 7,
);
const weekdayTotals = exactDateRows.reduce(
(obj, { date, y }) => {
const day = date.getDay();
obj[day] = (obj[day] ?? 0) + y;
return obj;
},
{} as Record<number, number>,
);
return weekdayOrder.map(day => {
const referenceDate = new Date(2026, 0, 4 + day);
const count = weekdayTotals[day] ?? 0;
return {
label: format(referenceDate, 'EEEE', { locale: dateLocale }),
count,
percent: total ? 100 * (count / total) : 0,
};
});
}, [exactDateRows, total, dateLocale]);
const topDateByDay = useMemo(() => {
if (!exactDateRows.length || total === 0) return null;
const dayTotals = exactDateRows.reduce(
(obj, { date, y }) => {
const dayDate = startOfDay(date);
const key = format(dayDate, 'yyyy-MM-dd');
const existing = obj[key];
obj[key] = {
date: dayDate,
count: (existing?.count ?? 0) + y,
};
return obj;
},
{} as Record<string, { date: Date; count: number }>,
);
return Object.values(dayTotals)
.sort((a, b) => b.count - a.count || b.date.getTime() - a.date.getTime())[0];
}, [exactDateRows, total]);
const topWeekday = useMemo(
() => [...weekdayTableData].sort((a, b) => b.count - a.count)[0],
[weekdayTableData],
);
const weekdayLabels = useMemo(
() => weekdayTableData.map(({ label }) => label),
[weekdayTableData],
);
const weekdayColorMap = useMemo(() => {
return weekdayLabels.reduce(
(obj, label, index) => {
const color = colord(CHART_COLORS[index % CHART_COLORS.length]);
obj[label] = color.alpha(0.7).toRgbString();
return obj;
},
{} as Record<string, string>,
);
}, [weekdayLabels]);
const weekdayPieChartData = useMemo(() => {
if (!weekdayTableData.length) return null;
return {
labels: weekdayLabels,
datasets: [
{
data: weekdayTableData.map(({ count }) => count),
backgroundColor: weekdayLabels.map(label => weekdayColorMap[label]),
borderWidth: 0,
},
],
};
}, [weekdayTableData, weekdayLabels, weekdayColorMap]);
return (
<Column gap="6">
<LoadingPanel
isLoading={query.isLoading}
isFetching={query.isFetching}
error={query.error}
minHeight="300px"
>
<Column gap="4">
<MetricsBar padding="2">
<InsightCard
label="Top weekday"
value={topWeekday?.count ? topWeekday.label : t(labels.none)}
hint={
topWeekday?.count
? `${formatLongNumber(topWeekday.count)} ${t(labels.count).toLowerCase()} - ${Math.round(
topWeekday.percent,
)}%`
: undefined
}
/>
<InsightCard
label="Top date"
value={topDateByDay ? formatDate(topDateByDay.date, 'PP', locale) : t(labels.none)}
hint={
topDateByDay
? `${formatLongNumber(topDateByDay.count)} ${t(labels.count).toLowerCase()} - ${Math.round(
100 * (topDateByDay.count / total),
)}%`
: undefined
}
/>
<InsightCard
label="Earliest date"
value={minPropertyDate ? formatDate(minPropertyDate, 'PPpp', locale) : t(labels.none)}
hint={
minPropertyDate
? formatDistance(minPropertyDate, zonedNow, {
addSuffix: true,
locale: dateLocale,
})
: undefined
}
/>
<InsightCard
label="Latest date"
value={maxPropertyDate ? formatDate(maxPropertyDate, 'PPpp', locale) : t(labels.none)}
hint={
maxPropertyDate
? formatDistance(maxPropertyDate, zonedNow, {
addSuffix: true,
locale: dateLocale,
})
: undefined
}
/>
</MetricsBar>
</Column>
</LoadingPanel>
<LoadingPanel
isLoading={query.isLoading}
isFetching={query.isFetching}
error={query.error}
minHeight="400px"
>
<Column minHeight="400px">
{chartData && (
<BarChart
chartData={chartData}
minDate={minPropertyDate ?? zonedNow}
maxDate={maxPropertyDate ?? zonedNow}
unit={chartUnit}
stacked={false}
renderXLabel={renderXLabel}
renderYLabel={(value: string | number) => formatLongNumber(Number(value))}
height="400px"
/>
)}
</Column>
</LoadingPanel>
<LoadingPanel
data={weekdayTableData}
isLoading={query.isLoading}
isFetching={query.isFetching}
error={query.error}
minHeight="300px"
>
<Grid columns={{ base: '1fr', md: '1fr 1fr' }} gap padding="2" alignItems="start">
<Column style={{ minWidth: 0 }} width="100%">
<ListTable title="Weekdays" metric={t(labels.count)} data={weekdayTableData} />
</Column>
<Column style={{ minWidth: 0 }} width="100%">
{weekdayPieChartData && (
<PieChart type="doughnut" chartData={weekdayPieChartData} height="280px" />
)}
</Column>
</Grid>
</LoadingPanel>
</Column>
);
}
@@ -1,133 +0,0 @@
'use client';
import { useMessages } from '@/components/hooks';
import { X } from '@/components/icons';
import { OPERATORS } from '@/lib/constants';
import type { EventPropertyFilter } from '@/lib/types';
import { Button, Icon, Row, Text, Tooltip, TooltipTrigger } from '@umami/react-zen';
export function EventDataFilterBar({
filters,
onChange,
}: {
filters: EventPropertyFilter[];
onChange: (filters: EventPropertyFilter[]) => void;
}) {
const { t, labels } = useMessages();
if (!filters.length) return null;
const operatorLabel = (op: string) => {
switch (op) {
case OPERATORS.equals:
return t(labels.is);
case OPERATORS.notEquals:
return t(labels.isNot);
case OPERATORS.contains:
return t(labels.contains);
case OPERATORS.doesNotContain:
return t(labels.doesNotContain);
case OPERATORS.regex:
return t(labels.regexMatch);
case OPERATORS.notRegex:
return t(labels.regexNotMatch);
case OPERATORS.greaterThan:
return t(labels.greaterThan);
case OPERATORS.lessThan:
return t(labels.lessThan);
case OPERATORS.greaterThanEquals:
return t(labels.greaterThanEquals);
case OPERATORS.lessThanEquals:
return t(labels.lessThanEquals);
case OPERATORS.before:
return t(labels.before);
case OPERATORS.after:
return t(labels.after);
default:
return op;
}
};
const handleRemove = (index: number) => {
onChange(filters.filter((_, i) => i !== index));
};
return (
<Row
gap
alignItems="center"
justifyContent="space-between"
padding="2"
border
borderRadius
wrap="wrap"
>
<Row alignItems="center" gap="2" wrap="wrap" width={{ base: '100%', md: 'auto' }}>
{filters.map((filter, index) => (
<FilterPill
key={`${filter.propertyName}-${index}`}
label={filter.propertyName}
operator={operatorLabel(filter.operator)}
value={filter.value}
onRemove={() => handleRemove(index)}
/>
))}
</Row>
<TooltipTrigger delay={0}>
<Button variant="zero" onPress={() => onChange([])}>
<Icon>
<X />
</Icon>
</Button>
<Tooltip>
<Text>{t(labels.clearAll)}</Text>
</Tooltip>
</TooltipTrigger>
</Row>
);
}
function FilterPill({
label,
operator,
value,
onRemove,
}: {
label: string;
operator: string;
value: string;
onRemove: () => void;
}) {
return (
<Row
border
padding="2"
color
backgroundColor
borderRadius
alignItems="center"
gap="4"
theme="dark"
>
<Row
alignItems="center"
gap="2"
style={{ maxWidth: 'min(500px, calc(100vw - 10rem))', minWidth: 0, overflow: 'hidden' }}
>
<Text color="primary" weight="bold">
{label}
</Text>
<Text color="muted">{operator}</Text>
<Text
color="primary"
weight="bold"
style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
>
{value}
</Text>
</Row>
<Icon onClick={onRemove} size="xs" style={{ cursor: 'pointer' }}>
<X />
</Icon>
</Row>
);
}
@@ -1,34 +0,0 @@
'use client';
import { useMessages } from '@/components/hooks';
import { ListFilter } from '@/components/icons';
import { DialogButton } from '@/components/input/DialogButton';
import type { EventPropertyFilter } from '@/lib/types';
import { EventDataFilterEditForm } from './EventDataFilterEditForm';
export function EventDataFilterButton({
websiteId,
eventName,
eventFilters,
onApply,
}: {
websiteId: string;
eventName: string;
eventFilters: EventPropertyFilter[];
onApply: (filters: EventPropertyFilter[]) => void;
}) {
const { t, labels } = useMessages();
return (
<DialogButton icon={<ListFilter />} label={t(labels.propertyFilter)} variant="outline">
{({ close }) => (
<EventDataFilterEditForm
websiteId={websiteId}
eventName={eventName}
value={eventFilters}
onApply={onApply}
onClose={close}
/>
)}
</DialogButton>
);
}
@@ -1,128 +0,0 @@
'use client';
import { Button, Column, Grid, Icon, List, ListItem, Menu, MenuItem, MenuTrigger, Popover, Row } from '@umami/react-zen';
import { format } from 'date-fns';
import { useState } from 'react';
import { Empty } from '@/components/common/Empty';
import { useEventDataFieldsQuery, useMessages, useMobile } from '@/components/hooks';
import { Plus } from '@/components/icons';
import { DATA_TYPE, OPERATORS } from '@/lib/constants';
import type { EventPropertyFilter } from '@/lib/types';
import { EventDataFilterRecord } from './EventDataFilterRecord';
export function EventDataFilterEditForm({
websiteId,
eventName,
value,
onApply,
onClose,
}: {
websiteId: string;
eventName: string;
value: EventPropertyFilter[];
onApply: (filters: EventPropertyFilter[]) => void;
onClose: () => void;
}) {
const { t, labels, messages } = useMessages();
const { isMobile } = useMobile();
const [filters, setFilters] = useState<EventPropertyFilter[]>(value);
const { data: fields = [] } = useEventDataFieldsQuery(websiteId, eventName);
const handleAdd = (propertyName: string) => {
const field = (fields as any[]).find(f => f.propertyName === propertyName);
const dataType: number = field?.dataType ?? 1;
setFilters(prev => [
...prev,
{
propertyName,
dataType,
operator:
dataType === DATA_TYPE.date
? OPERATORS.before
: dataType === DATA_TYPE.array
? OPERATORS.contains
: OPERATORS.equals,
value:
dataType === DATA_TYPE.boolean
? 'true'
: dataType === DATA_TYPE.date
? format(new Date(), 'yyyy-MM-dd')
: '',
},
]);
};
const handleChange = (index: number, filter: EventPropertyFilter) => {
setFilters(prev => prev.map((f, i) => (i === index ? filter : f)));
};
const handleRemove = (index: number) => {
setFilters(prev => prev.filter((_, i) => i !== index));
};
return (
<Column width={isMobile ? 'auto' : '700px'} gap="6">
<Column minHeight="400px">
<Grid columns={{ base: '1fr', md: '180px 1fr' }} overflow="hidden" gapY="6">
<Row display={{ base: 'flex', md: 'none' }}>
<MenuTrigger>
<Button>
<Icon>
<Plus />
</Icon>
</Button>
<Popover placement="bottom start" shouldFlip>
<Menu
onAction={key => handleAdd(key.toString())}
style={{ maxHeight: 'calc(100vh - 2rem)', overflowY: 'auto' }}
>
{(fields as any[]).map(field => (
<MenuItem key={field.propertyName} id={field.propertyName}>
{field.propertyName}
</MenuItem>
))}
</Menu>
</Popover>
</MenuTrigger>
</Row>
<Column
display={{ base: 'none', md: 'flex' }}
border="right"
paddingRight="3"
marginRight="6"
>
<List onAction={key => handleAdd(key.toString())}>
{(fields as any[]).map(field => (
<ListItem key={field.propertyName} id={field.propertyName}>
{field.propertyName}
</ListItem>
))}
</List>
</Column>
<Column overflow="auto" gapY="4" style={{ contain: 'layout' }}>
{filters.map((filter, index) => (
<EventDataFilterRecord
key={`${filter.propertyName}-${index}`}
websiteId={websiteId}
eventName={eventName}
filter={filter}
onChange={f => handleChange(index, f)}
onRemove={() => handleRemove(index)}
/>
))}
{!filters.length && <Empty message={t(messages.nothingSelected)} />}
</Column>
</Grid>
</Column>
<Row alignItems="center" justifyContent="space-between" gap>
<Button onPress={() => setFilters([])}>{t(labels.reset)}</Button>
<Row gap>
<Button onPress={onClose}>{t(labels.cancel)}</Button>
<Button variant="primary" onPress={() => { onApply(filters); onClose(); }}>
{t(labels.apply)}
</Button>
</Row>
</Row>
</Column>
);
}
@@ -1,266 +0,0 @@
'use client';
import { Button, Calendar, Column, ComboBox, Dialog, DialogTrigger, Grid, Icon, Label, ListItem, Loading, Popover, Row, Select, TextField } from '@umami/react-zen';
import { format, parseISO } from 'date-fns';
import { useState } from 'react';
import { DateDisplay } from '@/components/common/DateDisplay';
import { Empty } from '@/components/common/Empty';
import { MultiSelect } from '@/components/common/MultiSelect';
import { useEventDataValuesQuery, useMessages } from '@/components/hooks';
import { X } from '@/components/icons';
import { DATA_TYPE, OPERATORS } from '@/lib/constants';
import { getMaxSelectableDate } from '@/lib/date';
import type { EventPropertyFilter, Operator } from '@/lib/types';
const STRING_OPERATORS: Operator[] = [
OPERATORS.equals,
OPERATORS.notEquals,
OPERATORS.contains,
OPERATORS.doesNotContain,
OPERATORS.regex,
OPERATORS.notRegex,
];
const NUMERIC_OPERATORS: Operator[] = [
OPERATORS.equals,
OPERATORS.notEquals,
OPERATORS.greaterThan,
OPERATORS.lessThan,
OPERATORS.greaterThanEquals,
OPERATORS.lessThanEquals,
];
const BOOLEAN_OPERATORS: Operator[] = [OPERATORS.equals, OPERATORS.notEquals];
const DATE_OPERATORS: Operator[] = [OPERATORS.before, OPERATORS.after];
const ARRAY_OPERATORS: Operator[] = [OPERATORS.contains, OPERATORS.doesNotContain];
const MULTI_OPERATORS: Operator[] = [OPERATORS.equals, OPERATORS.notEquals];
const FREE_TEXT_OPERATORS: Operator[] = [
OPERATORS.contains,
OPERATORS.doesNotContain,
OPERATORS.regex,
OPERATORS.notRegex,
];
export function EventDataFilterRecord({
websiteId,
eventName,
filter,
onChange,
onRemove,
}: {
websiteId: string;
eventName: string;
filter: EventPropertyFilter;
onChange: (filter: EventPropertyFilter) => void;
onRemove: () => void;
}) {
const { t, labels, messages } = useMessages();
const [search, setSearch] = useState('');
const isNumeric = filter.dataType === DATA_TYPE.number;
const isBoolean = filter.dataType === DATA_TYPE.boolean;
const isDate = filter.dataType === DATA_TYPE.date;
const isArray = filter.dataType === DATA_TYPE.array;
const operators = isNumeric
? NUMERIC_OPERATORS
: isBoolean
? BOOLEAN_OPERATORS
: isDate
? DATE_OPERATORS
: isArray
? ARRAY_OPERATORS
: STRING_OPERATORS;
const isFreeText = !isArray && FREE_TEXT_OPERATORS.includes(filter.operator);
const { data, isLoading } = useEventDataValuesQuery(
websiteId,
eventName,
filter.propertyName,
filter.dataType,
{ enabled: !isNumeric && !isBoolean && !isDate && !isFreeText },
);
const values = (data as Array<{ value: string }> | undefined)?.map(d => d.value) ?? [];
const filteredValues = search
? values.filter(v => v.toLowerCase().includes(search.toLowerCase()))
: values;
const selected = filter.value ? filter.value.split(',').filter(Boolean) : [];
const operatorLabel = (op: Operator) => {
switch (op) {
case OPERATORS.equals: return t(labels.is);
case OPERATORS.notEquals: return t(labels.isNot);
case OPERATORS.contains: return t(labels.contains);
case OPERATORS.doesNotContain: return t(labels.doesNotContain);
case OPERATORS.regex: return t(labels.regexMatch);
case OPERATORS.notRegex: return t(labels.regexNotMatch);
case OPERATORS.greaterThan: return t(labels.greaterThan);
case OPERATORS.lessThan: return t(labels.lessThan);
case OPERATORS.greaterThanEquals: return t(labels.greaterThanEquals);
case OPERATORS.lessThanEquals: return t(labels.lessThanEquals);
case OPERATORS.before: return t(labels.before);
case OPERATORS.after: return t(labels.after);
default: return op;
}
};
const handleOperatorChange = (op: Operator) => {
// clear value when switching between multi-select and free-text modes
const wasMulti = MULTI_OPERATORS.includes(filter.operator);
const isMulti = MULTI_OPERATORS.includes(op);
onChange({
...filter,
operator: op,
value: wasMulti === isMulti ? filter.value : '',
});
};
return (
<Column>
<Label>{filter.propertyName}</Label>
<Grid columns="1fr auto" gap>
<Grid columns={{ base: '1fr', md: '200px 1fr' }} gap>
<Select value={filter.operator} onChange={value => handleOperatorChange(value as Operator)}>
{operators.map(op => (
<ListItem key={op} id={op}>
{operatorLabel(op)}
</ListItem>
))}
</Select>
{isBoolean ? (
<Select
value={filter.value || 'true'}
onChange={value => onChange({ ...filter, value: value as string })}
>
<ListItem id="true">{t(labels.true)}</ListItem>
<ListItem id="false">{t(labels.false)}</ListItem>
</Select>
) : isDate ? (
<DateValuePicker
value={filter.value}
onChange={value => onChange({ ...filter, value })}
/>
) : isArray ? (
<ComboBox
aria-label={filter.propertyName}
items={filteredValues}
inputValue={filter.value}
style={{ width: '100%' }}
onInputChange={v => {
setSearch(v);
onChange({ ...filter, value: v });
}}
formValue="text"
allowsEmptyCollection
allowsCustomValue
renderEmptyState={() =>
isLoading ? (
<Loading placement="center" icon="dots" />
) : (
<Empty message={t(messages.noResultsFound)} />
)
}
>
{filteredValues.map(v => (
<ListItem key={v} id={v}>
{v}
</ListItem>
))}
</ComboBox>
) : isNumeric || isFreeText ? (
<TextField
value={filter.value}
onChange={v => onChange({ ...filter, value: v })}
inputMode={isNumeric ? 'numeric' : 'text'}
/>
) : (
<MultiSelect
value={selected}
onChange={vals => onChange({ ...filter, value: vals.join(',') })}
searchValue={search}
onSearch={setSearch}
allowSearch
renderValue={vals => (vals.length > 0 ? vals.join(', ') : undefined)}
renderEmptyState={() =>
isLoading ? (
<Loading placement="center" icon="dots" />
) : (
<Empty message={t(messages.noResultsFound)} />
)
}
>
{filteredValues.map(v => (
<ListItem key={v} id={v}>
{v}
</ListItem>
))}
</MultiSelect>
)}
</Grid>
<Column justifyContent="flex-start">
<Button onPress={onRemove}>
<Icon>
<X />
</Icon>
</Button>
</Column>
</Grid>
</Column>
);
}
function DateValuePicker({
value,
onChange,
}: {
value: string;
onChange: (value: string) => void;
}) {
const { t, labels } = useMessages();
const [showPicker, setShowPicker] = useState(false);
const selectedDate = getSelectedDate(value);
const [draftDate, setDraftDate] = useState<Date>(selectedDate);
const handleOpen = () => {
setDraftDate(getSelectedDate(value));
setShowPicker(true);
};
const handleApply = () => {
onChange(format(draftDate, 'yyyy-MM-dd'));
setShowPicker(false);
};
return (
<DialogTrigger isOpen={showPicker} onOpenChange={setShowPicker}>
<Button onPress={handleOpen} style={{ width: '100%', justifyContent: 'flex-start' }}>
<DateDisplay startDate={selectedDate} endDate={selectedDate} />
</Button>
<Popover placement="bottom start" shouldFlip isNonModal>
<Dialog>
<Column gap>
<Calendar
value={draftDate}
minValue={new Date(2000, 0, 1)}
maxValue={getMaxSelectableDate()}
onChange={setDraftDate}
/>
<Row justifyContent="end" gap>
<Button onPress={() => setShowPicker(false)}>{t(labels.cancel)}</Button>
<Button variant="primary" onPress={handleApply}>
{t(labels.apply)}
</Button>
</Row>
</Column>
</Dialog>
</Popover>
</DialogTrigger>
);
}
function getSelectedDate(value?: string) {
if (!value) {
return new Date();
}
const date = parseISO(value);
return Number.isNaN(date.getTime()) ? new Date() : date;
}
@@ -1,177 +0,0 @@
'use client';
import { Column, useTheme } from '@umami/react-zen';
import { useCallback, useMemo } from 'react';
import { BarChart } from '@/components/charts/BarChart';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import {
useDateRange,
useEventDataNumericSeriesQuery,
useEventDataNumericStatsQuery,
useLocale,
useMessages,
useTimezone,
} from '@/components/hooks';
import { MetricCard } from '@/components/metrics/MetricCard';
import { MetricsBar } from '@/components/metrics/MetricsBar';
import { renderDateLabels } from '@/lib/charts';
import { getThemeColors } from '@/lib/colors';
import { generateTimeSeries } from '@/lib/date';
import { formatLongNumber } from '@/lib/format';
import type { EventPropertyFilter } from '@/lib/types';
export function EventDataNumericChart({
websiteId,
eventName,
propertyName,
eventFilters = [],
}: {
websiteId: string;
eventName: string;
propertyName: string;
eventFilters?: EventPropertyFilter[];
}) {
const { t, labels } = useMessages();
const { theme } = useTheme();
const { timezone } = useTimezone();
const { dateRange: { startDate, endDate, unit } } = useDateRange({ timezone });
const { locale, dateLocale } = useLocale();
const { colors } = useMemo(() => getThemeColors(theme), [theme]);
const sumQuery = useEventDataNumericSeriesQuery(
websiteId,
eventName,
propertyName,
'sum',
eventFilters,
);
const avgQuery = useEventDataNumericSeriesQuery(
websiteId,
eventName,
propertyName,
'avg',
eventFilters,
);
const statsQuery = useEventDataNumericStatsQuery(
websiteId,
eventName,
propertyName,
eventFilters,
);
const sumRows = useMemo(
() => (sumQuery.data as { t: string; y: number }[] | undefined) ?? [],
[sumQuery.data],
);
const avgRows = useMemo(
() => (avgQuery.data as { t: string; y: number }[] | undefined) ?? [],
[avgQuery.data],
);
const stats = statsQuery.data;
const formatMetricValue = useCallback(
(n: number) =>
Number(n).toLocaleString(locale, {
maximumFractionDigits: 2,
minimumFractionDigits: Number.isInteger(Number(n)) ? 0 : 2,
}),
[locale],
);
const chartData: any = useMemo(() => {
if (!sumQuery.data && !avgQuery.data) return;
return {
datasets: [
{
type: 'bar',
label: t(labels.sum),
data: generateTimeSeries(
sumRows.map(({ t, y }) => ({ x: t, y })),
startDate,
endDate,
unit,
dateLocale,
),
barPercentage: 0.9,
categoryPercentage: 0.9,
...colors.chart.visitors,
borderWidth: 1,
},
{
type: 'bar',
label: t(labels.average),
data: generateTimeSeries(
avgRows.map(({ t, y }) => ({ x: t, y })),
startDate,
endDate,
unit,
dateLocale,
),
barPercentage: 0.9,
categoryPercentage: 0.9,
...colors.chart.views,
borderWidth: 1,
},
],
};
}, [sumQuery.data, avgQuery.data, t, labels, startDate, endDate, unit, dateLocale, colors, sumRows, avgRows]);
const renderXLabel = useCallback(renderDateLabels(unit, locale), [unit, locale]);
return (
<Column gap="4">
<LoadingPanel
data={stats}
isLoading={sumQuery.isLoading || avgQuery.isLoading || statsQuery.isLoading}
isFetching={sumQuery.isFetching || avgQuery.isFetching || statsQuery.isFetching}
error={sumQuery.error || avgQuery.error || statsQuery.error}
minHeight="100px"
>
<MetricsBar padding="2">
<MetricCard
label={t(labels.total)}
value={stats?.total ?? 0}
formatValue={formatLongNumber}
/>
<MetricCard
label={t(labels.average)}
value={stats?.average ?? 0}
formatValue={formatMetricValue}
/>
<MetricCard
label="Median"
value={stats?.median ?? 0}
formatValue={formatMetricValue}
/>
<MetricCard
label={t(labels.max)}
value={stats?.max ?? 0}
formatValue={formatMetricValue}
/>
<MetricCard
label={t(labels.min)}
value={stats?.min ?? 0}
formatValue={formatMetricValue}
/>
</MetricsBar>
</LoadingPanel>
<LoadingPanel
isLoading={sumQuery.isLoading || avgQuery.isLoading || statsQuery.isLoading}
error={sumQuery.error || avgQuery.error || statsQuery.error}
minHeight="400px"
>
{chartData && (
<BarChart
chartData={chartData}
minDate={startDate}
maxDate={endDate}
unit={unit}
stacked={false}
renderXLabel={renderXLabel}
height="400px"
/>
)}
</LoadingPanel>
</Column>
);
}
@@ -70,6 +70,14 @@ export function EventDataPivotTable({
router.push(updateParams({ page }));
};
const renderTruncatedText = (value: string) => (
<Row overflow="hidden" minWidth="0" width="100%">
<Text truncate title={value} style={{ maxWidth: '100%' }}>
{value}
</Text>
</Row>
);
return (
<Column gap="4" minWidth="0" width="100%" maxWidth="100%">
<LoadingPanel
@@ -90,19 +98,11 @@ export function EventDataPivotTable({
)}
</DataColumn>
<DataColumn id="urlPath" label={t(labels.path)} width="220px">
{(row: any) => (
<Text truncate title={row.urlPath}>
{row.urlPath}
</Text>
)}
{(row: any) => renderTruncatedText(row.urlPath ?? '')}
</DataColumn>
{propertyKeys.map(key => (
<DataColumn key={key} id={key} label={key} width="160px">
{(row: any) => (
<Text truncate title={row[key]}>
{row[key] ?? ''}
</Text>
)}
{(row: any) => renderTruncatedText(row[key] ?? '')}
</DataColumn>
))}
<DataColumn id="createdAt" label={t(labels.created)} width="180px">
@@ -125,19 +125,11 @@ export function EventDataPivotTable({
)}
</DataColumn>
<DataColumn id="urlPath" label={t(labels.path)} width="220px">
{(row: any) => (
<Text truncate title={row.urlPath}>
{row.urlPath}
</Text>
)}
{(row: any) => renderTruncatedText(row.urlPath ?? '')}
</DataColumn>
{propertyKeys.map(key => (
<DataColumn key={key} id={key} label={key} width="160px">
{(row: any) => (
<Text truncate title={row[key]}>
{row[key] ?? ''}
</Text>
)}
{(row: any) => renderTruncatedText(row[key] ?? '')}
</DataColumn>
))}
<DataColumn id="createdAt" label={t(labels.created)} width="180px">
@@ -1,186 +0,0 @@
'use client';
import { Column, Grid } from '@umami/react-zen';
import { colord } from 'colord';
import { useCallback, useMemo } from 'react';
import { BarChart } from '@/components/charts/BarChart';
import { PieChart } from '@/components/charts/PieChart';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import {
useEventDataArraySeriesQuery,
useDateRange,
useEventDataPropertySeriesQuery,
useLocale,
useMessages,
useTimezone,
} from '@/components/hooks';
import { ListTable } from '@/components/metrics/ListTable';
import { renderDateLabels } from '@/lib/charts';
import { CHART_COLORS } from '@/lib/constants';
import { generateTimeSeries } from '@/lib/date';
import type { EventDataSeriesPoint, EventPropertyFilter } from '@/lib/types';
export function EventDataPropertyChart({
websiteId,
eventName,
propertyName,
eventFilters = [],
seriesType = 'property',
}: {
websiteId: string;
eventName: string;
propertyName: string;
eventFilters?: EventPropertyFilter[];
seriesType?: 'property' | 'array';
}) {
const { t, labels } = useMessages();
const { timezone } = useTimezone();
const { dateRange: { startDate, endDate, unit } } = useDateRange({ timezone });
const { locale, dateLocale } = useLocale();
const propertySeriesQuery = useEventDataPropertySeriesQuery(
websiteId,
eventName,
propertyName,
eventFilters,
{ enabled: seriesType === 'property' },
);
const arraySeriesQuery = useEventDataArraySeriesQuery(
websiteId,
eventName,
propertyName,
eventFilters,
{ enabled: seriesType === 'array' },
);
const { data, isLoading, isFetching, error } =
seriesType === 'array' ? arraySeriesQuery : propertySeriesQuery;
// Aggregate totals per value from the already-filtered time series
const aggregated = useMemo(() => {
if (!data) return [];
const totals = data.reduce((obj: Record<string, number>, { x, y }) => {
obj[x] = (obj[x] ?? 0) + y;
return obj;
}, {});
return Object.entries(totals)
.map(([value, total]) => ({ value, total: total as number }))
.sort((a, b) => b.total - a.total);
}, [data]);
const valueLabels = useMemo(() => aggregated.map(({ value }) => value), [aggregated]);
const colorMap = useMemo(() => {
return valueLabels.reduce(
(obj, label, index) => {
obj[label] = CHART_COLORS[index % CHART_COLORS.length];
return obj;
},
{} as Record<string, string>,
);
}, [valueLabels]);
const chartData = useMemo(() => {
if (!data) return;
const map = data.reduce((obj: Record<string, EventDataSeriesPoint[]>, { x, t, y }) => {
if (!obj[x]) obj[x] = [];
obj[x].push({ x, t, y });
return obj;
}, {});
if (!map || Object.keys(map).length === 0) {
return {
datasets: [
{
data: generateTimeSeries([], startDate, endDate, unit, dateLocale),
lineTension: 0,
borderWidth: 1,
},
],
};
}
const keys = [
...valueLabels.filter(label => map[label]),
...Object.keys(map).filter(key => !valueLabels.includes(key)),
];
return {
datasets: keys.map((key, index) => {
const color = colord(colorMap[key] || CHART_COLORS[index % CHART_COLORS.length]);
return {
label: key,
data: generateTimeSeries(
map[key].map(({ t, y }) => ({ x: t, y })),
startDate,
endDate,
unit,
dateLocale,
),
lineTension: 0,
backgroundColor: color.alpha(0.6).toRgbString(),
borderColor: color.alpha(0.7).toRgbString(),
borderWidth: 1,
};
}),
};
}, [data, startDate, endDate, unit, dateLocale, valueLabels, colorMap]);
const renderXLabel = useCallback(renderDateLabels(unit, locale), [unit, locale]);
const propertySum = useMemo(
() => aggregated.reduce((sum, { total }) => sum + total, 0),
[aggregated],
);
const tableData = useMemo(() => {
if (!aggregated.length || propertySum === 0) return [];
return aggregated.map(({ value, total }) => ({
label: value,
count: total,
percent: 100 * (total / propertySum),
}));
}, [aggregated, propertySum]);
const pieChartData = useMemo(() => {
if (!aggregated.length) return null;
return {
labels: valueLabels,
datasets: [
{
data: aggregated.map(({ total }) => total),
backgroundColor: valueLabels.map(label => colorMap[label]),
borderWidth: 0,
},
],
};
}, [aggregated, valueLabels, colorMap]);
return (
<Column gap="6">
<LoadingPanel isLoading={isLoading} error={error} minHeight="400px">
{chartData && (
<BarChart
chartData={chartData}
minDate={startDate}
maxDate={endDate}
unit={unit}
stacked={true}
renderXLabel={renderXLabel}
height="400px"
/>
)}
</LoadingPanel>
<LoadingPanel
data={tableData}
isLoading={isLoading}
isFetching={isFetching}
error={error}
minHeight="300px"
>
<Grid columns={{ base: '1fr', md: '1fr 1fr' }} gap padding="2" alignItems="start">
<ListTable title={propertyName} metric={t(labels.count)} data={tableData} />
{pieChartData && <PieChart type="doughnut" chartData={pieChartData} />}
</Grid>
</LoadingPanel>
</Column>
);
}
@@ -5,18 +5,18 @@ import { LoadingPanel } from '@/components/common/LoadingPanel';
import { Panel } from '@/components/common/Panel';
import { useEventDataPropertiesQuery, useMessages } from '@/components/hooks';
import { DATA_TYPE } from '@/lib/constants';
import type { EventPropertyFilter } from '@/lib/types';
import { EventDataDateChart } from '../event-data/EventDataDateChart';
import { EventDataFilterBar } from '../event-data/EventDataFilterBar';
import { EventDataFilterButton } from '../event-data/EventDataFilterButton';
import { EventDataNumericChart } from '../event-data/EventDataNumericChart';
import type { PropertyFilter } from '@/lib/types';
import { PropertyChart } from '@/components/property-data/PropertyChart';
import { PropertyDateChart } from '@/components/property-data/PropertyDateChart';
import { PropertyFilterBar } from '@/components/property-data/PropertyFilterBar';
import { PropertyFilterButton } from '@/components/property-data/PropertyFilterButton';
import { PropertyNumericChart } from '@/components/property-data/PropertyNumericChart';
import { EventDataPivotTable } from '../event-data/EventDataPivotTable';
import { EventDataPropertyChart } from '../event-data/EventDataPropertyChart';
export function EventProperties({ websiteId }: { websiteId: string }) {
const [eventName, setEventName] = useState('');
const [propertyName, setPropertyName] = useState('');
const [eventFilters, setEventFilters] = useState<EventPropertyFilter[]>([]);
const [propertyFilters, setPropertyFilters] = useState<PropertyFilter[]>([]);
const { t, labels } = useMessages();
const { data, isLoading, isFetching, error } = useEventDataPropertiesQuery(websiteId);
@@ -34,10 +34,8 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
return data
.filter((field: { eventName: string }) => field.eventName === eventName)
.filter((field: { propertyName: string; dataType: number }) => {
const key = `${field.propertyName}:${field.dataType}`;
if (seen.has(key)) return false;
seen.add(key);
if (seen.has(field.propertyName)) return false;
seen.add(field.propertyName);
return true;
});
@@ -52,7 +50,7 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
const handleEventChange = (value: string) => {
setEventName(value);
setPropertyName('');
setEventFilters([]);
setPropertyFilters([]);
};
return (
@@ -117,52 +115,57 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
marginTop={{ base: '2', md: '0' }}
style={{ minWidth: 0 }}
>
<EventDataFilterButton
<PropertyFilterButton
source="event"
websiteId={websiteId}
eventName={eventName}
eventFilters={eventFilters}
onApply={setEventFilters}
filters={propertyFilters}
onApply={setPropertyFilters}
/>
</Row>
)}
</Grid>
)}
{eventName && (
<EventDataFilterBar filters={eventFilters} onChange={setEventFilters} />
<PropertyFilterBar filters={propertyFilters} onChange={setPropertyFilters} />
)}
{eventName && propertyName && (
<Column border="bottom" paddingBottom="6">
{(selectedProperty?.dataType === DATA_TYPE.string ||
selectedProperty?.dataType === DATA_TYPE.boolean) && (
<EventDataPropertyChart
<PropertyChart
source="event"
websiteId={websiteId}
eventName={eventName}
propertyName={propertyName}
eventFilters={eventFilters}
propertyFilters={propertyFilters}
/>
)}
{selectedProperty?.dataType === DATA_TYPE.number && (
<EventDataNumericChart
<PropertyNumericChart
source="event"
websiteId={websiteId}
eventName={eventName}
propertyName={propertyName}
eventFilters={eventFilters}
propertyFilters={propertyFilters}
/>
)}
{selectedProperty?.dataType === DATA_TYPE.date && (
<EventDataDateChart
<PropertyDateChart
source="event"
websiteId={websiteId}
eventName={eventName}
propertyName={propertyName}
eventFilters={eventFilters}
propertyFilters={propertyFilters}
/>
)}
{selectedProperty?.dataType === DATA_TYPE.array && (
<EventDataPropertyChart
<PropertyChart
source="event"
websiteId={websiteId}
eventName={eventName}
propertyName={propertyName}
eventFilters={eventFilters}
propertyFilters={propertyFilters}
seriesType="array"
/>
)}
@@ -173,7 +176,7 @@ export function EventProperties({ websiteId }: { websiteId: string }) {
<EventDataPivotTable
websiteId={websiteId}
eventName={eventName}
eventFilters={eventFilters}
eventFilters={propertyFilters}
/>
</Panel>
)}
@@ -0,0 +1,133 @@
'use client';
import { PieChart } from '@/components/charts/PieChart';
import { Empty } from '@/components/common/Empty';
import { useMessages, useMobile } from '@/components/hooks';
import { ListTable } from '@/components/metrics/ListTable';
import { CHART_COLORS } from '@/lib/constants';
import { formatLongNumber, formatShortTime } from '@/lib/format';
import type { PropertyLeaderboardRow } from '@/lib/types';
import { Column, DataColumn, DataTable, Grid, Row, Text } from '@umami/react-zen';
import { useMemo } from 'react';
export function HighCardinalityPropertyChart({ rows }: { rows: PropertyLeaderboardRow[] }) {
const { t, labels } = useMessages();
const { isPhone } = useMobile();
const activeTable = useMemo(() => rows.filter(row => row.activity > 0).slice(0, 10), [rows]);
const userMix = useMemo(() => {
const totalNew = rows.reduce((sum, row) => sum + row.newSessions, 0);
const totalReturning = rows.reduce((sum, row) => sum + row.returningSessions, 0);
const total = totalNew + totalReturning;
return {
newCount: totalNew,
returningCount: totalReturning,
newRate: total ? (totalNew / total) * 100 : 0,
returningRate: total ? (totalReturning / total) * 100 : 0,
};
}, [rows]);
const sessionTypeTable = useMemo(() => {
return [
{
label: 'New',
count: userMix.newCount,
percent: userMix.newRate,
},
{
label: 'Returning',
count: userMix.returningCount,
percent: userMix.returningRate,
},
].filter(row => row.count > 0);
}, [userMix]);
const sessionTypeChartData = useMemo(() => {
if (!sessionTypeTable.length) return null;
return {
labels: sessionTypeTable.map(row => row.label),
datasets: [
{
data: sessionTypeTable.map(row => row.count),
backgroundColor: [CHART_COLORS[0], CHART_COLORS[1]],
borderWidth: 0,
},
],
};
}, [sessionTypeTable]);
return (
<Column gap="6">
<Column minHeight="400px">
<Grid columns="1fr" gap padding="2" alignItems="start">
<Column gap padding="2">
{activeTable.length === 0 ? (
<Empty />
) : isPhone ? (
<Column minWidth="0" width="100%">
<DataTable data={activeTable} style={{ width: '100%' }}>
<DataColumn
id="label"
label="Most Active"
width="1fr"
align="start"
>
{row => (
<Row overflow="hidden" minWidth="0" width="100%">
<Text truncate style={{ maxWidth: '100%', width: '100%' }}>
{row.label}
</Text>
</Row>
)}
</DataColumn>
</DataTable>
</Column>
) : (
<Column overflow="auto" minHeight="0">
<Column style={{ minWidth: '700px' }}>
<DataTable data={activeTable}>
<DataColumn
id="label"
label="Most Active"
width="minmax(220px, 2fr)"
align="start"
>
{row => (
<Row overflow="hidden">
<Text truncate style={{ maxWidth: '320px' }}>
{row.label}
</Text>
</Row>
)}
</DataColumn>
<DataColumn id="sessions" label="Visitors" align="end" width="90px">
{row => formatLongNumber(row.sessions)}
</DataColumn>
<DataColumn id="visits" label="Visits" align="end" width="90px">
{row => formatLongNumber(row.visits)}
</DataColumn>
<DataColumn id="views" label="Views" align="end" width="90px">
{row => formatLongNumber(row.views)}
</DataColumn>
<DataColumn id="events" label="Events" align="end" width="90px">
{row => formatLongNumber(row.events)}
</DataColumn>
<DataColumn id="duration" label="Duration" align="end" width="120px">
{row =>
formatShortTime(Math.abs(~~Number(row.totaltime)), ['h', 'm', 's'], ' ')
}
</DataColumn>
</DataTable>
</Column>
</Column>
)}
</Column>
</Grid>
</Column>
<Column minHeight="300px">
<Grid columns={{ base: '1fr', md: '1fr 1fr' }} gap padding="2" alignItems="start">
<ListTable title="Users" metric={t(labels.count)} data={sessionTypeTable} />
{sessionTypeChartData && <PieChart type="doughnut" chartData={sessionTypeChartData} />}
</Grid>
</Column>
</Column>
);
}
@@ -0,0 +1,143 @@
'use client';
import { Column, DataColumn, DataTable, Row, Text } from '@umami/react-zen';
import { useMemo } from 'react';
import { Avatar } from '@/components/common/Avatar';
import { DateDistance } from '@/components/common/DateDistance';
import { Empty } from '@/components/common/Empty';
import Link from '@/components/common/Link';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import { Pager } from '@/components/common/Pager';
import {
useMessages,
useMobile,
useNavigation,
useSessionDataPivotQuery,
} from '@/components/hooks';
import type { PropertyFilter } from '@/lib/types';
export function SessionDataPivotTable({
websiteId,
propertyName,
propertyKeys: providedPropertyKeys,
propertyFilters = [],
}: {
websiteId: string;
propertyName: string;
propertyKeys?: string[];
propertyFilters?: PropertyFilter[];
}) {
const { t, labels } = useMessages();
const { router, updateParams } = useNavigation();
const { isMobile } = useMobile();
const pivotQuery = useSessionDataPivotQuery(websiteId, propertyName, propertyFilters);
const propertyKeys = useMemo(() => {
if (providedPropertyKeys) return providedPropertyKeys;
return [];
}, [providedPropertyKeys]);
const tableMinWidth = useMemo(() => `${72 + 220 + 180 + propertyKeys.length * 160}px`, [propertyKeys.length]);
const tableData = useMemo(() => {
if (!pivotQuery.data?.data) return [];
return pivotQuery.data.data.map(
(row: {
sessionId: string;
distinctId: string;
createdAt: string;
propertyKeys: string[];
propertyValues: string[];
}) => {
const flat: Record<string, any> = {
sessionId: row.sessionId,
distinctId: row.distinctId,
createdAt: row.createdAt,
};
row.propertyKeys.forEach((key, i) => {
flat[key] = row.propertyValues[i] ?? '';
});
return flat;
},
);
}, [pivotQuery.data]);
const tableQuery = useMemo(
() => (pivotQuery.data ? { ...pivotQuery.data, data: tableData } : undefined),
[pivotQuery.data, tableData],
);
const showPager = tableQuery && tableQuery.count > tableQuery.pageSize;
const handlePageChange = (page: number) => {
router.push(updateParams({ page }));
};
const renderTruncatedText = (value: string) => (
<Row overflow="hidden" minWidth="0" width="100%">
<Text truncate title={value} style={{ maxWidth: '100%' }}>
{value}
</Text>
</Row>
);
const renderTable = (displayMode: 'cards' | 'table') => (
<DataTable data={tableQuery?.data} style={{ width: '100%' }} displayMode={displayMode}>
<DataColumn id="session" label={t(labels.session)} width="72px">
{(row: any) => (
<Link href={updateParams({ session: row.sessionId })}>
<Avatar seed={row.sessionId} size={32} />
</Link>
)}
</DataColumn>
{propertyKeys.map(key => (
<DataColumn key={key} id={key} label={key} width="160px">
{(row: any) => renderTruncatedText(row[key] ?? '')}
</DataColumn>
))}
<DataColumn id="distinctId" label="Distinct ID" width="220px">
{(row: any) => renderTruncatedText(row.distinctId || '')}
</DataColumn>
<DataColumn id="createdAt" label={t(labels.created)} width="180px">
{(row: any) => <DateDistance date={new Date(row.createdAt)} />}
</DataColumn>
</DataTable>
);
return (
<Column gap="4" minWidth="0" width="100%" maxWidth="100%">
<LoadingPanel
data={tableQuery?.data}
isLoading={pivotQuery.isLoading}
isFetching={pivotQuery.isFetching}
error={pivotQuery.error}
renderEmpty={() => <Empty />}
>
<Column gap="4" minWidth="0" width="100%" maxWidth="100%">
{isMobile ? (
renderTable('cards')
) : (
<div style={{ width: '100%', maxWidth: '100%', overflowX: 'auto', overflowY: 'hidden' }}>
<div style={{ width: tableMinWidth, minWidth: tableMinWidth }}>
{renderTable('table')}
</div>
</div>
)}
{showPager && tableQuery && (
<Row marginTop="6">
<Pager
page={tableQuery.page}
pageSize={tableQuery.pageSize}
count={tableQuery.count}
onPageChange={handlePageChange}
/>
</Row>
)}
</Column>
</LoadingPanel>
</Column>
);
}
@@ -0,0 +1,53 @@
'use client';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import { useSessionDataStatsQuery } from '@/components/hooks';
import type { PropertyFilter } from '@/lib/types';
import { PropertyChart } from '@/components/property-data/PropertyChart';
import { HighCardinalityPropertyChart } from './HighCardinalityPropertyChart';
const HIGH_CARDINALITY_NAME_PATTERN =
/(email|e-mail|name|(^|_)(id|uuid|token)($|_)|distinct_id|user_id|customer_id|client_id|member_id)/i;
function isHighCardinalityProperty(propertyName: string, totalValues: number, uniqueValues: number) {
if (!totalValues) return false;
const uniquenessRate = uniqueValues / totalValues;
const hasHighCardinalityName = HIGH_CARDINALITY_NAME_PATTERN.test(propertyName);
return totalValues >= 20 && (hasHighCardinalityName || uniqueValues >= 20 || uniquenessRate >= 0.6);
}
export function SessionStringPropertyView({
websiteId,
propertyName,
propertyFilters = [],
}: {
websiteId: string;
propertyName: string;
propertyFilters?: PropertyFilter[];
}) {
const statsQuery = useSessionDataStatsQuery(websiteId, propertyName, propertyFilters);
const rows = statsQuery.data ?? [];
const totalValues = rows.reduce((sum, row) => sum + row.sessions, 0);
const uniqueValues = rows.length;
const isHighCardinality = isHighCardinalityProperty(
propertyName,
totalValues,
uniqueValues,
);
return (
<LoadingPanel isLoading={statsQuery.isLoading} error={statsQuery.error} minHeight="300px">
{isHighCardinality ? (
<HighCardinalityPropertyChart rows={rows} />
) : (
<PropertyChart
source="session"
websiteId={websiteId}
propertyName={propertyName}
propertyFilters={propertyFilters}
/>
)}
</LoadingPanel>
);
}
@@ -1,21 +1,58 @@
import { Column, Grid, ListItem, Select } from '@umami/react-zen';
import { Column, ComboBox, Grid, Label, ListItem, Row } from '@umami/react-zen';
import { useMemo, useState } from 'react';
import { PieChart } from '@/components/charts/PieChart';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import {
useMessages,
useSessionDataPropertiesQuery,
useSessionDataValuesQuery,
} from '@/components/hooks';
import { ListTable } from '@/components/metrics/ListTable';
import { CHART_COLORS } from '@/lib/constants';
import { useMessages, usePropertyFieldsQuery, useSessionDataPropertiesQuery } from '@/components/hooks';
import { DATA_TYPE } from '@/lib/constants';
import type { PropertyFilter } from '@/lib/types';
import { PropertyChart } from '@/components/property-data/PropertyChart';
import { PropertyDateChart } from '@/components/property-data/PropertyDateChart';
import { PropertyFilterBar } from '@/components/property-data/PropertyFilterBar';
import { PropertyFilterButton } from '@/components/property-data/PropertyFilterButton';
import { PropertyNumericChart } from '@/components/property-data/PropertyNumericChart';
import { Panel } from '@/components/common/Panel';
import { SessionDataPivotTable } from '../session-data/SessionDataPivotTable';
import { SessionStringPropertyView } from '../session-data/SessionStringPropertyView';
export function SessionProperties({ websiteId }: { websiteId: string }) {
const [propertyName, setPropertyName] = useState('');
const [propertyFilters, setPropertyFilters] = useState<PropertyFilter[]>([]);
const { t, labels } = useMessages();
const { data, isLoading, isFetching, error } = useSessionDataPropertiesQuery(websiteId);
const { data, isLoading, isFetching, error } = usePropertyFieldsQuery('session', websiteId);
const { data: scopedData } = useSessionDataPropertiesQuery(
websiteId,
propertyName ? { selectedPropertyName: propertyName, propertyFilters } : undefined,
{ enabled: !!propertyName },
);
const properties: string[] = data?.map(e => e.propertyName);
const properties = useMemo(() => {
if (!data) return [];
const seen = new Set<string>();
return data.filter((field: { propertyName: string; dataType: number }) => {
if (seen.has(field.propertyName)) return false;
seen.add(field.propertyName);
return true;
});
}, [data]);
const selectedProperty = useMemo(
() => properties.find((field: { propertyName: string }) => field.propertyName === propertyName),
[properties, propertyName],
);
const scopedProperties = useMemo(() => {
if (!scopedData) return [];
const seen = new Set<string>();
return scopedData.filter((field: { propertyName: string }) => {
if (seen.has(field.propertyName)) return false;
seen.add(field.propertyName);
return true;
});
}, [scopedData]);
const scopedPropertyKeys = useMemo(
() => scopedProperties.map((field: { propertyName: string }) => field.propertyName),
[scopedProperties],
);
return (
<LoadingPanel
@@ -25,74 +62,107 @@ export function SessionProperties({ websiteId }: { websiteId: string }) {
error={error}
minHeight="300px"
>
<Column gap="6">
<Column gap="6" minWidth="0">
{data && (
<Grid columns="repeat(auto-fill, minmax(300px, 1fr))" gap>
<Select
label={t(labels.event)}
value={propertyName}
onChange={setPropertyName}
placeholder=""
maxHeight={480}
<Grid
columns={{ base: '1fr', md: '1fr auto' }}
gap
alignItems="end"
marginBottom="3"
width="100%"
style={{ minWidth: 0 }}
>
<Grid
columns={{ base: '1fr', md: 'repeat(auto-fill, minmax(300px, 1fr))' }}
gap
width="100%"
style={{ flex: 1, minWidth: 0 }}
>
{properties?.map(p => (
<ListItem key={p} id={p}>
{p}
</ListItem>
))}
</Select>
<Column gap="1" style={{ minWidth: 0 }}>
<Label>{t(labels.property)}</Label>
<ComboBox
inputValue={propertyName}
onInputChange={setPropertyName}
allowsCustomValue
allowsEmptyCollection
>
{properties.map((field: { propertyName: string }) => (
<ListItem key={field.propertyName} id={field.propertyName}>
{field.propertyName}
</ListItem>
))}
</ComboBox>
</Column>
</Grid>
{propertyName && (
<Row
width={{ base: '100%', md: 'auto' }}
marginTop={{ base: '2', md: '0' }}
style={{ minWidth: 0 }}
>
<PropertyFilterButton
source="session"
websiteId={websiteId}
fields={scopedProperties}
filters={propertyFilters}
onApply={setPropertyFilters}
/>
</Row>
)}
</Grid>
)}
{propertyName && <SessionValues websiteId={websiteId} propertyName={propertyName} />}
{propertyName && <PropertyFilterBar filters={propertyFilters} onChange={setPropertyFilters} />}
{propertyName && selectedProperty?.dataType === DATA_TYPE.number && (
<PropertyNumericChart
source="session"
websiteId={websiteId}
propertyName={propertyName}
propertyFilters={propertyFilters}
/>
)}
{propertyName && selectedProperty?.dataType === DATA_TYPE.date && (
<PropertyDateChart
source="session"
websiteId={websiteId}
propertyName={propertyName}
propertyFilters={propertyFilters}
/>
)}
{propertyName && selectedProperty?.dataType === DATA_TYPE.string && (
<SessionStringPropertyView
websiteId={websiteId}
propertyName={propertyName}
propertyFilters={propertyFilters}
/>
)}
{propertyName && selectedProperty?.dataType === DATA_TYPE.boolean && (
<PropertyChart
source="session"
websiteId={websiteId}
propertyName={propertyName}
propertyFilters={propertyFilters}
/>
)}
{propertyName && selectedProperty?.dataType === DATA_TYPE.array && (
<PropertyChart
source="session"
websiteId={websiteId}
propertyName={propertyName}
propertyFilters={propertyFilters}
seriesType="array"
/>
)}
{propertyName && (
<Panel minWidth="0" width="100%">
<SessionDataPivotTable
websiteId={websiteId}
propertyName={propertyName}
propertyKeys={scopedPropertyKeys}
propertyFilters={propertyFilters}
/>
</Panel>
)}
</Column>
</LoadingPanel>
);
}
const SessionValues = ({ websiteId, propertyName }) => {
const { data, isLoading, isFetching, error } = useSessionDataValuesQuery(websiteId, propertyName);
const propertySum = useMemo(() => {
return data?.reduce((sum, { total }) => sum + total, 0) ?? 0;
}, [data]);
const chartData = useMemo(() => {
if (!propertyName || !data) return null;
return {
labels: data.map(({ value }) => value),
datasets: [
{
data: data.map(({ total }) => total),
backgroundColor: CHART_COLORS,
borderWidth: 0,
},
],
};
}, [propertyName, data]);
const tableData = useMemo(() => {
if (!propertyName || !data || propertySum === 0) return [];
return data.map(({ value, total }) => ({
label: value,
count: total,
percent: 100 * (total / propertySum),
}));
}, [propertyName, data, propertySum]);
return (
<LoadingPanel
isLoading={isLoading}
isFetching={isFetching}
data={data}
error={error}
minHeight="300px"
>
{data && (
<Grid columns="1fr 1fr" gap>
<ListTable title={propertyName} data={tableData} />
<PieChart type="doughnut" chartData={chartData} />
</Grid>
)}
</LoadingPanel>
);
};
@@ -24,16 +24,20 @@ export function SessionsPage({ websiteId }) {
<Column gap="3">
<WebsiteControls websiteId={websiteId} />
<SessionModal websiteId={websiteId} />
<Panel>
<Tabs selectedKey={tab} onSelectionChange={handleSelect}>
<Panel minWidth="0" width="100%" style={{ overflow: 'hidden' }}>
<Tabs
selectedKey={tab}
onSelectionChange={handleSelect}
style={{ minWidth: 0, width: '100%' }}
>
<TabList>
<Tab id="activity">{t(labels.activity)}</Tab>
<Tab id="properties">{t(labels.properties)}</Tab>
</TabList>
<TabPanel id="activity">
<TabPanel id="activity" style={{ minWidth: 0, width: '100%' }}>
<SessionsDataTable websiteId={websiteId} />
</TabPanel>
<TabPanel id="properties">
<TabPanel id="properties" style={{ minWidth: 0, width: '100%', overflow: 'hidden' }}>
<SessionProperties websiteId={websiteId} />
</TabPanel>
</Tabs>
@@ -0,0 +1,39 @@
import { z } from 'zod';
import { parsePropertyFilters } from '@/lib/params';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams, pagingParams } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getSessionDataPivot } from '@/queries/sql/sessions/getSessionDataPivot';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
propertyName: z.string(),
...filterParams,
...pagingParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { propertyName, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const propertyFilters = parsePropertyFilters(query);
const result = await getSessionDataPivot(websiteId, propertyName, filters, propertyFilters);
return json(result);
}
@@ -0,0 +1,40 @@
import { z } from 'zod';
import { parsePropertyFilters } from '@/lib/params';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams, timezoneParam, unitParam } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getSessionDataArraySeries } from '@/queries/sql';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
propertyName: z.string(),
timezone: timezoneParam.optional(),
unit: unitParam.optional(),
...filterParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { propertyName, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const propertyFilters = parsePropertyFilters(query);
const data = await getSessionDataArraySeries(websiteId, propertyName, filters, propertyFilters);
return json(data);
}
@@ -0,0 +1,39 @@
import { z } from 'zod';
import { parsePropertyFilters } from '@/lib/params';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams, timezoneParam } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getSessionDataDateSeries } from '@/queries/sql';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
propertyName: z.string(),
timezone: timezoneParam.optional(),
...filterParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { propertyName, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const propertyFilters = parsePropertyFilters(query);
const data = await getSessionDataDateSeries(websiteId, propertyName, filters, propertyFilters);
return json(data);
}
@@ -0,0 +1,41 @@
import { z } from 'zod';
import { parsePropertyFilters } from '@/lib/params';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams, timezoneParam, unitParam } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getSessionDataNumericSeries } from '@/queries/sql';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
propertyName: z.string(),
metric: z.enum(['sum', 'avg', 'count']).default('sum'),
timezone: timezoneParam.optional(),
unit: unitParam.optional(),
...filterParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { propertyName, metric, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const propertyFilters = parsePropertyFilters(query);
const data = await getSessionDataNumericSeries(websiteId, propertyName, metric, filters, propertyFilters);
return json(data);
}
@@ -0,0 +1,39 @@
import { z } from 'zod';
import { parsePropertyFilters } from '@/lib/params';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams, timezoneParam } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getSessionDataNumericStats } from '@/queries/sql';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
propertyName: z.string(),
timezone: timezoneParam.optional(),
...filterParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { propertyName, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const propertyFilters = parsePropertyFilters(query);
const data = await getSessionDataNumericStats(websiteId, propertyName, filters, propertyFilters);
return json(data);
}
@@ -1,4 +1,5 @@
import { z } from 'zod';
import { parsePropertyFilters } from '@/lib/params';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams } from '@/lib/schema';
@@ -12,6 +13,7 @@ export async function GET(
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
selectedPropertyName: z.string().optional(),
...filterParams,
});
@@ -27,9 +29,16 @@ export async function GET(
return unauthorized();
}
const filters = await getQueryFilters(query, websiteId);
const { selectedPropertyName, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const propertyFilters = parsePropertyFilters(query);
const data = await getSessionDataProperties(websiteId, filters);
const data = await getSessionDataProperties(
websiteId,
filters,
propertyFilters,
selectedPropertyName,
);
return json(data);
}
@@ -0,0 +1,40 @@
import { z } from 'zod';
import { parsePropertyFilters } from '@/lib/params';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams, timezoneParam, unitParam } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getSessionDataPropertySeries } from '@/queries/sql';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
propertyName: z.string(),
timezone: timezoneParam.optional(),
unit: unitParam.optional(),
...filterParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { propertyName, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const propertyFilters = parsePropertyFilters(query);
const data = await getSessionDataPropertySeries(websiteId, propertyName, filters, propertyFilters);
return json(data);
}
@@ -0,0 +1,40 @@
import { z } from 'zod';
import { parsePropertyFilters } from '@/lib/params';
import { getQueryFilters, parseRequest } from '@/lib/request';
import { json, unauthorized } from '@/lib/response';
import { filterParams, timezoneParam, unitParam } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getSessionDataStats } from '@/queries/sql/sessions/getSessionDataStats';
export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const schema = z.object({
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
propertyName: z.string(),
timezone: timezoneParam.optional(),
unit: unitParam.optional(),
...filterParams,
});
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const { websiteId } = await params;
if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}
const { propertyName, ...rest } = query;
const filters = await getQueryFilters(rest, websiteId);
const propertyFilters = parsePropertyFilters(query);
const result = await getSessionDataStats(websiteId, propertyName, filters, propertyFilters);
return json(result);
}
@@ -13,6 +13,7 @@ export async function GET(
startAt: z.coerce.number().int(),
endAt: z.coerce.number().int(),
propertyName: z.string().optional(),
dataType: z.coerce.number().int().optional(),
...filterParams,
});
@@ -28,12 +29,13 @@ export async function GET(
return unauthorized();
}
const { propertyName } = query;
const { propertyName, dataType } = query;
const filters = await getQueryFilters(query, websiteId);
const data = await getSessionDataValues(websiteId, {
...filters,
propertyName,
dataType,
});
return json(data);