Add sparklines to Website, Pixel, Link tables

This commit is contained in:
Francis Cao committed 2026-07-08 10:03:08 -07:00
1 parent 1fb565bc27
commit 86b35475c0
11 files changed
+625 -20

No files matched your search

+29 -8
View File
@@ -1,9 +1,11 @@
import { DataColumn, DataTable, type DataTableProps, Row } from '@umami/react-zen';
import { useMemo } from 'react';
import { WebsiteSparkline } from '@/app/(main)/websites/WebsiteSparkline';
import { DateDistance } from '@/components/common/DateDistance';
import { ExternalLink } from '@/components/common/ExternalLink';
import Link from '@/components/common/Link';
import { SortableLabel } from '@/components/common/SortableLabel';
import { useMessages, useNavigation, useSlug } from '@/components/hooks';
import { useLinkListChartsQuery, useMessages, useNavigation, useSlug } from '@/components/hooks';
import { LinkDeleteButton } from './LinkDeleteButton';
import { LinkEditButton } from './LinkEditButton';
@@ -11,13 +13,17 @@ export interface LinksTableProps extends DataTableProps {
showActions?: boolean;
}
export function LinksTable({ showActions, ...props }: LinksTableProps) {
export function LinksTable({ showActions, data = [], ...props }: LinksTableProps & { data?: any[] }) {
const { t, labels } = useMessages();
const { websiteId, renderUrl } = useNavigation();
const { getSlugUrl } = useSlug('link');
const linkIds = useMemo(() => data.map(row => row.id), [data]);
const chartsQuery = useLinkListChartsQuery(linkIds);
const charts = chartsQuery.data?.data || {};
const isChartLoading = chartsQuery.isLoading && !chartsQuery.data;
return (
<DataTable {...props}>
<DataTable {...props} data={data}>
<DataColumn id="name" label={<SortableLabel label={t(labels.name)} sortKey="name" />}>
{({ id, name }: any) => {
return <Link href={renderUrl(`/links/${id}`)}>{name}</Link>;
@@ -26,7 +32,6 @@ export function LinksTable({ showActions, ...props }: LinksTableProps) {
<DataColumn
id="slug"
label={<SortableLabel label={t(labels.link)} sortKey="slug" />}
width="25%"
style={{ minWidth: 0 }}
>
{({ slug }: any) => {
@@ -37,27 +42,43 @@ export function LinksTable({ showActions, ...props }: LinksTableProps) {
<DataColumn
id="url"
label={<SortableLabel label={t(labels.destinationUrl)} sortKey="url" />}
width="30%"
style={{ minWidth: 0 }}
>
{({ url }: any) => {
return <ExternalLink href={url}>{url}</ExternalLink>;
}}
</DataColumn>
<DataColumn
id="chart"
label={<span style={{ whiteSpace: 'normal' }}>{`${t(labels.visitors)} (7d)`}</span>}
style={{ minWidth: 0 }}
>
{(row: any) => {
const chart = charts[row.id];
return (
<WebsiteSparkline
values={chart?.values}
total={chart?.total}
isLoading={isChartLoading}
/>
);
}}
</DataColumn>
<DataColumn
id="created"
label={
<SortableLabel label={t(labels.created)} sortKey="createdAt" defaultDirection="desc" />
}
width="200px"
width="180px"
>
{(row: any) => <DateDistance date={new Date(row.createdAt)} />}
</DataColumn>
{showActions && (
<DataColumn id="action" align="end" width="100px">
<DataColumn id="action" align="end" width="72px">
{({ id, name }: any) => {
return (
<Row>
<Row gap="2">
<LinkEditButton linkId={id} />
<LinkDeleteButton linkId={id} websiteId={websiteId} name={name} />
</Row>
+33 -5
View File
@@ -1,9 +1,11 @@
import { DataColumn, DataTable, type DataTableProps, Row } from '@umami/react-zen';
import { useMemo } from 'react';
import { WebsiteSparkline } from '@/app/(main)/websites/WebsiteSparkline';
import { DateDistance } from '@/components/common/DateDistance';
import { ExternalLink } from '@/components/common/ExternalLink';
import Link from '@/components/common/Link';
import { SortableLabel } from '@/components/common/SortableLabel';
import { useMessages, useNavigation, useSlug } from '@/components/hooks';
import { useMessages, useNavigation, usePixelListChartsQuery, useSlug } from '@/components/hooks';
import { PixelDeleteButton } from './PixelDeleteButton';
import { PixelEditButton } from './PixelEditButton';
@@ -11,13 +13,21 @@ export interface PixelsTableProps extends DataTableProps {
showActions?: boolean;
}
export function PixelsTable({ showActions, ...props }: PixelsTableProps) {
export function PixelsTable({
showActions,
data = [],
...props
}: PixelsTableProps & { data?: any[] }) {
const { t, labels } = useMessages();
const { renderUrl } = useNavigation();
const { getSlugUrl } = useSlug('pixel');
const pixelIds = useMemo(() => data.map(row => row.id), [data]);
const chartsQuery = usePixelListChartsQuery(pixelIds);
const charts = chartsQuery.data?.data || {};
const isChartLoading = chartsQuery.isLoading && !chartsQuery.data;
return (
<DataTable {...props}>
<DataTable {...props} data={data}>
<DataColumn id="name" label={<SortableLabel label={t(labels.name)} sortKey="name" />}>
{({ id, name }: any) => {
return <Link href={renderUrl(`/pixels/${id}`)}>{name}</Link>;
@@ -33,21 +43,39 @@ export function PixelsTable({ showActions, ...props }: PixelsTableProps) {
);
}}
</DataColumn>
<DataColumn
id="chart"
label={<span style={{ whiteSpace: 'normal' }}>{`${t(labels.visitors)} (7d)`}</span>}
style={{ minWidth: 0 }}
>
{(row: any) => {
const chart = charts[row.id];
return (
<WebsiteSparkline
values={chart?.values}
total={chart?.total}
isLoading={isChartLoading}
/>
);
}}
</DataColumn>
<DataColumn
id="created"
label={
<SortableLabel label={t(labels.created)} sortKey="createdAt" defaultDirection="desc" />
}
width="180px"
>
{(row: any) => <DateDistance date={new Date(row.createdAt)} />}
</DataColumn>
{showActions && (
<DataColumn id="action" align="end" width="100px">
<DataColumn id="action" align="end" width="72px">
{(row: any) => {
const { id, name } = row;
return (
<Row>
<Row gap="2">
<PixelEditButton pixelId={id} />
<PixelDeleteButton pixelId={id} name={name} />
</Row>
@@ -0,0 +1,79 @@
import { useTheme } from '@umami/react-zen';
import { useMemo } from 'react';
import { useMessages } from '@/components/hooks';
import { getThemeColors } from '@/lib/colors';
export function WebsiteSparkline({
values = [],
total = 0,
isLoading = false,
}: {
values?: number[];
total?: number;
isLoading?: boolean;
}) {
const { theme } = useTheme();
const { t, labels } = useMessages();
const { colors } = useMemo(() => getThemeColors(theme), [theme]);
const tooltipLabel = `${total.toLocaleString()} ${t(labels.visitors).toLocaleLowerCase()}`;
const points = useMemo(() => {
if (!values.length) {
return '';
}
const width = 96;
const height = 24;
const padding = 2;
const max = Math.max(...values, 0);
const min = Math.min(...values, 0);
const range = max - min || 1;
return values
.map((value, index) => {
const x = values.length === 1 ? width / 2 : (index / (values.length - 1)) * width;
const y =
height - padding - ((value - min) / range) * Math.max(height - padding * 2, 1);
return `${x},${y}`;
})
.join(' ');
}, [values]);
if (isLoading) {
return (
<div
style={{
width: '100%',
maxWidth: 88,
height: 24,
borderRadius: 9999,
background: 'var(--surface-sunken)',
}}
/>
);
}
return (
<div style={{ width: '100%', maxWidth: 88, cursor: 'default' }} title={tooltipLabel}>
<svg
width="100%"
height="24"
viewBox="0 0 96 24"
preserveAspectRatio="none"
role="img"
aria-label={tooltipLabel}
style={{ display: 'block' }}
>
<polyline
points={points}
fill="none"
stroke={colors.chart.visitors.borderColor}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
);
}
+38 -7
View File
@@ -1,10 +1,11 @@
import { DataColumn, DataTable, type DataTableProps, Icon, Text } from '@umami/react-zen';
import type { ReactNode } from 'react';
import { useMemo, type ReactNode } from 'react';
import { DateDistance } from '@/components/common/DateDistance';
import { LinkButton } from '@/components/common/LinkButton';
import { SortableLabel } from '@/components/common/SortableLabel';
import { useMessages, useNavigation } from '@/components/hooks';
import { useMessages, useNavigation, useWebsiteListChartsQuery } from '@/components/hooks';
import { SquarePen } from '@/components/icons';
import { WebsiteSparkline } from './WebsiteSparkline';
export interface WebsitesTableProps extends DataTableProps {
showActions?: boolean;
@@ -13,13 +14,26 @@ export interface WebsitesTableProps extends DataTableProps {
renderLink?: (row: any) => ReactNode;
}
export function WebsitesTable({ showActions, renderLink, ...props }: WebsitesTableProps) {
export function WebsitesTable({
showActions,
renderLink,
data = [],
...props
}: WebsitesTableProps & { data?: any[] }) {
const { t, labels } = useMessages();
const { renderUrl } = useNavigation();
const websiteIds = useMemo(() => data.map(row => row.id), [data]);
const chartsQuery = useWebsiteListChartsQuery(websiteIds);
const charts = chartsQuery.data?.data || {};
const isChartLoading = chartsQuery.isLoading && !chartsQuery.data;
return (
<DataTable {...props}>
<DataColumn id="name" label={<SortableLabel label={t(labels.name)} sortKey="name" />}>
<DataTable {...props} data={data}>
<DataColumn
id="name"
label={<SortableLabel label={t(labels.name)} sortKey="name" />}
style={{ minWidth: 0 }}
>
{renderLink}
</DataColumn>
<DataColumn
@@ -33,17 +47,34 @@ export function WebsitesTable({ showActions, renderLink, ...props }: WebsitesTab
</Text>
)}
</DataColumn>
<DataColumn
id="chart"
label={<span style={{ whiteSpace: 'normal' }}>{`${t(labels.visitors)} (7d)`}</span>}
style={{ minWidth: 0 }}
>
{(row: any) => {
const chart = charts[row.id];
return (
<WebsiteSparkline
values={chart?.values}
total={chart?.total}
isLoading={isChartLoading}
/>
);
}}
</DataColumn>
<DataColumn
id="created"
label={
<SortableLabel label={t(labels.created)} sortKey="createdAt" defaultDirection="desc" />
}
width="200px"
width="180px"
>
{(row: any) => <DateDistance date={new Date(row.createdAt)} />}
</DataColumn>
{showActions && (
<DataColumn id="action" label=" " align="end" width="60px">
<DataColumn id="action" label=" " align="end" width="48px">
{(row: any) => {
const websiteId = row.id;
+47
View File
@@ -0,0 +1,47 @@
import { z } from 'zod';
import { EVENT_TYPE } from '@/lib/constants';
import { parseDateRange } from '@/lib/date';
import { parseRequest } from '@/lib/request';
import { json } from '@/lib/response';
import { timezoneParam } from '@/lib/schema';
import { canViewLink } from '@/permissions';
import { getWebsiteListCharts } from '@/queries/sql';
const schema = z.object({
ids: z
.string()
.transform(value => value.split(',').map(item => item.trim()).filter(Boolean))
.pipe(z.array(z.uuid()).min(1).max(20)),
startAt: z.coerce.number().int().optional(),
endAt: z.coerce.number().int().optional(),
timezone: timezoneParam.optional(),
});
export async function GET(request: Request) {
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const timezone = query.timezone || 'UTC';
const defaultRange = parseDateRange('7day', undefined, undefined, timezone);
const hasDateRange = query.startAt != null && query.endAt != null;
const startDate = hasDateRange ? new Date(query.startAt) : defaultRange.startDate;
const endDate = hasDateRange ? new Date(query.endAt) : defaultRange.endDate;
const linkIds = (
await Promise.all(
query.ids.map(async (linkId: string) => ((await canViewLink(auth, linkId)) ? linkId : null)),
)
).filter(Boolean);
const data = await getWebsiteListCharts(linkIds, {
startDate,
endDate,
timezone,
eventType: EVENT_TYPE.linkEvent,
});
return json({ data });
}
+49
View File
@@ -0,0 +1,49 @@
import { z } from 'zod';
import { EVENT_TYPE } from '@/lib/constants';
import { parseDateRange } from '@/lib/date';
import { parseRequest } from '@/lib/request';
import { json } from '@/lib/response';
import { timezoneParam } from '@/lib/schema';
import { canViewPixel } from '@/permissions';
import { getWebsiteListCharts } from '@/queries/sql';
const schema = z.object({
ids: z
.string()
.transform(value => value.split(',').map(item => item.trim()).filter(Boolean))
.pipe(z.array(z.uuid()).min(1).max(20)),
startAt: z.coerce.number().int().optional(),
endAt: z.coerce.number().int().optional(),
timezone: timezoneParam.optional(),
});
export async function GET(request: Request) {
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const timezone = query.timezone || 'UTC';
const defaultRange = parseDateRange('7day', undefined, undefined, timezone);
const hasDateRange = query.startAt != null && query.endAt != null;
const startDate = hasDateRange ? new Date(query.startAt) : defaultRange.startDate;
const endDate = hasDateRange ? new Date(query.endAt) : defaultRange.endDate;
const pixelIds = (
await Promise.all(
query.ids.map(async (pixelId: string) =>
(await canViewPixel(auth, pixelId)) ? pixelId : null,
),
)
).filter(Boolean);
const data = await getWebsiteListCharts(pixelIds, {
startDate,
endDate,
timezone,
eventType: EVENT_TYPE.pixelEvent,
});
return json({ data });
}
+47
View File
@@ -0,0 +1,47 @@
import { z } from 'zod';
import { parseDateRange } from '@/lib/date';
import { parseRequest } from '@/lib/request';
import { json } from '@/lib/response';
import { timezoneParam } from '@/lib/schema';
import { canViewWebsite } from '@/permissions';
import { getWebsiteListCharts } from '@/queries/sql';
const schema = z.object({
ids: z
.string()
.transform(value => value.split(',').map(item => item.trim()).filter(Boolean))
.pipe(z.array(z.uuid()).min(1).max(20)),
startAt: z.coerce.number().int().optional(),
endAt: z.coerce.number().int().optional(),
timezone: timezoneParam.optional(),
});
export async function GET(request: Request) {
const { auth, query, error } = await parseRequest(request, schema);
if (error) {
return error();
}
const timezone = query.timezone || 'UTC';
const defaultRange = parseDateRange('7day', undefined, undefined, timezone);
const hasDateRange = query.startAt != null && query.endAt != null;
const startDate = hasDateRange ? new Date(query.startAt) : defaultRange.startDate;
const endDate = hasDateRange ? new Date(query.endAt) : defaultRange.endDate;
const websiteIds = (
await Promise.all(
query.ids.map(async (websiteId: string) =>
(await canViewWebsite(auth, websiteId)) ? websiteId : null,
),
)
).filter(Boolean);
const data = await getWebsiteListCharts(websiteIds, {
startDate,
endDate,
timezone,
});
return json({ data });
}