Fixed chart rendering when using date nav buttons.

This commit is contained in:
Mike Cao 2025-06-12 23:07:25 -07:00
parent 1649992654
commit 7b5591a3ce
18 changed files with 177 additions and 320 deletions

View file

@ -30,10 +30,10 @@ export interface BarChartProps extends ChartProps {
YAxisType?: string;
minDate?: Date;
maxDate?: Date;
isAllTime?: boolean;
}
export function BarChart({
chartData,
renderXLabel,
renderYLabel,
unit,
@ -43,7 +43,6 @@ export function BarChart({
minDate,
maxDate,
currency,
isAllTime,
...props
}: BarChartProps) {
const [tooltip, setTooltip] = useState(null);
@ -51,14 +50,14 @@ export function BarChart({
const { locale } = useLocale();
const { colors } = useMemo(() => getThemeColors(theme), [theme]);
const options: any = useMemo(() => {
const chartOptions: any = useMemo(() => {
return {
__id: new Date().getTime(),
scales: {
x: {
type: XAxisType,
stacked: true,
min: isAllTime ? '' : minDate,
min: minDate,
max: maxDate,
time: {
unit,
@ -94,7 +93,7 @@ export function BarChart({
},
},
};
}, [colors, unit, stacked, renderXLabel, renderYLabel]);
}, [chartData, colors, unit, stacked, renderXLabel, renderYLabel]);
const handleTooltip = ({ tooltip }: { tooltip: any }) => {
const { opacity, labelColors, dataPoints } = tooltip;
@ -121,9 +120,9 @@ export function BarChart({
<Chart
{...props}
type="bar"
chartOptions={options}
chartData={chartData}
chartOptions={chartOptions}
onTooltip={handleTooltip}
height="400px"
/>
{tooltip && <ChartTooltip {...tooltip} />}
</>

View file

@ -1,29 +1,25 @@
import { useState, useRef, useEffect, useMemo } from 'react';
import { Loading, Box, Column, BoxProps } from '@umami/react-zen';
import ChartJS, { LegendItem, ChartOptions } from 'chart.js/auto';
import { Box, Column, BoxProps } from '@umami/react-zen';
import ChartJS, { LegendItem, ChartOptions, ChartData, UpdateMode } from 'chart.js/auto';
import { Legend } from '@/components/metrics/Legend';
import { DEFAULT_ANIMATION_DURATION } from '@/lib/constants';
ChartJS.defaults.font.family = 'Inter';
export interface ChartProps extends BoxProps {
type?: 'bar' | 'bubble' | 'doughnut' | 'pie' | 'line' | 'polarArea' | 'radar' | 'scatter';
data?: object;
isLoading?: boolean;
animationDuration?: number;
updateMode?: string;
onCreate?: (chart: any) => void;
onUpdate?: (chart: any) => void;
onTooltip?: (model: any) => void;
chartData?: ChartData & { focusLabel?: string };
chartOptions?: ChartOptions;
updateMode?: UpdateMode;
animationDuration?: number;
onTooltip?: (model: any) => void;
}
export function Chart({
type,
data,
isLoading = false,
chartData,
animationDuration = DEFAULT_ANIMATION_DURATION,
updateMode,
onCreate,
onUpdate,
onTooltip,
chartOptions,
...props
@ -59,53 +55,6 @@ export function Chart({
};
}, [chartOptions]);
const createChart = (data: any) => {
ChartJS.defaults.font.family = 'Inter';
chart.current = new ChartJS(canvas.current, {
type,
data,
options,
});
onCreate?.(chart.current);
setLegendItems(chart.current.legend.legendItems);
};
const updateChart = (data: any) => {
if (data.datasets) {
if (data.datasets.length === chart.current.data.datasets.length) {
chart.current.data.datasets.forEach((dataset: { data: any }, index: string | number) => {
if (data?.datasets[index]) {
dataset.data = data?.datasets[index]?.data;
if (chart.current.legend.legendItems[index]) {
chart.current.legend.legendItems[index].text = data.datasets[index]?.label;
}
}
});
} else {
chart.current.data.datasets = data.datasets;
}
}
if (data.focusLabel !== null) {
chart.current.data.datasets.forEach(ds => {
ds.hidden = data.focusLabel ? ds.label !== data.focusLabel : false;
});
}
chart.current.options = options;
// Allow config changes before update
onUpdate?.(chart.current);
chart.current.update(updateMode);
setLegendItems(chart.current.legend.legendItems);
};
const handleLegendClick = (item: LegendItem) => {
if (type === 'bar') {
const { datasetIndex } = item;
@ -127,20 +76,47 @@ export function Chart({
setLegendItems(chart.current.legend.legendItems);
};
// Create chart
useEffect(() => {
if (data) {
if (!chart.current) {
createChart(data);
} else {
updateChart(data);
}
if (canvas.current) {
chart.current = new ChartJS(canvas.current, {
type,
data: chartData,
options,
});
setLegendItems(chart.current.legend.legendItems);
}
}, [data, options]);
return () => {
chart.current?.destroy();
};
}, []);
// Update chart
useEffect(() => {
if (chart.current && chartData) {
// Replace labels and datasets *in-place*
chart.current.data.labels = chartData.labels;
chart.current.data.datasets = chartData.datasets;
if (chartData.focusLabel !== null) {
chart.current.data.datasets.forEach((ds: { hidden: boolean; label: any }) => {
ds.hidden = chartData.focusLabel ? ds.label !== chartData.focusLabel : false;
});
}
chart.current.options = options;
chart.current.update(updateMode);
setLegendItems(chart.current.legend.legendItems);
}
}, [chartData, options, updateMode]);
return (
<Column gap="6">
<Box {...props}>
{isLoading && <Loading position="page" icon="dots" />}
<canvas ref={canvas} />
</Box>
<Legend items={legendItems} onClick={handleLegendClick} />

View file

@ -1,9 +1,9 @@
import { ReactNode } from 'react';
import Link from 'next/link';
import { Button } from '@umami/react-zen';
import { Button, ButtonProps } from '@umami/react-zen';
import { useLocale } from '@/components/hooks';
export interface LinkButtonProps {
export interface LinkButtonProps extends ButtonProps {
href: string;
target?: string;
scroll?: boolean;

View file

@ -6,12 +6,15 @@ export {
ChevronRight as Chevron,
Clock,
Copy,
Database,
Download,
Edit,
Ellipsis,
Eye,
ExternalLink,
File,
FileJson,
FileText,
Globe,
Grid2X2,
KeyRound,
@ -25,6 +28,7 @@ export {
Minimize,
Moon,
MoreHorizontal as More,
Paperclip,
PanelLeft,
Plus,
RefreshCw as Refresh,

View file

@ -88,6 +88,7 @@ export function ReportEditButton({
title={formatMessage(labels.delete)}
onConfirm={handleDelete}
onCancel={handleClose}
isDanger
>
<Row gap="1">
{formatMessage(messages.confirmDelete, { target: <b key={name}>{name}</b> })}

View file

@ -47,7 +47,7 @@ export function WebsiteDateFilter({
};
const handleIncrement = (increment: number) => {
router.push(renderUrl({ increment }));
router.push(renderUrl({ offset: offset + increment }));
saveDateRange(getOffsetDateRange(dateRange, increment));
};

View file

@ -1,26 +1,26 @@
import { useMemo, useState, useEffect } from 'react';
import { colord } from 'colord';
import { BarChart } from '@/components/charts/BarChart';
import { BarChart, BarChartProps } from '@/components/charts/BarChart';
import { useDateRange, useLocale, useWebsiteEventsSeriesQuery } from '@/components/hooks';
import { renderDateLabels } from '@/lib/charts';
import { CHART_COLORS } from '@/lib/constants';
import { LoadingPanel } from '@/components/common/LoadingPanel';
export interface EventsChartProps {
export interface EventsChartProps extends BarChartProps {
websiteId: string;
className?: string;
focusLabel?: string;
}
export function EventsChart({ websiteId, className, focusLabel }: EventsChartProps) {
export function EventsChart({ websiteId, focusLabel }: EventsChartProps) {
const {
dateRange: { startDate, endDate, unit, value },
} = useDateRange(websiteId);
const { locale } = useLocale();
const { data, isLoading } = useWebsiteEventsSeriesQuery(websiteId);
const { data, isLoading, error } = useWebsiteEventsSeriesQuery(websiteId);
const [label, setLabel] = useState<string>(focusLabel);
const chartData = useMemo(() => {
if (!data) return [];
const chartData: any = useMemo(() => {
if (!data) return;
const map = (data as any[]).reduce((obj, { x, t, y }) => {
if (!obj[x]) {
@ -55,16 +55,18 @@ export function EventsChart({ websiteId, className, focusLabel }: EventsChartPro
}, [focusLabel]);
return (
<BarChart
minDate={startDate}
maxDate={endDate}
className={className}
data={chartData}
unit={unit}
stacked={true}
renderXLabel={renderDateLabels(unit, locale)}
isLoading={isLoading}
isAllTime={value === 'all'}
/>
<LoadingPanel isLoading={isLoading} error={error}>
{chartData && (
<BarChart
chartData={chartData}
minDate={value === 'all' ? undefined : startDate}
maxDate={endDate}
unit={unit}
stacked={true}
renderXLabel={renderDateLabels(unit, locale)}
height="400px"
/>
)}
</LoadingPanel>
);
}

View file

@ -96,13 +96,20 @@ const AnimatedRow = ({
}) => {
const props = useSpring({
width: percent,
y: value,
y: !isNaN(value) ? value : 0,
from: { width: 0, y: 0 },
config: animate ? config.default : { duration: 0 },
});
return (
<Grid columns="1fr 50px 50px" paddingLeft="2" alignItems="center" hoverBackgroundColor="2" gap>
<Grid
columns="1fr 50px 50px"
paddingLeft="2"
alignItems="center"
hoverBackgroundColor="2"
borderRadius
gap
>
<Row alignItems="center">
<Text>{label}</Text>
</Row>

View file

@ -15,26 +15,16 @@ export interface PageviewsChartProps extends BarChartProps {
};
};
unit: string;
isLoading?: boolean;
isAllTime?: boolean;
}
export function PageviewsChart({
data,
unit,
isLoading,
isAllTime,
...props
}: PageviewsChartProps) {
export function PageviewsChart({ data, unit, ...props }: PageviewsChartProps) {
const { formatMessage, labels } = useMessages();
const { theme } = useTheme();
const { locale } = useLocale();
const { colors } = useMemo(() => getThemeColors(theme), [theme]);
const chartData = useMemo(() => {
if (!data) {
return {};
}
const chartData: any = useMemo(() => {
if (!data) return;
return {
__id: new Date().getTime(),
@ -84,11 +74,10 @@ export function PageviewsChart({
return (
<BarChart
{...props}
data={chartData}
chartData={chartData}
unit={unit}
isLoading={isLoading}
isAllTime={isAllTime}
renderXLabel={renderXLabel}
height="400px"
/>
);
}

View file

@ -38,8 +38,8 @@ export function RealtimeChart({ data, unit, ...props }: RealtimeChartProps) {
return (
<PageviewsChart
{...props}
minDate={startDate.toISOString()}
maxDate={endDate.toISOString()}
minDate={startDate}
maxDate={endDate}
unit={unit}
data={chartData}
animationDuration={animationDuration}