Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,109 @@
import React from "react";
import "@testing-library/jest-dom/vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { BrowserRouter as Router } from "react-router";
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test, vi } from "vitest";
import AnalyticsOverview from "./AnalyticsOverview";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "de" } }),
}));
vi.mock("i18next", () => ({
t: (key: string) => key,
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({ authenticated: false }),
}));
const overview = {
uniqueVisitors: 1234,
pageViews: 34,
events: 5,
liveVisitors: 1,
top: {
httpReferrers: [{ name: "Direct", count: 1234 }],
urls: [
{ name: null, count: 10 },
{ name: "/pricing", count: 9 },
{ name: "/docs", count: 4 },
],
routes: [{ name: "/portals/:portal", count: 3 }],
sources: [{ name: "newsletter", count: 6 }],
via: [{ name: "partner", count: 4 }],
medium: [{ name: "email", count: 6 }],
campaign: [{ name: "spring", count: 2 }],
user: [],
},
} as any;
function renderOverview() {
return render(
<Router>
<AnalyticsOverview overview={overview} withUsers={false} />
</Router>
);
}
describe("AnalyticsOverview", () => {
test("renders top-item tabs with accessible state and mobile-friendly sizing", () => {
renderOverview();
const pagesTab = screen.getByRole("tab", { name: "analytics.pages" });
const routesTab = screen.getByRole("tab", { name: "analytics.routes" });
const tablist = pagesTab.closest('[role="tablist"]');
expect(tablist).toHaveClass("min-w-0", "overflow-x-auto");
expect(pagesTab).toHaveClass("min-h-10", "shrink-0", "whitespace-nowrap");
expect(pagesTab).toHaveAttribute("aria-selected", "true");
expect(routesTab).toHaveAttribute("aria-selected", "false");
const panel = screen.getByRole("tabpanel", { name: "analytics.pages" });
expect(panel).toHaveAttribute("id", pagesTab.getAttribute("aria-controls"));
expect(within(panel).getByText("shared.notSet")).toBeInTheDocument();
expect(within(panel).getByText("/pricing")).toBeInTheDocument();
fireEvent.click(routesTab);
expect(routesTab).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("tabpanel", { name: "analytics.routes" })).toHaveTextContent("/portals/:portal");
});
test("supports keyboard tab selection", () => {
renderOverview();
const pagesTab = screen.getByRole("tab", { name: "analytics.pages" });
fireEvent.keyDown(pagesTab, { key: "ArrowRight" });
expect(screen.getByRole("tab", { name: "analytics.routes" })).toHaveAttribute("aria-selected", "true");
});
test("formats overview numbers with the active locale", () => {
renderOverview();
expect(screen.getAllByText("1.234").length).toBeGreaterThanOrEqual(2);
});
test("keeps analytics overview free of legacy number formatters", () => {
const sourceRoot = path.resolve(process.cwd(), "apps/web/app/components/analytics");
const overviewSource = fs.readFileSync(path.join(sourceRoot, "AnalyticsOverview.tsx"), "utf8");
const chartSource = fs.readFileSync(path.join(sourceRoot, "AnalyticsOverviewChart.tsx"), "utf8");
expect(`${overviewSource}\n${chartSource}`).not.toContain("NumberUtils");
});
test("precomputes top-item max counts once per item set", () => {
const source = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/components/analytics/AnalyticsOverview.tsx"), "utf8");
expect(source).toContain("useMemo");
expect(source).toContain("const maxCount = useMemo");
expect(source).toContain('fallbackName: t("shared.notSet")');
expect(source).not.toContain('fallbackName: "?"');
expect(source).not.toContain('fallbackName: "none"');
expect(source).not.toContain("const counts = items.map");
expect(source).not.toContain("Math.max(...counts)");
});
});
@@ -0,0 +1,329 @@
import { Link } from "react-router";
import { t as i18nT } from "i18next";
import clsx from "clsx";
import { lazy, Suspense, useEffect, useId, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import UrlUtils from "~/utils/app/UrlUtils";
import { useRootData } from "~/utils/data/useRootData";
import type { AnalyticsOverviewDto } from "~/utils/helpers/.server/AnalyticsService";
import { useLocaleFormatters } from "~/locale/format";
import { Card } from "../ui/card";
import { Label } from "../ui/label";
const AnalyticsOverviewChart = lazy(() => import("./AnalyticsOverviewChart"));
function joinRootUrl(rootUrl: string | undefined, path: string) {
if (!rootUrl) {
return path;
}
return `${rootUrl.replace(/\/+$/g, "")}/${path.replace(/^\/+/g, "")}`;
}
const MetricCard = ({ label, value }: { label: string; value: string | number }) => {
const formatters = useLocaleFormatters();
return (
<Card className="group-hover:bg-secondary mx-auto h-24 gap-3 p-4">
<Label>{label}</Label>
<div className="text-2xl font-semibold tracking-normal">{formatters.number(Number(value), { maximumFractionDigits: 0 })}</div>
</Card>
);
};
const Metrics = ({ authenticated, overview, rootUrl }: { authenticated: Boolean; overview: AnalyticsOverviewDto; rootUrl?: string }) => {
const { t } = useTranslation();
return (
<dl className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
{authenticated ? (
<>
<Link to={joinRootUrl(rootUrl, "visitors")} className="group">
<MetricCard label={t("analytics.uniqueVisitors")} value={overview.uniqueVisitors} />
</Link>
<Link to={joinRootUrl(rootUrl, "page-views")} className="group">
<MetricCard label={t("analytics.pageViews")} value={overview.pageViews} />
</Link>
<Link to={joinRootUrl(rootUrl, "events")} className="group">
<MetricCard label={t("analytics.events")} value={overview.events} />
</Link>
</>
) : (
<>
<MetricCard label={t("analytics.uniqueVisitors")} value={overview.uniqueVisitors} />
<MetricCard label={t("analytics.pageViews")} value={overview.pageViews} />
<MetricCard label={t("analytics.events")} value={overview.events} />
</>
)}
<div>
<MetricCard label={t("analytics.liveVisitors")} value={overview.liveVisitors} />
</div>
</dl>
);
};
interface TopItemDto {
title: string;
items: { name: string | null; count: number; image?: any }[];
viewMoreRoute?: string;
fallbackName?: string;
bgClassName?: string;
tabTitle?: string;
}
function TopItemsData({ title, items, viewMoreRoute, fallbackName, bgClassName }: TopItemDto) {
const { authenticated } = useRootData();
const formatters = useLocaleFormatters();
const maxCount = useMemo(() => Math.max(0, ...items.map((item) => item.count)), [items]);
function getWidthPercentageCss(current: { count: number }) {
const percentage = maxCount > 0 ? (current.count / maxCount) * 100 : 0;
if (percentage >= 95) {
return "w-[95%]";
} else if (percentage >= 90) {
return "w-[90%]";
} else if (percentage >= 80) {
return "w-[80%]";
} else if (percentage >= 70) {
return "w-[70%]";
} else if (percentage >= 60) {
return "w-[60%]";
} else if (percentage >= 50) {
return "w-[50%]";
} else if (percentage >= 40) {
return "w-[40%]";
} else if (percentage >= 30) {
return "w-[30%]";
} else if (percentage >= 20) {
return "w-[20%]";
} else if (percentage >= 10) {
return "w-[10%]";
} else if (percentage >= 3) {
return "w-[3%]";
}
return "w-[3%]";
}
const renderTopItems = () => {
return items.map((item, idx) => (
<div key={idx} className="flex justify-between space-x-2">
<div className="w-full truncate">
<div className="flex items-center space-x-1">
<div
className={clsx("flex items-center space-x-2 overflow-visible px-2 py-0.5 text-sm", getWidthPercentageCss(item), bgClassName ?? "bg-orange-50")}
>
{item.image !== undefined && <div className="flex-shrink-0">{item.image}</div>}
{fallbackName ? <span>{!item.name ? fallbackName : item.name}</span> : <div>{item.name}</div>}
</div>
</div>
</div>
<div className="px-2 py-0.5 text-right text-sm font-extrabold">{formatters.number(item.count, { maximumFractionDigits: 0 })}</div>
</div>
));
};
return (
<>
<div className="h-48 space-y-1 overflow-y-auto">{renderTopItems()}</div>
{viewMoreRoute && authenticated && (
<Link to={viewMoreRoute} className="text-muted-foreground hover:text-foreground/80 flex justify-center p-1 text-xs font-medium underline">
{i18nT("analytics.viewMore")}
</Link>
)}
</>
);
}
function TopItems({ tabs }: { tabs: TopItemDto[] }) {
const [selectedTab, setSelectedTab] = useState(0);
const tab = tabs[selectedTab] ?? tabs[0];
const baseId = useId();
useEffect(() => {
if (selectedTab >= tabs.length) {
setSelectedTab(0);
}
}, [selectedTab, tabs.length]);
function selectAdjacentTab(offset: number) {
setSelectedTab((current) => (current + offset + tabs.length) % tabs.length);
}
return (
<div className="border-border bg-background min-w-0 space-y-1 rounded-md border px-4 py-2 shadow-sm">
<div className="flex min-w-0 items-center justify-between gap-2">
<h4 id={`${baseId}-heading`} className="min-w-0 truncate text-sm font-bold">
{tab.title}
</h4>
{tabs.length > 1 && (
<div role="tablist" aria-labelledby={`${baseId}-heading`} className="flex min-w-0 items-center gap-1 overflow-x-auto">
{tabs.map((item, idx) => {
const selected = selectedTab === idx;
return (
<button
key={idx}
id={`${baseId}-tab-${idx}`}
type="button"
role="tab"
aria-selected={selected}
aria-controls={`${baseId}-panel`}
tabIndex={selected ? 0 : -1}
onClick={() => setSelectedTab(idx)}
onKeyDown={(event) => {
if (event.key === "ArrowRight") {
event.preventDefault();
selectAdjacentTab(1);
} else if (event.key === "ArrowLeft") {
event.preventDefault();
selectAdjacentTab(-1);
} else if (event.key === "Home") {
event.preventDefault();
setSelectedTab(0);
} else if (event.key === "End") {
event.preventDefault();
setSelectedTab(tabs.length - 1);
}
}}
className={clsx(
"min-h-10 shrink-0 rounded-md px-2 py-1 text-xs font-medium whitespace-nowrap focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
selected ? "text-theme-500 hover:text-theme-600 underline" : "text-muted-foreground hover:text-foreground"
)}
>
{item.tabTitle}
</button>
);
})}
</div>
)}
</div>
<div id={`${baseId}-panel`} role={tabs.length > 1 ? "tabpanel" : undefined} aria-labelledby={tabs.length > 1 ? `${baseId}-tab-${selectedTab}` : undefined}>
<TopItemsData {...tab} />
</div>
</div>
);
}
export default function AnalyticsOverview({ overview, withUsers, rootUrl }: { overview: AnalyticsOverviewDto; withUsers: boolean; rootUrl?: string }) {
const { authenticated } = useRootData();
const { t } = useTranslation();
return (
<div className="space-y-2">
<div className="w-64"></div>
<Metrics authenticated={authenticated} overview={overview} rootUrl={rootUrl} />
{overview.charts && (
<Suspense fallback={<Card className="h-56 animate-pulse p-4" />}>
<AnalyticsOverviewChart chartData={overview.charts.pageViewsAndUniqueVisitors} pageViewsLabel={t("analytics.pageViews")} uniqueVisitorsLabel={t("analytics.uniqueVisitors")} />
</Suspense>
)}
<div className={clsx("grid gap-2", withUsers && "md:grid-cols-2 lg:grid-cols-4", !withUsers && "md:grid-cols-2 lg:grid-cols-3")}>
<TopItems
tabs={[
{
title: t("analytics.topHttpReferrers"),
items: overview.top.httpReferrers.map((item) => {
return {
image:
!item.name || item.name === "Direct" ? (
<svg
className="text-muted-foreground h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
stroke="currentColor"
>
<path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75l3 3m0 0l3-3m-3 3v-7.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
) : item.name.startsWith("localhost") ? (
<svg
className="text-muted-foreground h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
stroke="currentColor"
>
<path strokeLinecap="round" strokeLinejoin="round" d="M17.25 6.75L22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3l-4.5 16.5" />
</svg>
) : (
<img className="h-4 w-4" src={`http://www.google.com/s2/favicons?domain=${item.name}&sz=256`} alt={item.name} />
),
name: UrlUtils.stripTrailingSlash(item.name?.replace("https://", "").replace("http://", "").replace("www.", "") ?? ""),
count: item.count,
};
}),
fallbackName: t("analytics.direct"),
bgClassName: "bg-orange-50 dark:bg-orange-900 dark:text-white",
},
]}
/>
<TopItems
tabs={[
{
title: t("analytics.topPages"),
items: overview.top.urls,
fallbackName: t("shared.notSet"),
bgClassName: "bg-emerald-50 dark:bg-emerald-900 dark:text-white",
tabTitle: t("analytics.pages"),
},
{
title: t("analytics.topRoutes"),
items: overview.top.routes,
fallbackName: t("shared.notSet"),
bgClassName: "bg-emerald-50 dark:bg-emerald-900 dark:text-white",
tabTitle: t("analytics.routes"),
},
]}
/>
<TopItems
tabs={[
{
tabTitle: t("analytics.source"),
title: t("analytics.topSources"),
items: overview.top.sources,
fallbackName: t("analytics.fallbacks.noReferrer"),
bgClassName: "bg-indigo-50 dark:bg-indigo-900 dark:text-white",
},
{
tabTitle: t("analytics.referrers"),
title: t("analytics.topReferrers"),
items: overview.top.via,
fallbackName: t("shared.notSet"),
bgClassName: "bg-teal-50 dark:bg-teal-900 dark:text-white",
},
{
tabTitle: t("analytics.medium"),
title: t("analytics.medium"),
items: overview.top.medium,
fallbackName: t("shared.notSet"),
bgClassName: "bg-indigo-50 dark:bg-indigo-900 dark:text-white",
},
{
tabTitle: t("analytics.campaigns"),
title: t("analytics.campaigns"),
items: overview.top.campaign,
fallbackName: t("shared.notSet"),
bgClassName: "bg-indigo-50 dark:bg-indigo-900 dark:text-white",
},
]}
/>
{withUsers && (
<TopItems
tabs={[
{
tabTitle: t("models.user.plural"),
title: t("models.user.plural"),
items: overview.top.user,
fallbackName: t("shared.notSet"),
bgClassName: "bg-indigo-50 dark:bg-indigo-900 dark:text-white",
},
]}
/>
)}
</div>
</div>
);
}
@@ -0,0 +1,33 @@
import { Area, AreaChart, CartesianGrid, Legend, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import type { AnalyticsOverviewDto } from "~/utils/helpers/.server/AnalyticsService";
import { useLocaleFormatters } from "~/locale/format";
import { Card } from "../ui/card";
type AnalyticsOverviewChartProps = {
chartData: NonNullable<AnalyticsOverviewDto["charts"]>["pageViewsAndUniqueVisitors"];
pageViewsLabel: string;
uniqueVisitorsLabel: string;
};
export default function AnalyticsOverviewChart({ chartData, pageViewsLabel, uniqueVisitorsLabel }: AnalyticsOverviewChartProps) {
const formatters = useLocaleFormatters();
const valueFormatter = (value: number) => formatters.number(value, { maximumFractionDigits: 0 });
return (
<Card className="h-56 p-4">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData} margin={{ top: 8, right: 16, left: 0, bottom: 0 }}>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="date" tickLine={false} axisLine={false} fontSize={12} />
<YAxis tickFormatter={valueFormatter} tickLine={false} axisLine={false} fontSize={12} width={48} />
<Tooltip formatter={(value) => valueFormatter(Number(value))} />
<Legend />
<Area type="monotone" dataKey="Page views" name={pageViewsLabel} stroke="#4f46e5" fill="#4f46e5" fillOpacity={0.16} strokeWidth={2} />
<Area type="monotone" dataKey="Unique visitors" name={uniqueVisitorsLabel} stroke="#0891b2" fill="#0891b2" fillOpacity={0.16} strokeWidth={2} />
</AreaChart>
</ResponsiveContainer>
</Card>
);
}
@@ -0,0 +1,57 @@
import React from "react";
import { render, screen } from "@testing-library/react";
import AnalyticsPageViewsTable from "./AnalyticsPageViewsTable";
import { BrowserRouter as Router } from "react-router";
import { AnalyticsPageView } from "@toolctrl/db/prisma-browser";
import { vi, describe, expect, test } from "vitest";
vi.mock("react-i18next", () => ({
useTranslation: () => {
return { t: (str: string) => str, i18n: { exists: (key: string) => ["analytics.url", "analytics.viewed"].includes(key) } };
},
}));
const d = "2023-03-21";
const items = [
{ id: "1", url: "/page1", route: "/page1", createdAt: d, uniqueVisitorId: "1" },
{ id: "2", url: "/page2", route: "/page2", createdAt: d, uniqueVisitorId: "1" },
] as unknown as AnalyticsPageView[];
describe("AnalyticsPageViewsTable", () => {
test("renders table with correct headers and values", () => {
const result = render(
<Router>
<AnalyticsPageViewsTable items={items} />
</Router>
);
const table = result.container.getElementsByTagName("table")[0];
// Check number of rows
const rows = screen.getAllByRole("row");
expect(rows.length).toBe(items.length + 1); // Include header row
// Check number of columns
const headerRow = table.getElementsByTagName("thead")[0];
const headers = headerRow.getElementsByTagName("th");
expect(headers.length).toBe(2);
// Check header titles
const headerTitles = [...headers].map((header) => header.textContent);
expect(headerTitles).toContain("analytics.url");
expect(headerTitles).toContain("analytics.viewed");
// Check cell values
items.forEach((item, i) => {
const tbody = table.getElementsByTagName("tbody")[0];
const row = tbody.getElementsByTagName("tr")[i];
const cells = row.getElementsByTagName("td");
expect(cells.length).toBe(2);
expect(cells[0].textContent).toContain(item.url);
expect(cells[0].textContent).toContain(item.route);
expect(cells[1].textContent).toMatch(/21\.03\.2023|Mar 21, 2023/);
});
});
});
@@ -0,0 +1,31 @@
import { AnalyticsPageView } from "@toolctrl/db/prisma-browser";
import { useTranslation } from "react-i18next";
import DateCell from "../ui/dates/DateCell";
import TableSimple from "../ui/tables/TableSimple";
export default function AnalyticsPageViewsTable({ items }: { items: AnalyticsPageView[] }) {
const { t } = useTranslation();
return (
<TableSimple
items={items}
headers={[
{
name: "url",
title: t("analytics.url"),
className: "w-full",
value: (item) => (
<div className="flex flex-col truncate">
<div className="font-medium text-gray-800">{item.url}</div>
<div className="text-muted-foreground">{item.route}</div>
</div>
),
},
{
name: "date",
title: t("analytics.viewed"),
value: (item) => <DateCell date={item.createdAt} />,
},
]}
/>
);
}