forked from opengeos/GeoLibre
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDashboardPanel.tsx
More file actions
594 lines (568 loc) · 21.4 KB
/
Copy pathDashboardPanel.tsx
File metadata and controls
594 lines (568 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
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 {
ChevronLeft,
ChevronRight,
LayoutDashboard,
PanelBottomClose,
PanelBottomOpen,
Pencil,
Plus,
Trash2,
X,
} from "lucide-react";
import { useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from "react";
import { useTranslation } from "react-i18next";
import { numericValues, type ChartRow, type ChartType } from "../../lib/attribute-charts";
import { isChartableLayer, useLayerChartData } from "../../hooks/useLayerChartData";
import { ChartView, computeChart, type ChartSpec } from "./charts/chart-view";
import { WidgetEditorDialog } from "./WidgetEditorDialog";
import { PANEL_RESIZE_END_EVENT, PANEL_RESIZE_START_EVENT } from "../../lib/panel-resize";
const MIN_DASHBOARD_HEIGHT = 160;
const MAX_DASHBOARD_HEIGHT = 720;
const DEFAULT_DASHBOARD_HEIGHT = 360;
// Per-row floor once widgets wrap onto multiple rows; below it the panel
// scrolls instead of crushing the charts. A single row has no floor, so it
// 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: ChartRow[],
field: string | undefined,
aggregation: IndicatorAggregation,
): number | null {
if (aggregation === "count") {
return rows.length;
}
if (!field) return null;
// Reuse the shared coercion so numeric strings count, as they do in the charts.
const values = numericValues(rows, field);
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}. An indicator is
* a KPI tile rather than a chart, so the caller passes the narrowed chart type
* and skips this for `"indicator"` widgets. */
function widgetToSpec(widget: DashboardWidget, type: ChartType): ChartSpec {
return {
type,
field: widget.field,
xField: widget.xField,
yField: widget.yField,
bins: widget.bins,
category: widget.category,
aggregation: widget.aggregation,
valueField: widget.valueField,
};
}
/**
* The Dashboard panel: a bottom-docked, resizable strip of chart widgets, each
* bound to a layer and field(s), in the spirit of CARTO Builder / Foursquare
* Studio (issue #401). Widgets are stored in the project, so a dashboard
* reopens intact. Rendered only while open. Charts are read-only summaries
* here; cross-filtering the map is intentionally out of scope for now.
*/
export function DashboardPanel() {
const { t } = useTranslation();
const widgets = useAppStore((s) => s.widgets);
const layers = useAppStore((s) => s.layers);
const columns = useAppStore((s) => s.dashboardColumns);
const setDashboardOpen = useAppStore((s) => s.setDashboardOpen);
const setDashboardColumns = useAppStore((s) => s.setDashboardColumns);
const addWidget = useAppStore((s) => s.addWidget);
const updateWidget = useAppStore((s) => s.updateWidget);
const removeWidget = useAppStore((s) => s.removeWidget);
const moveWidget = useAppStore((s) => s.moveWidget);
// Choices for the column-count picker, derived from the supported range.
const columnOptions = useMemo(() => {
const values: number[] = [];
for (let n = MIN_DASHBOARD_COLUMNS; n <= MAX_DASHBOARD_COLUMNS; n += 1) {
values.push(n);
}
return values;
}, []);
const sectionRef = useRef<HTMLElement>(null);
const resizeCleanupRef = useRef<(() => void) | null>(null);
const [height, setHeight] = useState(DEFAULT_DASHBOARD_HEIGHT);
// Collapse the panel to just its header bar for a full map view, without
// losing the last height (issue #459). The height is kept in state so an
// expand restores the panel to exactly the size the user last dragged it to.
const [isCollapsed, setIsCollapsed] = useState(false);
const [editorOpen, setEditorOpen] = useState(false);
const [editing, setEditing] = useState<DashboardWidget | null>(null);
// Layers that expose chartable attributes, for the editor's layer picker.
const chartableLayers = useMemo(
() =>
layers
.filter((layer) => isChartableLayer(layer))
.map((layer) => ({ id: layer.id, name: layer.name })),
[layers],
);
const startResize = (event: ReactMouseEvent<HTMLDivElement>) => {
event.preventDefault();
event.stopPropagation();
const startY = event.clientY;
const startHeight = height;
let nextHeight = startHeight;
let frame: number | null = null;
const prevCursor = document.body.style.cursor;
const prevSelect = document.body.style.userSelect;
document.body.style.cursor = "row-resize";
document.body.style.userSelect = "none";
window.dispatchEvent(new Event(PANEL_RESIZE_START_EVENT));
const onMove = (moveEvent: MouseEvent) => {
const available = Math.max(MIN_DASHBOARD_HEIGHT, window.innerHeight - 180);
const maxHeight = Math.min(MAX_DASHBOARD_HEIGHT, available);
nextHeight = Math.min(
maxHeight,
Math.max(MIN_DASHBOARD_HEIGHT, startHeight + startY - moveEvent.clientY),
);
if (frame !== null) return;
frame = window.requestAnimationFrame(() => {
frame = null;
if (sectionRef.current) {
sectionRef.current.style.height = `${nextHeight}px`;
}
});
};
const cleanup = () => {
window.removeEventListener("mousemove", onMove);
window.removeEventListener("mouseup", onUp);
if (frame !== null) window.cancelAnimationFrame(frame);
window.dispatchEvent(new Event(PANEL_RESIZE_END_EVENT));
document.body.style.cursor = prevCursor;
document.body.style.userSelect = prevSelect;
};
const onUp = () => {
cleanup();
resizeCleanupRef.current = null;
setHeight(nextHeight);
};
window.addEventListener("mousemove", onMove);
window.addEventListener("mouseup", onUp);
resizeCleanupRef.current = cleanup;
};
// Tear down an in-flight drag if the panel unmounts mid-resize.
useEffect(() => () => resizeCleanupRef.current?.(), []);
const openAdd = () => {
setEditing(null);
setEditorOpen(true);
};
const openEdit = (widget: DashboardWidget) => {
setEditing(widget);
setEditorOpen(true);
};
const handleSave = (widget: DashboardWidget) => {
if (widgets.some((w) => w.id === widget.id)) {
const { id: _id, ...patch } = widget;
updateWidget(widget.id, patch);
} else {
addWidget(widget);
}
};
// When widgets wrap onto multiple rows, floor the grid height (rows plus the
// gap-3 gaps between them) so it scrolls rather than crushing the charts; a
// single row stays unbounded and fills the panel (issue #728). calc() lets
// the browser resolve 0.75rem so the gap tracks the root font size.
const rowCount = Math.max(1, Math.ceil(widgets.length / Math.max(1, columns)));
const gridMinHeight =
rowCount > 1
? // 0.75rem is gap-3; keep in sync if the grid's gap class changes.
`calc(${rowCount} * ${MIN_DASHBOARD_ROW_HEIGHT}px + ${rowCount - 1} * 0.75rem)`
: undefined;
return (
<section
ref={sectionRef}
style={isCollapsed ? undefined : { height }}
className="relative flex shrink-0 flex-col border-t bg-card"
>
{!isCollapsed ? (
<div
role="separator"
aria-orientation="horizontal"
aria-label={t("dashboard.resize")}
aria-valuenow={Math.round(height)}
aria-valuemin={MIN_DASHBOARD_HEIGHT}
aria-valuemax={MAX_DASHBOARD_HEIGHT}
tabIndex={0}
className="absolute -top-1 left-0 right-0 z-20 h-2 cursor-row-resize select-none border-t border-transparent hover:border-primary focus-visible:border-primary focus-visible:outline-none"
onMouseDown={startResize}
onKeyDown={(event) => {
// Arrow keys resize for keyboard-only users (Shift = larger step).
const step = event.shiftKey ? 24 : 8;
if (event.key === "ArrowUp") {
setHeight((h) => Math.min(MAX_DASHBOARD_HEIGHT, h + step));
} else if (event.key === "ArrowDown") {
setHeight((h) => Math.max(MIN_DASHBOARD_HEIGHT, h - step));
} else {
return;
}
event.preventDefault();
}}
/>
) : null}
<div className="flex items-center gap-2 border-b px-3 py-1.5">
<LayoutDashboard className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-semibold">{t("dashboard.title")}</span>
<span className="text-xs text-muted-foreground">
{t("dashboard.widgetCount", { count: widgets.length })}
</span>
<div className="ms-auto flex items-center gap-2">
{!isCollapsed && widgets.length > 0 ? (
<label className="flex items-center gap-1.5 text-xs text-muted-foreground">
<span className="hidden sm:inline">{t("dashboard.columns")}</span>
<Select
aria-label={t("dashboard.columns")}
className="h-8 w-16"
value={String(columns)}
onChange={(event) => setDashboardColumns(Number(event.target.value))}
>
{columnOptions.map((n) => (
<option key={n} value={n}>
{n}
</option>
))}
</Select>
</label>
) : null}
{!isCollapsed ? (
<Button
variant="outline"
size="sm"
className="h-8 px-2"
onClick={openAdd}
disabled={chartableLayers.length === 0}
title={
chartableLayers.length === 0
? t("dashboard.noLayersHint")
: t("dashboard.addWidget")
}
>
<Plus className="h-3.5 w-3.5" />
<span className="hidden sm:inline">{t("dashboard.addWidget")}</span>
</Button>
) : null}
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
aria-label={isCollapsed ? t("dashboard.expand") : t("dashboard.collapse")}
title={isCollapsed ? t("dashboard.expand") : t("dashboard.collapse")}
onClick={() => setIsCollapsed((c) => !c)}
>
{isCollapsed ? (
<PanelBottomOpen className="h-4 w-4" />
) : (
<PanelBottomClose className="h-4 w-4" />
)}
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
aria-label={t("dashboard.close")}
title={t("dashboard.close")}
onClick={() => setDashboardOpen(false)}
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{!isCollapsed ? (
<div className="min-h-0 flex-1 overflow-auto p-3">
{widgets.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-1 text-center">
<p className="text-sm text-muted-foreground">
{chartableLayers.length === 0 ? t("dashboard.emptyNoLayers") : t("dashboard.empty")}
</p>
</div>
) : (
<div
className="grid h-full gap-3"
style={{
gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
// Equal-height rows that shrink with the panel (issue #728).
gridAutoRows: "minmax(0, 1fr)",
minHeight: gridMinHeight,
}}
>
{widgets.map((widget, index) => (
<WidgetCard
key={widget.id}
widget={widget}
index={index}
count={widgets.length}
onEdit={() => openEdit(widget)}
onRemove={() => removeWidget(widget.id)}
onMove={(toIndex) => moveWidget(widget.id, toIndex)}
/>
))}
</div>
)}
</div>
) : null}
<WidgetEditorDialog
open={editorOpen}
onOpenChange={setEditorOpen}
widget={editing}
layers={chartableLayers}
onSave={handleSave}
/>
</section>
);
}
function WidgetCard({
widget,
index,
count,
onEdit,
onRemove,
onMove,
}: {
widget: DashboardWidget;
index: number;
count: number;
onEdit: () => void;
onRemove: () => void;
onMove: (toIndex: number) => void;
}) {
const { t } = useTranslation();
const data = useLayerChartData(widget.layerId);
const result = useMemo(
() =>
widget.type === "indicator" || widget.type === "selector"
? null
: computeChart(data.rows, widgetToSpec(widget, widget.type)),
[data.rows, widget],
);
// A readable title from the widget's chart type and fields when untitled.
const defaultWidgetTitle = (): string => {
switch (widget.type) {
case "histogram":
return `${t("dashboard.chartType.histogram")} · ${widget.field ?? ""}`;
case "scatter":
return `${widget.yField ?? ""} / ${widget.xField ?? ""}`;
case "bar": {
const agg =
widget.aggregation === "sum"
? t("dashboard.aggregate.sum")
: widget.aggregation === "mean"
? t("dashboard.aggregate.mean")
: t("dashboard.aggregate.count");
return `${agg} · ${widget.category ?? ""}`;
}
case "line":
return `${t("dashboard.chartType.line")} · ${widget.field ?? ""}`;
case "box":
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;
}
case "selector":
return `${t("dashboard.chartType.selector")} · ${widget.category ?? ""}`;
}
};
const title = widget.title?.trim() || defaultWidgetTitle();
return (
<div className="flex min-h-0 flex-col gap-2 overflow-hidden rounded-md border bg-background p-3">
<div className="flex shrink-0 items-center gap-2">
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium" title={title}>
{title}
</div>
<div className="truncate text-xs text-muted-foreground" title={data.layerName}>
{data.hasData ? data.layerName : t("dashboard.layerMissing")}
</div>
</div>
<div className="flex shrink-0 items-center">
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
aria-label={t("dashboard.moveBack")}
title={t("dashboard.moveBack")}
disabled={index === 0}
onClick={() => onMove(index - 1)}
>
<ChevronLeft className="h-3.5 w-3.5 rtl:rotate-180" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
aria-label={t("dashboard.moveForward")}
title={t("dashboard.moveForward")}
disabled={index === count - 1}
onClick={() => onMove(index + 1)}
>
<ChevronRight className="h-3.5 w-3.5 rtl:rotate-180" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
aria-label={t("dashboard.editWidget")}
title={t("dashboard.editWidget")}
onClick={onEdit}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
aria-label={t("dashboard.removeWidget")}
title={t("dashboard.removeWidget")}
onClick={onRemove}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</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>
) : widget.type === "selector" ? (
<div className="flex min-h-0 flex-1 flex-col gap-1.5 overflow-auto">
{(() => {
if (!widget.category || !data.hasData) {
return (
<p className="text-center text-xs text-muted-foreground">{t("dashboard.noData")}</p>
);
}
// Extract distinct values from the category field, sorted.
const cat = widget.category!;
const values = Array.from(
new Set(
data.rows
.map((row) => String((row as unknown as Record<string, unknown>)[cat] ?? ""))
.filter((v) => v !== ""),
),
).sort((a, b) => a.localeCompare(b));
if (values.length === 0) {
return (
<p className="text-center text-xs text-muted-foreground">{t("dashboard.noData")}</p>
);
}
// Keyed on the selector config so switching field or single/multi
// mode remounts with an empty selection instead of carrying over
// values that no longer apply.
return (
<SelectorValues
key={`${cat}:${widget.multiple ?? false}`}
values={values}
multiple={widget.multiple ?? false}
/>
);
})()}
</div>
) : (
<div className="flex min-h-0 flex-1 flex-col [&>svg]:min-h-0 [&>svg]:flex-1">
{data.hasData && result ? (
<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>
);
}
/** Renders the selector widget body: a scrollable list of clickable value
* chips. In single mode clicking a value toggles it as the only selected value.
* In multi mode each chip toggles independently. Cross-filtering is not yet
* wired; this prepares the UI and selection state for it. */
function SelectorValues({ values, multiple }: { values: string[]; multiple: boolean }) {
const [selected, setSelected] = useState<Set<string>>(new Set());
const toggle = (value: string) => {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(value)) {
next.delete(value);
} else {
if (!multiple) next.clear();
next.add(value);
}
return next;
});
};
return (
<div className="flex flex-wrap gap-1.5">
{values.map((value) => {
const isSelected = selected.has(value);
return (
<button
key={value}
type="button"
aria-pressed={isSelected}
onClick={() => toggle(value)}
className={`rounded-full border px-2.5 py-0.5 text-xs transition-colors ${
isSelected
? "border-primary bg-primary text-primary-foreground"
: "border-border bg-background text-muted-foreground hover:border-primary/50"
}`}
>
{value}
</button>
);
})}
</div>
);
}