Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,58 @@
import { Bar, BarChart, CartesianGrid, Legend, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { useTranslation } from "react-i18next";
import { useLocaleFormatters } from "~/locale/format";
import { formatMonthLabel } from "./dashboardFormatters";
export type DashboardMonthlySeriesChartProps = {
/** `id` is an ISO month (`2026-07`); the label is formatted for the viewer's locale. */
points: readonly { id: string; value: number; comparisonValue?: number }[];
valueFormat: "currency" | "count";
hasComparison: boolean;
};
/**
* Lazily loaded visual enhancement. Columns, not bars: time runs left to right
* (IBCS). The current period is the solid, saturated series and the previous
* year is the lighter one behind it — the only two encodings on the chart, so a
* reader can tell "now" from "then" without decoding a colour key.
*
* The parent card owns the accessible summary and data table, so this SVG is
* hidden from assistive technology.
*/
export default function DashboardMonthlySeriesChart({ points, valueFormat, hasComparison }: DashboardMonthlySeriesChartProps) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const formatValue = (value: number) =>
valueFormat === "currency"
? formatters.currency(value, "EUR", { maximumFractionDigits: 0 })
: formatters.number(value, { maximumFractionDigits: 0 });
const data = points.map((point) => ({
...point,
label: formatMonthLabel(point.id, formatters.locale),
}));
return (
<div className="h-64 w-full" aria-hidden="true" data-ui-id="ui.dashboard.widget.sales.orderIntake.chart">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 8, right: 8, bottom: 8, left: 8 }}>
<CartesianGrid vertical={false} strokeDasharray="3 3" />
<XAxis dataKey="label" tickLine={false} axisLine={false} interval="preserveStartEnd" minTickGap={8} />
<YAxis
tickLine={false}
axisLine={false}
width={72}
tickFormatter={(value) => formatters.compact(Number(value), { maximumFractionDigits: 1 })}
/>
<Tooltip cursor={{ fill: "rgba(107, 114, 128, 0.08)" }} formatter={(value) => formatValue(Number(value))} />
{hasComparison ? <Legend verticalAlign="top" height={28} /> : null}
{hasComparison ? (
<Bar dataKey="comparisonValue" name={t("app.dashboard.series.previousYear")} fill="#cbd5e1" radius={[4, 4, 0, 0]} maxBarSize={28} />
) : null}
<Bar dataKey="value" name={t("app.dashboard.series.currentPeriod")} fill="#334155" radius={[4, 4, 0, 0]} maxBarSize={28} />
</BarChart>
</ResponsiveContainer>
</div>
);
}
@@ -0,0 +1,261 @@
// R-P11b interim-UI (AD-28) — DashboardPage unit test. Fixture via the real
// buildDashboardPageVM. The page is display-only: it renders the derived layout
// and owns no controls. i18n mocked.
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
buildDashboardPageVM,
type BuildDashboardPageInput,
type DashboardPageVM,
} from "@hivegrid/view-models";
import { DashboardPage } from "./DashboardPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
const byUiId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLElement;
function fixtureInput(overrides: Partial<BuildDashboardPageInput> = {}): BuildDashboardPageInput {
return {
catalog: [
{
key: "general.welcome",
domain: "general",
kind: "hero",
titleKey: "app.dashboard.widgets.welcome.title",
descriptionKey: "app.dashboard.widgets.welcome.description",
requiredAnyPermission: ["dashboard.read"],
defaultPeriod: "today",
},
{
key: "sales.forecast",
domain: "sales",
kind: "trend",
titleKey: "app.dashboard.widgets.salesForecast.title",
descriptionKey: "app.dashboard.widgets.salesForecast.description",
requiredAnyPermission: ["deals.read_aggregates"],
defaultPeriod: "quarter",
},
{
key: "tasks.my_open",
domain: "tasks",
kind: "list",
titleKey: "app.dashboard.widgets.myTasks.title",
descriptionKey: "app.dashboard.widgets.myTasks.description",
requiredAnyPermission: ["tasks.read_own"],
defaultPeriod: "today",
},
],
layouts: [
{
role: "gf",
nameKey: "app.dashboard.roles.gf.name",
descriptionKey: "app.dashboard.roles.gf.description",
mobileFirst: false,
widgets: [
{ key: "general.welcome", position: { x: 0, y: 0 }, size: { w: 12, h: 1 } },
{ key: "sales.forecast", position: { x: 0, y: 1 }, size: { w: 4, h: 2 } },
{ key: "tasks.my_open", position: { x: 4, y: 1 }, size: { w: 4, h: 2 } },
],
},
{
role: "monteur",
nameKey: "app.dashboard.roles.monteur.name",
descriptionKey: "app.dashboard.roles.monteur.description",
mobileFirst: true,
widgets: [{ key: "tasks.my_open", position: { x: 0, y: 0 }, size: { w: 12, h: 2 } }],
},
],
snapshot: {
generatedAt: "2026-07-12T08:00:00.000Z",
sales: {
openProjects: 7,
wonProjects: 3,
forecastValue: 125000,
winRate: {
won: 18,
lost: 7,
rate: 0.72,
outcomes: [
{ id: "won", labelKey: "app.dashboard.winRate.won", value: 18, color: "#334155" },
{ id: "lost", labelKey: "app.dashboard.winRate.lost", value: 7, color: "#cbd5e1" },
],
},
orderIntake: {
currentMonth: 42000,
trailingTwelveMonths: 318000,
series: {
points: [
{ id: "2026-05", value: 21000, comparisonValue: 18000 },
{ id: "2026-06", value: 35000, comparisonValue: 30000 },
{ id: "2026-07", value: 42000, comparisonValue: 26000 },
],
valueFormat: "currency",
hasComparison: true,
},
},
},
projects: {
activeProjects: 5,
dueSoon: 2,
openDefects: 1,
myProjects: [],
stageDistribution: [{ id: "stage-1", label: "Vertrieb · Qualifiziert", value: 4, color: "#2563eb" }],
},
tasks: {
myOpen: 4,
dueToday: 1,
items: [{ id: "task-1", label: "Angebot nachfassen", href: "/app/acme/tasks", meta: "2026-07-14" }],
},
hr: { pendingRequests: 2 },
activity: { items: [] },
comms: { callsToday: 6 },
finance: {
openReceivables: 48000,
overdueReceivables: 12500,
agingBuckets: [
{ id: "not_due", labelKey: "app.dashboard.receivables.notDue", value: 35500, color: "#94a3b8" },
{ id: "overdue_1_30", labelKey: "app.dashboard.receivables.overdue1To30", value: 8000, color: "#64748b" },
{ id: "overdue_31_60", labelKey: "app.dashboard.receivables.overdue31To60", value: 3000, color: "#475569" },
{ id: "overdue_61_90", labelKey: "app.dashboard.receivables.overdue61To90", value: 1000, color: "#d97706" },
{ id: "overdue_90_plus", labelKey: "app.dashboard.receivables.overdue90Plus", value: 500, color: "#b91c1c" },
],
averageDaysToPayment: 27,
},
schedule: { today: [] },
},
permissions: ["dashboard.read", "deals.read_aggregates", "tasks.read_own"],
activeRole: "gf",
streamUrl: "/app/acme/dashboard/stream",
canCustomize: true,
...overrides,
};
}
function renderPage(vm: DashboardPageVM) {
render(<DashboardPage vm={vm} />);
}
describe("DashboardPage", () => {
it("renders the active role layout with hero, KPI, and list widgets", () => {
renderPage(buildDashboardPageVM(fixtureInput()));
expect(byUiId("ui.dashboard.roleLayouts")).toBeTruthy();
expect(byUiId("ui.dashboard.widget.general.welcome")).toBeTruthy();
expect(byUiId("ui.dashboard.widget.sales.forecast")).toBeTruthy();
expect(byUiId("ui.dashboard.widget.tasks.my_open")).toBeTruthy();
expect(screen.getByText("Angebot nachfassen")).toBeTruthy();
expect(screen.getByText(/125\.000/)).toBeTruthy();
});
it("wraps single-metric tiles in a link when the widget carries an href", () => {
renderPage(buildDashboardPageVM(fixtureInput({ widgetHrefs: { "sales.forecast": "/acme/projects/boards" } })));
const link = byUiId("ui.dashboard.widget.sales.forecast.link");
expect(link).toBeTruthy();
expect(link?.getAttribute("href")).toBe("/acme/projects/boards");
});
it("uses the 12-column layout contract and exposes chart data as an accessible table", () => {
const base = fixtureInput();
const catalog: BuildDashboardPageInput["catalog"] = [
...base.catalog,
{
key: "projects.stage_distribution",
domain: "projects",
kind: "chart",
titleKey: "app.dashboard.widgets.stageDistribution.title",
descriptionKey: "app.dashboard.widgets.stageDistribution.description",
requiredAnyPermission: ["dashboard.read"],
defaultPeriod: "30d",
},
];
const layouts: BuildDashboardPageInput["layouts"] = [
{
...base.layouts[0]!,
widgets: [
...base.layouts[0]!.widgets,
{ key: "projects.stage_distribution", position: { x: 0, y: 3 }, size: { w: 8, h: 3 } },
],
},
];
renderPage(buildDashboardPageVM(fixtureInput({ catalog, layouts })));
expect(byUiId("ui.dashboard.widget.projects.stage_distribution")?.parentElement?.className).toContain("lg:col-span-8");
expect(byUiId("ui.dashboard.widget.projects.stage_distribution")?.parentElement?.className).toContain("lg:col-start-1");
expect(screen.getByRole("table", { name: "app.dashboard.widgets.stageDistribution.title" })).toBeTruthy();
expect(screen.getByRole("rowheader", { name: "Vertrieb · Qualifiziert" })).toBeTruthy();
expect(screen.queryByText("app.dashboard.customize.available")).toBeNull();
});
it("renders a monthly series widget with an accessible month table", async () => {
const base = fixtureInput();
const catalog: BuildDashboardPageInput["catalog"] = [
...base.catalog,
{
key: "sales.order_intake",
domain: "sales",
kind: "trend",
titleKey: "app.dashboard.widgets.orderIntake.title",
descriptionKey: "app.dashboard.widgets.orderIntake.description",
requiredAnyPermission: ["deals.read_aggregates"],
defaultPeriod: "quarter",
},
];
const layouts: BuildDashboardPageInput["layouts"] = [
{ ...base.layouts[0]!, widgets: [{ key: "sales.order_intake", position: { x: 0, y: 0 }, size: { w: 8, h: 3 } }] },
];
renderPage(buildDashboardPageVM(fixtureInput({ catalog, layouts })));
const table = await screen.findByRole("table", { name: "app.dashboard.widgets.orderIntake.title" });
expect(table).toBeTruthy();
// Every month of the series is readable without the chart, including the
// previous-year column the visual encoding carries as a second bar.
expect(screen.getByRole("columnheader", { name: "app.dashboard.series.previousYear" })).toBeTruthy();
expect(screen.getAllByRole("rowheader")).toHaveLength(3);
// Once as the headline metric, once in the month table.
expect(screen.getAllByText(/42\.000/).length).toBeGreaterThanOrEqual(2);
});
it("marks permission-hidden widgets with clear text instead of data", () => {
renderPage(buildDashboardPageVM(fixtureInput({ permissions: ["dashboard.read"] })));
expect(screen.getAllByText("app.dashboard.widgets.permissionHidden").length).toBeGreaterThan(0);
expect(screen.queryByText(/125\.000/)).toBeNull();
});
it("renders the derived layout without offering a role switcher", () => {
renderPage(buildDashboardPageVM(fixtureInput()));
expect(document.querySelector("[data-ui-id^='ui.dashboard.roleSwitcher']")).toBeNull();
});
it("renders the Monteur layout when the server derived it", () => {
renderPage(buildDashboardPageVM(fixtureInput({ activeRole: "monteur" })));
expect(byUiId("ui.dashboard.widget.tasks.my_open")).toBeTruthy();
expect(byUiId("ui.dashboard.widget.sales.forecast")).toBeNull();
});
it("offers no live-update controls", () => {
renderPage(buildDashboardPageVM(fixtureInput()));
expect(byUiId("ui.dashboard.liveBar")).toBeNull();
expect(byUiId("ui.dashboard.live.toggle")).toBeNull();
expect(byUiId("ui.dashboard.live.lastUpdated")).toBeNull();
});
it("renders a plain-language loading state", () => {
renderPage({ status: "loading" });
expect(byUiId("ui.dashboard.page.loading")).toBeTruthy();
expect(screen.getByText("app.dashboard.loading")).toBeTruthy();
});
it("renders the catalog error message in the error state", () => {
renderPage({ status: "error", error: { messageKey: "app.dashboard.errors.tenantNotFound" } });
expect(byUiId("ui.dashboard.page.error")).toBeTruthy();
expect(screen.getByText("app.dashboard.errors.tenantNotFound")).toBeTruthy();
});
});
@@ -0,0 +1,371 @@
// R-P11b (P11 dashboard, 3 fixed role layouts) Interim-UI (AD-28) — composed
// from ~/ui (D-DASH archetype "KPI + Widget-Compose"). Pure: renders the
// permission-gated widget grid of the one layout the server derived from the
// member's seat. The route owns the SSE stream and feeds the latest snapshot in
// as the VM, so the page has no live-state controls of its own. No
// useLoaderData. Final Subframe optics = tracked design-nachzug (D-DASH).
import { lazy, Suspense, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
FeatherActivity,
FeatherCalendar,
FeatherCheckSquare,
FeatherCreditCard,
FeatherFolder,
FeatherHome,
FeatherLayoutDashboard,
FeatherPhoneCall,
FeatherTrendingUp,
FeatherUsers,
} from "@subframe/core";
import type { DashboardPageVM, DashboardWidgetDomain, DashboardWidgetItemVM, DashboardWidgetVM } from "@hivegrid/view-models";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { Alert } from "~/ui/components/Alert";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { Loader } from "~/ui/components/Loader";
import { StatsCard } from "~/ui/components/StatsCard";
import { APP_TIME_ZONE, createLocaleFormatters } from "~/locale/format";
import { formatMonthLabel } from "./dashboardFormatters";
import { AppLink } from "~/components/app/AppLink";
const DashboardStageDistributionChart = lazy(() => import("./DashboardStageDistributionChart"));
const DashboardMonthlySeriesChart = lazy(() => import("./DashboardMonthlySeriesChart"));
export type DashboardPageProps = {
vm: DashboardPageVM;
};
const sectionHeading = "text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary";
const mutedText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
const metricValue = "text-subtitle-0 font-subtitle-0 text-text-neutral-primary";
const domainIcons: Record<DashboardWidgetDomain, ReactNode> = {
general: <FeatherHome />,
sales: <FeatherTrendingUp />,
finance: <FeatherCreditCard />,
projects: <FeatherFolder />,
tasks: <FeatherCheckSquare />,
hr: <FeatherUsers />,
activity: <FeatherActivity />,
comms: <FeatherPhoneCall />,
schedule: <FeatherCalendar />,
};
/** Same currency/count rendering as the chart, for the screen-reader table. */
function formatSeriesValue(value: number, format: "currency" | "count", language: string): string {
const formatters = createLocaleFormatters(language);
return format === "currency"
? formatters.currency(value, "EUR", { maximumFractionDigits: 0 })
: formatters.number(value, { maximumFractionDigits: 0 });
}
function formatDateTime(value: string | null, language: string): string {
if (!value) return "—";
return new Intl.DateTimeFormat(language, { timeZone: APP_TIME_ZONE, dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
}
export function DashboardPage(props: DashboardPageProps) {
const { t, i18n } = useTranslation();
const header = (
<PageHeader icon={<FeatherLayoutDashboard className={PAGE_HEADER_ICON_CLASS} />} title={t("app.dashboard.title")} />
);
if (props.vm.status === "loading" || props.vm.status === "idle") {
return (
<PageShell uiId="ui.dashboard.page.loading">
{header}
<PageBody className="items-center gap-4">
<Loader size="medium" />
<span className={mutedText}>{t("app.dashboard.loading")}</span>
</PageBody>
</PageShell>
);
}
if (props.vm.status === "error") {
return (
<PageShell uiId="ui.dashboard.page.error">
{header}
<PageBody>
<Alert variant="error" title={t(props.vm.error.messageKey)} />
</PageBody>
</PageShell>
);
}
if (props.vm.status === "empty") {
return (
<PageShell uiId="ui.dashboard.page.empty">
{header}
<PageBody>
<EmptyState outlined title={t("app.dashboard.title")} body={t("app.dashboard.widgets.empty")} />
</PageBody>
</PageShell>
);
}
const data = props.vm.data;
const activeRole = data.layout;
return (
<PageShell uiId="ui.dashboard.roleLayouts">
<PageHeader
icon={<FeatherLayoutDashboard className={PAGE_HEADER_ICON_CLASS} />}
title={t("app.dashboard.title")}
subtitle={t(activeRole.descriptionKey)}
/>
<PageBody>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-flow-row-dense lg:grid-cols-12">
{activeRole.widgets.map((widget) => (
<div key={widget.key} className={dashboardWidgetGridClass(widget)}>
<DashboardWidgetCard widget={widget} language={i18n.language} />
</div>
))}
</div>
</PageBody>
</PageShell>
);
}
function DashboardWidgetCard({ widget, language }: { widget: DashboardWidgetVM; language: string }) {
const { t } = useTranslation();
if (!widget.visible) {
return (
<Card className="h-full" data-ui-id={`ui.dashboard.widget.${widget.key}`}>
<span className={sectionHeading}>{t(widget.titleKey)}</span>
<span className={mutedText}>{t("app.dashboard.widgets.permissionHidden")}</span>
</Card>
);
}
if (widget.series) {
const series = widget.series;
const descriptionId = `dashboard-series-${widget.key.replace(/[^a-z0-9]+/gi, "-")}-description`;
return (
<Card className="h-full" data-ui-id={`ui.dashboard.widget.${widget.key}`}>
<div className="flex w-full items-start justify-between gap-2">
<div className="flex flex-col gap-1">
<span className={sectionHeading}>{t(widget.titleKey)}</span>
<span id={descriptionId} className={mutedText}>
{t(widget.descriptionKey)}
</span>
</div>
<SubframeIcon domain={widget.domain} />
</div>
{widget.metrics.length > 0 ? (
<div className="grid w-full grid-cols-2 gap-4">
{widget.metrics.map((metric) => (
<div key={metric.labelKey} className="flex flex-col gap-1">
<span className={mutedText}>{t(metric.labelKey)}</span>
<span className={metricValue}>{metric.value}</span>
</div>
))}
</div>
) : null}
<Suspense
fallback={
<div className="flex h-64 items-center justify-center">
<Loader size="medium" />
</div>
}
>
<DashboardMonthlySeriesChart points={series.points} valueFormat={series.valueFormat} hasComparison={series.hasComparison} />
</Suspense>
<div className="sr-only">
<table aria-describedby={descriptionId}>
<caption>{t(widget.titleKey)}</caption>
<thead>
<tr>
<th scope="col">{t("app.dashboard.series.monthColumn")}</th>
<th scope="col">{t("app.dashboard.series.currentPeriod")}</th>
{series.hasComparison ? <th scope="col">{t("app.dashboard.series.previousYear")}</th> : null}
</tr>
</thead>
<tbody>
{series.points.map((point) => (
<tr key={point.id}>
<th scope="row">{formatMonthLabel(point.id, language)}</th>
<td>{formatSeriesValue(point.value, series.valueFormat, language)}</td>
{series.hasComparison ? (
<td>{point.comparisonValue === undefined ? "—" : formatSeriesValue(point.comparisonValue, series.valueFormat, language)}</td>
) : null}
</tr>
))}
</tbody>
</table>
</div>
</Card>
);
}
if (widget.kind === "chart") {
const points = widget.chart?.points ?? [];
const resolvedPoints = points.map((point) => ({
...point,
label: point.labelKey ? t(point.labelKey) : point.label ?? "—",
}));
const descriptionId = `dashboard-chart-${widget.key.replace(/[^a-z0-9]+/gi, "-")}-description`;
return (
<Card className="h-full min-h-[22rem]" data-ui-id={`ui.dashboard.widget.${widget.key}`}>
<div className="flex w-full items-start justify-between gap-2">
<div className="flex flex-col gap-1">
<span className={sectionHeading}>{t(widget.titleKey)}</span>
<span id={descriptionId} className={mutedText}>{t(widget.descriptionKey)}</span>
</div>
<SubframeIcon domain={widget.domain} />
</div>
{points.length > 0 ? (
<>
<Suspense fallback={<div className="flex min-h-60 items-center justify-center"><Loader size="medium" /></div>}>
<DashboardStageDistributionChart points={resolvedPoints} valueFormat={widget.chart?.valueFormat ?? "count"} />
</Suspense>
<div className="sr-only">
<p>{t("app.dashboard.widgets.stageDistribution.a11ySummary", { count: points.reduce((sum, point) => sum + point.value, 0) })}</p>
<table aria-describedby={descriptionId}>
<caption>{t(widget.titleKey)}</caption>
<thead>
<tr>
<th scope="col">{t("app.dashboard.widgets.stageDistribution.stageColumn")}</th>
<th scope="col">{t("app.dashboard.widgets.stageDistribution.projectCountColumn")}</th>
</tr>
</thead>
<tbody>
{resolvedPoints.map((point) => (
<tr key={point.id}>
<th scope="row">{point.label}</th>
<td>{formatSeriesValue(point.value, widget.chart?.valueFormat ?? "count", language)}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
) : (
<span className={mutedText}>{t("app.dashboard.widgets.stageDistribution.empty")}</span>
)}
</Card>
);
}
if (widget.kind === "hero") {
return (
<Card className="h-full" data-ui-id={`ui.dashboard.widget.${widget.key}`}>
<span className={sectionHeading}>{t(widget.titleKey)}</span>
<span className={mutedText}>{t(widget.descriptionKey)}</span>
{widget.metrics[0] ? (
<span className={mutedText}>
{t(widget.metrics[0].labelKey)}: {formatDateTime(widget.metrics[0].value, language)}
</span>
) : null}
</Card>
);
}
if (widget.metrics.length === 1 && widget.items.length === 0) {
const card = (
<StatsCard
trend="neutral"
label={t(widget.titleKey)}
value={widget.metrics[0].value}
comparisonText={t(widget.metrics[0].labelKey)}
icon={domainIcons[widget.domain]}
className="h-full"
data-ui-id={`ui.dashboard.widget.${widget.key}`}
/>
);
return widget.href ? (
<AppLink href={widget.href} className="block h-full w-full" data-ui-id={`ui.dashboard.widget.${widget.key}.link`}>
{card}
</AppLink>
) : (
card
);
}
return (
<Card className="h-full" data-ui-id={`ui.dashboard.widget.${widget.key}`}>
<div className="flex w-full items-center justify-between gap-2">
<span className={sectionHeading}>{t(widget.titleKey)}</span>
<SubframeIcon domain={widget.domain} />
</div>
<span className={mutedText}>{t(widget.descriptionKey)}</span>
{widget.metrics.length > 0 ? (
<div className="grid w-full grid-cols-2 gap-4">
{widget.metrics.map((metric) => (
<div key={metric.labelKey} className="flex flex-col gap-1">
<span className={mutedText}>{t(metric.labelKey)}</span>
<span className={metricValue}>{metric.value}</span>
</div>
))}
</div>
) : null}
{widget.kind === "list" ? (
widget.items.length > 0 ? (
<div className="flex w-full flex-col gap-1">
{widget.items.map((item) => (
<DashboardWidgetItemRow key={item.id} item={item} />
))}
</div>
) : (
<span className={mutedText}>{t("app.dashboard.widgets.empty")}</span>
)
) : null}
</Card>
);
}
function dashboardWidgetGridClass(widget: DashboardWidgetVM): string {
const widthClass =
widget.size.w <= 3
? "lg:col-span-3"
: widget.size.w <= 4
? "lg:col-span-4"
: widget.size.w <= 6
? "lg:col-span-6"
: widget.size.w <= 8
? "lg:col-span-8"
: "lg:col-span-12";
const startClass =
widget.position.x === 0
? "lg:col-start-1"
: widget.position.x === 3
? "lg:col-start-4"
: widget.position.x === 4
? "lg:col-start-5"
: widget.position.x === 6
? "lg:col-start-7"
: widget.position.x === 8
? "lg:col-start-9"
: "";
return `min-w-0 ${widthClass} ${startClass}`;
}
function SubframeIcon({ domain }: { domain: DashboardWidgetDomain }) {
return <span className="text-icon-neutral-tertiary">{domainIcons[domain]}</span>;
}
function DashboardWidgetItemRow({ item }: { item: DashboardWidgetItemVM }) {
const { t, i18n } = useTranslation();
const label = item.labelKey ? t(item.labelKey) : item.label;
const tooltip = item.tooltip ?? label;
const meta = item.metaDateIso ? formatDateTime(item.metaDateIso, i18n.language) : item.meta;
return (
<div className="flex w-full min-w-0 items-center justify-between gap-3 overflow-hidden">
{item.href ? (
<AppLink href={item.href} title={tooltip} className="text-body-default-medium-0 font-body-default-medium-0 text-brand-brand-text-default min-w-0 truncate hover:underline">
{label}
</AppLink>
) : (
<span className={`${mutedText} min-w-0 truncate`} title={tooltip}>
{label}
</span>
)}
{meta ? <span className={`${mutedText} max-w-[50%] shrink-0 truncate whitespace-nowrap`}>{meta}</span> : null}
</div>
);
}
export default DashboardPage;
@@ -0,0 +1,62 @@
import { Bar, BarChart, CartesianGrid, Cell, LabelList, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { useLocaleFormatters } from "~/locale/format";
export type DashboardStageDistributionChartProps = {
points: readonly { id: string; label: string; value: number; color: string }[];
/** Currency buckets (receivables) print as money; counts stay plain numbers. */
valueFormat?: "currency" | "count";
};
/** Kept in sync with AXIS_WIDTH: a longer label would wrap onto a second line. */
function shortenLabel(value: string): string {
return value.length > 30 ? `${value.slice(0, 29)}…` : value;
}
/** Wide enough for "<Pipeline> · <Phase>" on a single line. */
const AXIS_WIDTH = 240;
/** Row height per bar — leaves visible air between the category labels. */
const ROW_HEIGHT = 52;
/**
* Lazily loaded visual enhancement for the dashboard. The parent card owns the
* accessible summary and data table, so this canvas/SVG representation is
* intentionally hidden from assistive technology.
*/
export default function DashboardStageDistributionChart({ points, valueFormat = "count" }: DashboardStageDistributionChartProps) {
const formatters = useLocaleFormatters();
const height = Math.max(240, Math.min(640, points.length * ROW_HEIGHT));
const formatValue = (value: number) =>
valueFormat === "currency"
? formatters.currency(value, "EUR", { maximumFractionDigits: 0 })
: formatters.number(value, { maximumFractionDigits: 0 });
return (
<div className="w-full" style={{ height }} aria-hidden="true" data-ui-id="ui.dashboard.widget.projects.stageDistribution.chart">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={[...points]} layout="vertical" margin={{ top: 8, right: 32, bottom: 8, left: 4 }}>
<CartesianGrid horizontal={false} strokeDasharray="3 3" />
<XAxis type="number" allowDecimals={false} tickLine={false} axisLine={false} />
<YAxis
type="category"
dataKey="label"
width={AXIS_WIDTH}
tickLine={false}
axisLine={false}
tickFormatter={shortenLabel}
/>
<Tooltip
cursor={{ fill: "rgba(107, 114, 128, 0.08)" }}
formatter={(value) => formatValue(Number(value))}
/>
<Bar dataKey="value" radius={[0, 6, 6, 0]} maxBarSize={24}>
{points.map((point) => (
<Cell key={point.id} fill={point.color} />
))}
<LabelList dataKey="value" position="right" className="fill-text-neutral-secondary" formatter={(value: number) => formatValue(Number(value))} />
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
);
}
@@ -0,0 +1,12 @@
import { describe, expect, it } from "vitest";
import { formatMonthLabel } from "./dashboardFormatters";
describe("formatMonthLabel", () => {
it("formats an ISO month without loading the chart module", () => {
expect(formatMonthLabel("2026-07", "de-DE")).toBe("Juli 26");
});
it("keeps malformed input visible", () => {
expect(formatMonthLabel("not-a-month", "de-DE")).toBe("not-a-month");
});
});
@@ -0,0 +1,6 @@
/** `2026-07` -> "Jul 26" in the viewer's locale; falls back to the raw id. */
export function formatMonthLabel(isoMonth: string, locale: string): string {
const [year, month] = isoMonth.split("-").map(Number);
if (!year || !month) return isoMonth;
return new Intl.DateTimeFormat(locale, { month: "short", year: "2-digit" }).format(new Date(year, month - 1, 1));
}
@@ -0,0 +1,48 @@
// R-P11b — client-side consumer of the dashboard SSE snapshot route
// (app.$tenant/dashboard.stream). The route owns this hook and feeds the
// resulting snapshot into DashboardPage as a prop. The loader already supplies a
// fresh snapshot, so the stream opens after a short warm-up instead of
// duplicating the expensive snapshot query in the page-load critical path.
//
// The stream is always on: the dashboard shows the current state of the
// workspace, and letting a member switch that off only ever produced staler
// numbers with no way to tell them apart from fresh ones.
import { useEffect, useState } from "react";
import type { DashboardPageData } from "@hivegrid/view-models";
const DASHBOARD_STREAM_WARMUP_MS = 15_000;
export function useDashboardStream({ streamUrl, initialGeneratedAt }: { streamUrl: string; initialGeneratedAt: string }) {
const [snapshot, setSnapshot] = useState<DashboardPageData | null>(null);
// A fresh loader snapshot supersedes whatever the stream delivered before.
useEffect(() => {
setSnapshot(null);
}, [initialGeneratedAt, streamUrl]);
useEffect(() => {
if (typeof EventSource === "undefined") {
return;
}
let source: EventSource | null = null;
const timer = window.setTimeout(() => {
source = new EventSource(streamUrl);
source.addEventListener("dashboard.snapshot", onSnapshot as EventListener);
}, DASHBOARD_STREAM_WARMUP_MS);
function onSnapshot(event: MessageEvent) {
try {
setSnapshot(JSON.parse(event.data) as DashboardPageData);
} catch {
// Malformed payloads are ignored; the loader data stays visible.
}
}
return () => {
window.clearTimeout(timer);
source?.removeEventListener("dashboard.snapshot", onSnapshot as EventListener);
source?.close();
};
}, [streamUrl]);
return { snapshot };
}