Spaces:
Running

loopable / web /src /viz /kit /Kpi.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
b2aa446 verified
Raw History Blame Contribute Delete
4.75 kB
import type { ReactNode } from "react";
import "../../styles/sdlc81/dashboard-kit.css";
import "../../styles/sdlc82/kpi-trend.css";
/** A source-checked measure. Numeric strings are refused, except ISO date measures. */
export interface KpiProps {
label: string;
value: number | string | null;
unit?: string;
validated?: boolean;
reason?: string | null;
noPrior?: boolean;
change?: { previous?: number | null; absolute?: number | null; percent?: number | null; reason?: string | null };
period?: string;
onClick?: () => void;
formattedValue?: string;
formattedChange?: string;
/** Optional number series drawn as a sparkline under the value and the change. */
trend?: ReadonlyArray<number | null>;
}
export function finite(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value);
}
export function formatMeasure(value: number | string | null, unit = "", format?: string): string {
if (unit === "date" && typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)
&& Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value) {
return new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeZone: "UTC" }).format(new Date(value));
}
if (!finite(value)) return "Unavailable";
if (/^[A-Z]{3}$/.test(unit)) return new Intl.NumberFormat(undefined, { style: "currency", currency: unit }).format(value);
const digits = format === ",d" || ["units", "rank", "count"].includes(unit) ? 0 : 2;
return new Intl.NumberFormat(undefined, { maximumFractionDigits: digits }).format(value)
+ (["%", "percent"].includes(unit) ? "%" : "");
}
/** Comparison text uses checked evidence and retains no-prior reasons. */
export function formatComparison(change?: KpiProps["change"], noPrior = false, formattedChange?: string) {
const percent = !noPrior && finite(change?.percent)
&& [change?.previous, change?.absolute].every(v => v == null || finite(v)) ? change.percent : null;
return {
sign: percent === null || percent === 0 ? "neutral" : percent > 0 ? "up" : "down",
text: percent === null ? change?.reason || "No comparison data"
: formattedChange ?? `${percent > 0 ? "+" : ""}${formatMeasure(percent, "%")}`,
};
}
export function Kpi({ label, value, unit, validated = false, reason, change, noPrior, period,
onClick, formattedValue, formattedChange, trend }: KpiProps) {
const usable = validated === true && formatMeasure(value, unit) !== "Unavailable"
&& (!change || [change.previous, change.absolute, change.percent].every(v => v == null || finite(v)));
const comparison = formatComparison(usable ? change : undefined, noPrior, formattedChange);
const valueText = formattedValue ?? formatMeasure(value, unit);
const content = <>
<span className="lp-kpi-label">{label}</span>
{usable ? <>
<span className="lp-kpi-value" title={valueText}>{valueText}</span>
<span className="lp-kpi-change" data-sign={comparison.sign}>{comparison.text}</span>
{trend && <KpiTrend points={trend} />}
{reason && <span className="lp-figure-reason" role="status">{reason}</span>}
</> : <span className="lp-figure-reason" role="status">{reason || "This figure could not be validated"}</span>}
{period && <span className="lp-kpi-period">{period}</span>}
</>;
return onClick && usable ? <button type="button" className="lp-kpi" onClick={onClick}>{content}</button>
: <div className="lp-kpi">{content}</div>;
}
/** Supply Kpi children to keep one measure anatomy across Apps. */
export interface KpiStripProps { children: ReactNode; label?: string }
export function KpiStrip({ children, label = "Key figures" }: KpiStripProps) {
return <div className="lp-kpi-strip" role="group" aria-label={label}>{children}</div>;
}
/** A sparkline: one path over finite points, a null breaks the line, no axes and no labels. */
export interface KpiTrendProps { points: ReadonlyArray<number | null> }
export function KpiTrend({ points }: KpiTrendProps) {
if (!Array.isArray(points) || !points.every(v => v === null || finite(v))) return null;
const values = points.filter(finite);
if (values.length < 2) return null;
const lo = Math.min(...values), span = Math.max(...values) - lo || 1, step = 100 / (points.length - 1);
let d = "", open = false;
points.forEach((v, i) => {
if (!finite(v)) { open = false; return; }
d += `${open ? "L" : "M"}${(i * step).toFixed(2)} ${(30 - ((v - lo) / span) * 28).toFixed(2)} `;
open = true;
});
return <svg className="lp-kpi-trend" viewBox="0 0 100 32" preserveAspectRatio="none" aria-hidden="true" focusable="false">
<path d={d.trim()} data-points={values.length} vectorEffect="non-scaling-stroke" />
</svg>;
}