Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 88 additions & 14 deletions apps/geolibre-desktop/src/components/panels/DashboardPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { DashboardWidget } from "@geolibre/core";
import type { DashboardWidget, IndicatorAggregation } from "@geolibre/core";
import { MAX_DASHBOARD_COLUMNS, MIN_DASHBOARD_COLUMNS, useAppStore } from "@geolibre/core";
import { Button, Select } from "@geolibre/ui";
import {
Expand Down Expand Up @@ -27,6 +27,49 @@ const DEFAULT_DASHBOARD_HEIGHT = 360;
// fills and resizes with the panel height (issue #728).
const MIN_DASHBOARD_ROW_HEIGHT = 200;

/** Compute the indicator value from layer data and an aggregation. Returns
* null when there is no numeric data to aggregate. Count works on any layer. */
function computeIndicator(
rows: Record<string, unknown>[],
field: string | undefined,
aggregation: IndicatorAggregation,
): number | null {
if (aggregation === "count") {
return rows.length;
}
if (!field) return null;
const values = rows
.map((r) => r[field])
.filter((v): v is number => typeof v === "number" && !Number.isNaN(v));
if (values.length === 0) return null;
switch (aggregation) {
case "sum":
return values.reduce((a, b) => a + b, 0);
case "mean":
return values.reduce((a, b) => a + b, 0) / values.length;
case "min":
return Math.min(...values);
case "max":
return Math.max(...values);
case "median": {
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
default:
return null;
}
}

/** Format a number for display in the indicator tile. Large numbers get
* locale-aware grouping; small numbers keep up to 2 decimal places. */
function formatIndicatorValue(value: number): string {
if (Number.isInteger(value)) {
return value.toLocaleString();
}
return value.toLocaleString(undefined, { maximumFractionDigits: 2 });
}

/** Turn a stored widget into the render-side {@link ChartSpec}. */
function widgetToSpec(widget: DashboardWidget): ChartSpec {
return {
Expand Down Expand Up @@ -351,6 +394,11 @@ function WidgetCard({
return `${t("dashboard.chartType.box")} · ${widget.field ?? ""}`;
case "pie":
return `${t("dashboard.chartType.pie")} · ${widget.category ?? ""}`;
case "indicator": {
const agg = widget.indicatorAggregation ?? "count";
const aggLabel = t(`dashboard.indicatorAggregation.${agg}`);
return widget.field ? `${aggLabel} · ${widget.field}` : aggLabel;
}
}
};
const title = widget.title?.trim() || defaultWidgetTitle();
Expand Down Expand Up @@ -412,19 +460,45 @@ function WidgetCard({
</div>
</div>

{/* [&>svg] targets ChartView's chart SVG, which is a direct DOM child
(React Fragments emit no nodes): it flexes to fill, min-h-0 lets it
shrink past its intrinsic aspect-ratio height, and preserveAspectRatio
letterboxes it. Update this if a chart ever wraps its SVG (issue #728). */}
<div className="flex min-h-0 flex-1 flex-col [&>svg]:min-h-0 [&>svg]:flex-1">
{data.hasData ? (
<ChartView result={result} color={widget.color} />
) : (
<p className="flex flex-1 items-center justify-center py-4 text-center text-xs text-muted-foreground">
{t("dashboard.noData")}
</p>
)}
</div>
{/* Indicator widgets render a KPI tile instead of a chart. */}
{widget.type === "indicator" ? (
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1">
{(() => {
const agg = widget.indicatorAggregation ?? "count";
const value = computeIndicator(data.rows, widget.field, agg);
if (value === null) {
return (
<p className="text-center text-xs text-muted-foreground">{t("dashboard.noData")}</p>
);
}
const formatted = formatIndicatorValue(value);
const colorStyle = widget.color ? { color: widget.color } : undefined;
return (
<>
<span className="text-3xl font-bold leading-none tracking-tight" style={colorStyle}>
{widget.prefix ?? ""}
{formatted}
{widget.suffix ?? ""}
</span>
<span className="text-xs text-muted-foreground">
{t(`dashboard.indicatorAggregation.${agg}`)}
{widget.field ? ` · ${widget.field}` : ""}
</span>
</>
);
})()}
</div>
) : (
<div className="flex min-h-0 flex-1 flex-col [&>svg]:min-h-0 [&>svg]:flex-1">
{data.hasData ? (
<ChartView result={result} color={widget.color} />
) : (
<p className="flex flex-1 items-center justify-center py-4 text-center text-xs text-muted-foreground">
{t("dashboard.noData")}
</p>
)}
</div>
)}
</div>
);
}
106 changes: 95 additions & 11 deletions apps/geolibre-desktop/src/components/panels/WidgetEditorDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { DashboardWidget } from "@geolibre/core";
import type { DashboardWidget, DashboardWidgetType, IndicatorAggregation } from "@geolibre/core";
import {
Button,
ColorField,
Expand All @@ -20,7 +20,6 @@ import {
MIN_HISTOGRAM_BINS,
numericColumns,
type BarAggregation,
type ChartType,
} from "../../lib/attribute-charts";
import { useLayerChartData } from "../../hooks/useLayerChartData";

Expand Down Expand Up @@ -56,7 +55,7 @@ export function WidgetEditorDialog({
}: WidgetEditorDialogProps) {
const { t } = useTranslation();
const [layerId, setLayerId] = useState("");
const [type, setType] = useState<ChartType>("histogram");
const [type, setType] = useState<DashboardWidgetType>("histogram");
const [field, setField] = useState("");
const [xField, setXField] = useState("");
const [yField, setYField] = useState("");
Expand All @@ -65,6 +64,10 @@ export function WidgetEditorDialog({
const [aggregation, setAggregation] = useState<BarAggregation>("count");
const [valueField, setValueField] = useState("");
const [title, setTitle] = useState("");
// "indicator" widget fields (issue #1381).
const [indicatorAggregation, setIndicatorAggregation] = useState<IndicatorAggregation>("count");
const [prefix, setPrefix] = useState("");
const [suffix, setSuffix] = useState("");
// "" means no custom color: fall back to the theme primary / palette.
const [color, setColor] = useState("");

Expand All @@ -82,6 +85,9 @@ export function WidgetEditorDialog({
setValueField(widget?.valueField ?? "");
setTitle(widget?.title ?? "");
setColor(widget?.color ?? "");
setIndicatorAggregation(widget?.indicatorAggregation ?? "count");
setPrefix(widget?.prefix ?? "");
setSuffix(widget?.suffix ?? "");
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, widget]);

Expand All @@ -97,14 +103,16 @@ export function WidgetEditorDialog({
// sum/average rather than count); scatter needs two numeric fields so x and y
// aren't forced to the same column; the rest need one numeric field.
const isCategorical = type === "bar" || type === "pie";
const isIndicator = type === "indicator";
const canSave =
layerId !== "" &&
(isCategorical
? hasCategory && (aggregation === "count" || hasNumeric)
: type === "scatter"
? numericCols.length >= 2
: hasNumeric);

(isIndicator
? indicatorAggregation === "count" || hasNumeric
: isCategorical
? hasCategory && (aggregation === "count" || hasNumeric)
: type === "scatter"
? numericCols.length >= 2
: hasNumeric);
const save = () => {
if (!canSave) return;
const next: DashboardWidget = {
Expand Down Expand Up @@ -134,6 +142,15 @@ export function WidgetEditorDialog({
next.aggregation = agg;
if (agg !== "count") next.valueField = pick(valueField, numericCols);
}
if (type === "indicator") {
next.indicatorAggregation = indicatorAggregation;
if (indicatorAggregation !== "count") {
next.field = pick(field, numericCols);
}
// Preserve whitespace: prefix/suffix may have intentional spaces (" ha").
if (prefix) next.prefix = prefix;
if (suffix) next.suffix = suffix;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
onSave(next);
onOpenChange(false);
};
Expand Down Expand Up @@ -169,7 +186,7 @@ export function WidgetEditorDialog({
</Select>
</div>

{!hasChartable ? (
{!hasChartable && type !== "indicator" ? (
<p className="text-sm text-muted-foreground">{t("dashboard.editor.noFields")}</p>
) : (
Comment on lines +189 to 191

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Keep the widget type selector available without chartable fields.

For a new widget, type defaults to "histogram", so this branch hides the entire selector before the user can choose the enabled "indicator" option. Consequently, count indicators still cannot be created on layers with no numeric or categorical columns. Render the type selector regardless, disable only field-dependent options, and show the “no fields” message separately.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/geolibre-desktop/src/components/panels/WidgetEditorDialog.tsx` around
lines 189 - 191, Update the WidgetEditorDialog rendering around the
hasChartable/type condition so the widget type selector remains visible when no
chartable fields exist. Disable only options that require fields, keep the
indicator option selectable, and render the noFields message separately without
replacing the selector.

<div className="flex flex-wrap items-end gap-3">
Expand All @@ -180,7 +197,7 @@ export function WidgetEditorDialog({
className="w-36"
value={type}
onChange={(event) => {
const nextType = event.target.value as ChartType;
const nextType = event.target.value as DashboardWidgetType;
setType(nextType);
// Pie has no "average"; drop a carried-over mean so the
// select doesn't show a stale value with no matching option.
Expand All @@ -207,6 +224,7 @@ export function WidgetEditorDialog({
<option value="pie" disabled={!hasCategory}>
{t("dashboard.chartType.pie")}
</option>
<option value="indicator">{t("dashboard.chartType.indicator")}</option>
Comment thread
coderabbitai[bot] marked this conversation as resolved.
</Select>
</div>

Expand Down Expand Up @@ -312,6 +330,72 @@ export function WidgetEditorDialog({
)}
</>
)}

{type === "indicator" && (
<>
<div className="grid gap-1.5">
<Label htmlFor="widget-indicator-agg">
{t("dashboard.editor.aggregate")}
</Label>
<Select
id="widget-indicator-agg"
className="w-32"
value={indicatorAggregation}
onChange={(event) =>
setIndicatorAggregation(event.target.value as IndicatorAggregation)
}
>
<option value="count">{t("dashboard.indicatorAggregation.count")}</option>
<option value="sum" disabled={!hasNumeric}>
{t("dashboard.indicatorAggregation.sum")}
</option>
<option value="mean" disabled={!hasNumeric}>
{t("dashboard.indicatorAggregation.mean")}
</option>
<option value="min" disabled={!hasNumeric}>
{t("dashboard.indicatorAggregation.min")}
</option>
<option value="max" disabled={!hasNumeric}>
{t("dashboard.indicatorAggregation.max")}
</option>
<option value="median" disabled={!hasNumeric}>
{t("dashboard.indicatorAggregation.median")}
</option>
</Select>
</div>
{indicatorAggregation !== "count" && (
<FieldSelect
id="widget-indicator-field"
label={t("dashboard.editor.field")}
value={pick(field, numericCols)}
options={numericCols}
onChange={setField}
/>
)}
<div className="flex gap-2">
<div className="grid gap-1.5">
<Label htmlFor="widget-prefix">{t("dashboard.editor.prefix")}</Label>
<Input
id="widget-prefix"
className="w-20"
value={prefix}
placeholder="€"
onChange={(event) => setPrefix(event.target.value)}
/>
</div>
<div className="grid gap-1.5">
<Label htmlFor="widget-suffix">{t("dashboard.editor.suffix")}</Label>
<Input
id="widget-suffix"
className="w-20"
value={suffix}
placeholder=" ha"
onChange={(event) => setSuffix(event.target.value)}
/>
</div>
</div>
</>
)}
</div>
)}

Expand Down
13 changes: 12 additions & 1 deletion apps/geolibre-desktop/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2675,13 +2675,22 @@
"bar": "Bar",
"line": "Line",
"box": "Box plot",
"pie": "Pie"
"pie": "Pie",
"indicator": "Indicator"
},
"aggregate": {
"count": "Count",
"sum": "Sum",
"mean": "Average"
},
"indicatorAggregation": {
"count": "Count",
"sum": "Sum",
"mean": "Average",
"min": "Minimum",
"max": "Maximum",
"median": "Median"
},
"chart": {
"emptyNumeric": "No numeric values to plot.",
"emptyScatter": "No rows have both fields set to a number.",
Expand All @@ -2707,6 +2716,8 @@
"category": "Category",
"aggregate": "Aggregate",
"value": "Value",
"prefix": "Prefix",
"suffix": "Suffix",
"titleLabel": "Title",
"titlePlaceholder": "Optional title",
"color": "Color",
Expand Down
13 changes: 12 additions & 1 deletion apps/geolibre-desktop/src/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -2669,13 +2669,22 @@
"bar": "Barras",
"line": "Líneas",
"box": "Diagrama de caja",
"pie": "Circular"
"pie": "Circular",
"indicator": "Indicador"
},
"aggregate": {
"count": "Recuento",
"sum": "Suma",
"mean": "Promedio"
},
"indicatorAggregation": {
"count": "Recuento",
"sum": "Suma",
"mean": "Promedio",
"min": "Mínimo",
"max": "Máximo",
"median": "Mediana"
},
"chart": {
"emptyNumeric": "No hay valores numéricos que graficar.",
"emptyScatter": "Ninguna fila tiene ambos campos establecidos como número.",
Expand All @@ -2701,6 +2710,8 @@
"category": "Categoría",
"aggregate": "Agregado",
"value": "Valor",
"prefix": "Prefijo",
"suffix": "Sufijo",
"titleLabel": "Título",
"titlePlaceholder": "Título opcional",
"color": "Color",
Expand Down
Loading
Loading