Website compare fix. Updated date functions.

This commit is contained in:
Mike Cao 2025-06-19 00:40:21 -07:00
parent 5a85433e63
commit da173779e0
7 changed files with 91 additions and 94 deletions

View file

@ -16,7 +16,7 @@ export function WebsiteChart({
const { startDate, endDate, unit, value } = dateRange; const { startDate, endDate, unit, value } = dateRange;
const { data, isLoading, isFetching, error } = useWebsitePageviewsQuery({ const { data, isLoading, isFetching, error } = useWebsitePageviewsQuery({
websiteId, websiteId,
compareMode: compareMode ? dateCompare : undefined, compare: compareMode ? dateCompare : undefined,
}); });
const { pageviews, sessions, compare } = (data || {}) as any; const { pageviews, sessions, compare } = (data || {}) as any;

View file

@ -129,7 +129,13 @@ export function WebsiteCompareTables({ websiteId }: { websiteId: string }) {
const value = y - prev; const value = y - prev;
const change = Math.abs(((y - prev) / prev) * 100); const change = Math.abs(((y - prev) / prev) * 100);
return !isNaN(change) && <ChangeLabel value={value}>{formatNumber(change)}%</ChangeLabel>; return (
!isNaN(change) && (
<Row alignItems="center" marginRight="3">
<ChangeLabel value={value}>{formatNumber(change)}%</ChangeLabel>
</Row>
)
);
}; };
const { startDate, endDate } = getCompareDate( const { startDate, endDate } = getCompareDate(
@ -147,7 +153,7 @@ export function WebsiteCompareTables({ websiteId }: { websiteId: string }) {
<Panel> <Panel>
<Grid columns={{ xs: '1fr', lg: '200px 1fr 1fr' }} gap="6"> <Grid columns={{ xs: '1fr', lg: '200px 1fr 1fr' }} gap="6">
<SideMenu items={items} selectedKey={view} /> <SideMenu items={items} selectedKey={view} />
<Column border="left" paddingLeft="6"> <Column border="left" paddingLeft="6" gap="6">
<Row alignItems="center" justifyContent="space-between"> <Row alignItems="center" justifyContent="space-between">
<Heading size="1">{formatMessage(labels.previous)}</Heading> <Heading size="1">{formatMessage(labels.previous)}</Heading>
<DateDisplay startDate={startDate} endDate={endDate} /> <DateDisplay startDate={startDate} endDate={endDate} />
@ -160,7 +166,7 @@ export function WebsiteCompareTables({ websiteId }: { websiteId: string }) {
params={params} params={params}
/> />
</Column> </Column>
<Column> <Column border="left" paddingLeft="6" gap="6">
<Row alignItems="center" justifyContent="space-between"> <Row alignItems="center" justifyContent="space-between">
<Heading size="1"> {formatMessage(labels.current)}</Heading> <Heading size="1"> {formatMessage(labels.current)}</Heading>
<DateDisplay startDate={dateRange.startDate} endDate={dateRange.endDate} /> <DateDisplay startDate={dateRange.startDate} endDate={dateRange.endDate} />

View file

@ -5,7 +5,7 @@ import { Chart, ChartProps } from '@/components/charts/Chart';
import { useLocale } from '@/components/hooks'; import { useLocale } from '@/components/hooks';
import { renderNumberLabels } from '@/lib/charts'; import { renderNumberLabels } from '@/lib/charts';
import { getThemeColors } from '@/lib/colors'; import { getThemeColors } from '@/lib/colors';
import { formatDate, formatDateByUnit } from '@/lib/date'; import { formatDate, DATE_FORMATS } from '@/lib/date';
import { formatLongCurrency, formatLongNumber } from '@/lib/format'; import { formatLongCurrency, formatLongNumber } from '@/lib/format';
const dateFormats = { const dateFormats = {
@ -37,7 +37,7 @@ export function BarChart({
renderXLabel, renderXLabel,
renderYLabel, renderYLabel,
unit, unit,
XAxisType = 'time', XAxisType = 'timeseries',
YAxisType = 'linear', YAxisType = 'linear',
stacked = false, stacked = false,
minDate, minDate,
@ -57,8 +57,8 @@ export function BarChart({
x: { x: {
type: XAxisType, type: XAxisType,
stacked: true, stacked: true,
min: formatDateByUnit(minDate, unit), min: formatDate(minDate, DATE_FORMATS[unit], locale),
max: formatDateByUnit(maxDate, unit), max: formatDate(maxDate, DATE_FORMATS[unit], locale),
offset: true, offset: true,
time: { time: {
unit, unit,

View file

@ -8,15 +8,15 @@ export interface WebsitePageviewsData {
} }
export function useWebsitePageviewsQuery( export function useWebsitePageviewsQuery(
{ websiteId, compareMode }: { websiteId: string; compareMode?: string }, { websiteId, compare }: { websiteId: string; compare?: string },
options?: ReactQueryOptions<WebsitePageviewsData>, options?: ReactQueryOptions<WebsitePageviewsData>,
) { ) {
const { get, useQuery } = useApi(); const { get, useQuery } = useApi();
const filterParams = useFilterParams(websiteId); const filterParams = useFilterParams(websiteId);
return useQuery<WebsitePageviewsData>({ return useQuery<WebsitePageviewsData>({
queryKey: ['websites:pageviews', { websiteId, compareMode, ...filterParams }], queryKey: ['websites:pageviews', { websiteId, compare, ...filterParams }],
queryFn: () => get(`/websites/${websiteId}/pageviews`, { compareMode, ...filterParams }), queryFn: () => get(`/websites/${websiteId}/pageviews`, { compare, ...filterParams }),
enabled: !!websiteId, enabled: !!websiteId,
...options, ...options,
}); });

View file

@ -1,4 +1,4 @@
import { ReactNode, useMemo, useState } from 'react'; import { ReactNode, useEffect, useMemo, useState } from 'react';
import { Icon, Text, SearchField, Row, Column } from '@umami/react-zen'; import { Icon, Text, SearchField, Row, Column } from '@umami/react-zen';
import { LinkButton } from '@/components/common/LinkButton'; import { LinkButton } from '@/components/common/LinkButton';
import { DEFAULT_ANIMATION_DURATION } from '@/lib/constants'; import { DEFAULT_ANIMATION_DURATION } from '@/lib/constants';
@ -11,7 +11,6 @@ import { LoadingPanel } from '@/components/common/LoadingPanel';
export interface MetricsTableProps extends ListTableProps { export interface MetricsTableProps extends ListTableProps {
websiteId: string; websiteId: string;
type?: string; type?: string;
className?: string;
dataFilter?: (data: any) => any; dataFilter?: (data: any) => any;
limit?: number; limit?: number;
delay?: number; delay?: number;
@ -20,13 +19,14 @@ export interface MetricsTableProps extends ListTableProps {
searchFormattedValues?: boolean; searchFormattedValues?: boolean;
showMore?: boolean; showMore?: boolean;
params?: { [key: string]: any }; params?: { [key: string]: any };
onDataLoad?: (data: any) => any;
className?: string;
children?: ReactNode; children?: ReactNode;
} }
export function MetricsTable({ export function MetricsTable({
websiteId, websiteId,
type, type,
className,
dataFilter, dataFilter,
limit, limit,
delay = null, delay = null,
@ -34,6 +34,8 @@ export function MetricsTable({
searchFormattedValues = false, searchFormattedValues = false,
showMore = true, showMore = true,
params, params,
onDataLoad,
className,
children, children,
...props ...props
}: MetricsTableProps) { }: MetricsTableProps) {
@ -79,9 +81,15 @@ export function MetricsTable({
return []; return [];
}, [data, dataFilter, search, limit, formatValue, type]); }, [data, dataFilter, search, limit, formatValue, type]);
useEffect(() => {
if (data) {
onDataLoad?.(data);
}
}, [data]);
return ( return (
<Column gap="3" justifyContent="space-between"> <Column gap="3" justifyContent="space-between">
<LoadingPanel data={data} isFetching={isFetching} isLoading={isLoading} error={error}> <LoadingPanel data={data} isFetching={isFetching} isLoading={isLoading} error={error} gap>
<Row alignItems="center" justifyContent="space-between"> <Row alignItems="center" justifyContent="space-between">
{allowSearch && <SearchField value={search} onSearch={setSearch} delay={300} />} {allowSearch && <SearchField value={search} onSearch={setSearch} delay={300} />}
{children} {children}

View file

@ -4,7 +4,7 @@ import { BarChart, BarChartProps } from '@/components/charts/BarChart';
import { useLocale, useMessages } from '@/components/hooks'; import { useLocale, useMessages } from '@/components/hooks';
import { renderDateLabels } from '@/lib/charts'; import { renderDateLabels } from '@/lib/charts';
import { getThemeColors } from '@/lib/colors'; import { getThemeColors } from '@/lib/colors';
import { formatDateByUnit } from '@/lib/date'; import { generateTimeSeries } from '@/lib/date';
export interface PageviewsChartProps extends BarChartProps { export interface PageviewsChartProps extends BarChartProps {
data: { data: {
@ -18,7 +18,7 @@ export interface PageviewsChartProps extends BarChartProps {
unit: string; unit: string;
} }
export function PageviewsChart({ data, unit, ...props }: PageviewsChartProps) { export function PageviewsChart({ data, unit, minDate, maxDate, ...props }: PageviewsChartProps) {
const { formatMessage, labels } = useMessages(); const { formatMessage, labels } = useMessages();
const { theme } = useTheme(); const { theme } = useTheme();
const { locale, dateLocale } = useLocale(); const { locale, dateLocale } = useLocale();
@ -32,7 +32,7 @@ export function PageviewsChart({ data, unit, ...props }: PageviewsChartProps) {
datasets: [ datasets: [
{ {
label: formatMessage(labels.visitors), label: formatMessage(labels.visitors),
data: convertDataset(data.sessions, unit, dateLocale), data: generateTimeSeries(data.sessions, minDate, maxDate, unit, dateLocale),
borderWidth: 1, borderWidth: 1,
barPercentage: 0.9, barPercentage: 0.9,
categoryPercentage: 0.9, categoryPercentage: 0.9,
@ -41,7 +41,7 @@ export function PageviewsChart({ data, unit, ...props }: PageviewsChartProps) {
}, },
{ {
label: formatMessage(labels.views), label: formatMessage(labels.views),
data: convertDataset(data.pageviews, unit, dateLocale), data: generateTimeSeries(data.pageviews, minDate, maxDate, unit, dateLocale),
barPercentage: 0.9, barPercentage: 0.9,
categoryPercentage: 0.9, categoryPercentage: 0.9,
borderWidth: 1, borderWidth: 1,
@ -53,7 +53,13 @@ export function PageviewsChart({ data, unit, ...props }: PageviewsChartProps) {
{ {
type: 'line', type: 'line',
label: `${formatMessage(labels.views)} (${formatMessage(labels.previous)})`, label: `${formatMessage(labels.views)} (${formatMessage(labels.previous)})`,
data: data.compare.pageviews, data: generateTimeSeries(
data.compare.pageviews,
minDate,
maxDate,
unit,
dateLocale,
),
borderWidth: 2, borderWidth: 2,
backgroundColor: '#8601B0', backgroundColor: '#8601B0',
borderColor: '#8601B0', borderColor: '#8601B0',
@ -62,7 +68,7 @@ export function PageviewsChart({ data, unit, ...props }: PageviewsChartProps) {
{ {
type: 'line', type: 'line',
label: `${formatMessage(labels.visitors)} (${formatMessage(labels.previous)})`, label: `${formatMessage(labels.visitors)} (${formatMessage(labels.previous)})`,
data: data.compare.sessions, data: generateTimeSeries(data.compare.sessions, minDate, maxDate, unit, dateLocale),
borderWidth: 2, borderWidth: 2,
backgroundColor: '#f15bb5', backgroundColor: '#f15bb5',
borderColor: '#f15bb5', borderColor: '#f15bb5',
@ -81,12 +87,10 @@ export function PageviewsChart({ data, unit, ...props }: PageviewsChartProps) {
{...props} {...props}
chartData={chartData} chartData={chartData}
unit={unit} unit={unit}
minDate={minDate}
maxDate={maxDate}
renderXLabel={renderXLabel} renderXLabel={renderXLabel}
height="400px" height="400px"
/> />
); );
} }
function convertDataset(data: { x: string; y: number }[], unit: string, locale?: any) {
return data.map(d => ({ ...d, d: d.x, x: formatDateByUnit(d.x, unit, locale) }));
}

View file

@ -34,7 +34,8 @@ import {
subWeeks, subWeeks,
endOfMinute, endOfMinute,
isSameDay, isSameDay,
parseISO, isBefore,
isEqual,
} from 'date-fns'; } from 'date-fns';
import { getDateLocale } from '@/lib/lang'; import { getDateLocale } from '@/lib/lang';
import { DateRange } from '@/lib/types'; import { DateRange } from '@/lib/types';
@ -48,19 +49,7 @@ export const TIME_UNIT = {
year: 'year', year: 'year',
}; };
export const CUSTOM_FORMATS = { export const DATE_FUNCTIONS = {
'en-US': {
p: 'ha',
pp: 'h:mm:ss',
},
'fr-FR': {
'M/d': 'd/M',
'MMM d': 'd MMM',
'EEE M/d': 'EEE d/M',
},
};
const DATE_FUNCTIONS = {
minute: { minute: {
diff: differenceInMinutes, diff: differenceInMinutes,
add: addMinutes, add: addMinutes,
@ -105,6 +94,15 @@ const DATE_FUNCTIONS = {
}, },
}; };
export const DATE_FORMATS = {
minute: 'yyyy-MM-dd HH:mm',
hour: 'yyyy-MM-dd HH',
day: 'yyyy-MM-dd',
week: "yyyy-'W'II",
month: 'yyyy-MM',
year: 'yyyy',
};
export function isValidTimezone(timezone: string) { export function isValidTimezone(timezone: string) {
try { try {
Intl.DateTimeFormat(undefined, { timeZone: timezone }); Intl.DateTimeFormat(undefined, { timeZone: timezone });
@ -283,52 +281,6 @@ export function getMinimumUnit(startDate: number | Date, endDate: number | Date)
return 'year'; return 'year';
} }
export function formatDateByUnit(dateInput: string | Date, unit: string, locale?: any) {
const date = typeof dateInput === 'string' ? parseISO(dateInput) : dateInput;
switch (unit) {
case 'minute':
return format(startOfMinute(date), 'yyyy-MM-dd HH:mm');
case 'hour':
return format(startOfHour(date), 'yyyy-MM-dd HH');
case 'day':
return format(startOfDay(date), 'yyyy-MM-dd');
case 'week':
return format(startOfWeek(date, { locale }), "yyyy-'W'II");
case 'month':
return format(startOfMonth(date), 'yyyy-MM');
case 'year':
return format(startOfYear(date), 'yyyy');
default:
return format(startOfDay(date), 'yyyy-MM-dd');
}
}
export function getDateArray(data: any[], startDate: Date, endDate: Date, unit: string) {
const arr = [];
const { diff, add, start } = DATE_FUNCTIONS[unit];
const n = diff(endDate, startDate);
for (let i = 0; i <= n; i++) {
const t = start(add(startDate, i));
const y = data.find(({ x }) => start(new Date(x)).getTime() === t.getTime())?.y || 0;
arr.push({ x: t, y });
}
return arr;
}
export function formatDate(date: string | number | Date, str: string, locale = 'en-US') {
return format(
typeof date === 'string' ? new Date(date) : date,
CUSTOM_FORMATS?.[locale]?.[str] || str,
{
locale: getDateLocale(locale),
},
);
}
export function maxDate(...args: Date[]) { export function maxDate(...args: Date[]) {
return max(args.filter(n => isDate(n))); return max(args.filter(n => isDate(n)));
} }
@ -337,15 +289,6 @@ export function minDate(...args: any[]) {
return min(args.filter(n => isDate(n))); return min(args.filter(n => isDate(n)));
} }
export function getLocalTime(t: string | number | Date) {
return addMinutes(new Date(t), new Date().getTimezoneOffset());
}
export function getDateLength(startDate: Date, endDate: Date, unit: string | number) {
const { diff } = DATE_FUNCTIONS[unit];
return diff(endDate, startDate) + 1;
}
export function getCompareDate(compare: string, startDate: Date, endDate: Date) { export function getCompareDate(compare: string, startDate: Date, endDate: Date) {
if (compare === 'yoy') { if (compare === 'yoy') {
return { startDate: subYears(startDate, 1), endDate: subYears(endDate, 1) }; return { startDate: subYears(startDate, 1), endDate: subYears(endDate, 1) };
@ -368,3 +311,39 @@ export function getDayOfWeekAsDate(dayOfWeek: number) {
return currentDate; return currentDate;
} }
export function formatDate(date: string | number | Date, dateFormat: string, locale = 'en-US') {
return format(typeof date === 'string' ? new Date(date) : date, dateFormat, {
locale: getDateLocale(locale),
});
}
export function generateTimeSeries(
data: { x: string; y: number }[],
minDate: Date,
maxDate: Date,
unit: string,
locale: string,
) {
const add = DATE_FUNCTIONS[unit].add;
const start = DATE_FUNCTIONS[unit].start;
const fmt = DATE_FORMATS[unit];
let current = start(minDate);
const end = start(maxDate);
const timeseries: string[] = [];
while (isBefore(current, end) || isEqual(current, end)) {
timeseries.push(formatDate(current, fmt, locale));
current = add(current, 1);
}
const lookup = new Map(data.map(({ x, y }) => [formatDate(x, fmt, locale), { x, y }]));
return timeseries.map(t => {
const { x, y } = lookup.get(t) || {};
return { x: t, d: x, y: y ?? null };
});
}