@nubitio/dashboard 0.7.4 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,8 +1,10 @@
1
- import { AppToolbar, Badge, EmptyState, StatCard } from "@nubitio/ui";
2
- import { useCallback, useEffect, useState } from "react";
3
- import { getCoreApiBaseUrl, getCoreCurrency, getCoreLocale } from "@nubitio/core";
4
- import { jsx, jsxs } from "react/jsx-runtime";
5
- import { Link } from "react-router-dom";
1
+ import { AppToolbar, Badge, DateRangePicker, EmptyState, IconButton, Popover, SegmentedControl, StatCard } from "@nubitio/ui";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { useCallback, useMemo, useState } from "react";
4
+ import { Link, useSearchParams } from "react-router-dom";
5
+ import { useQuery } from "@tanstack/react-query";
6
+ import { getCoreCurrency, getCoreLocale, useCoreHttpClient } from "@nubitio/core";
7
+ import { Area, AreaChart, CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
6
8
  //#region packages/dashboard/dashboard/defineDashboard.ts
7
9
  const dashboardCache = /* @__PURE__ */ new Map();
8
10
  function cacheKey(config) {
@@ -43,67 +45,270 @@ function defineDashboard(config) {
43
45
  return dashboard;
44
46
  }
45
47
  //#endregion
46
- //#region packages/dashboard/dashboard/useDashboardData.ts
47
- function resolveDataUrl(dataUrl) {
48
- if (/^https?:\/\//i.test(dataUrl)) return dataUrl;
49
- return `${getCoreApiBaseUrl().replace(/\/+$/, "")}${dataUrl.startsWith("/") ? dataUrl : `/${dataUrl}`}`;
50
- }
51
- const EMPTY = {
52
- data: {},
53
- loading: false,
54
- error: null
55
- };
56
- function useDashboardData(dataUrl, refreshInterval) {
57
- const [state, setState] = useState({
58
- ...EMPTY,
59
- loading: !!dataUrl
48
+ //#region packages/dashboard/dashboard/DashboardLayoutControls.tsx
49
+ function DashboardLayoutControls({ layout }) {
50
+ return /* @__PURE__ */ jsxs("div", {
51
+ className: "nb-dashboard-layout-controls",
52
+ children: [
53
+ layout.editMode && layout.hiddenWidgets.length > 0 && /* @__PURE__ */ jsx(Popover, {
54
+ ariaLabel: "Hidden widgets",
55
+ align: "end",
56
+ trigger: ({ toggle }) => /* @__PURE__ */ jsx(IconButton, {
57
+ icon: "ph ph-eye-slash",
58
+ label: `Hidden widgets (${layout.hiddenWidgets.length})`,
59
+ onClick: toggle
60
+ }),
61
+ panel: () => /* @__PURE__ */ jsx("ul", {
62
+ className: "nb-dashboard-layout-controls__hidden-list",
63
+ children: layout.hiddenWidgets.map(({ sectionId, widget }) => /* @__PURE__ */ jsxs("li", { children: [/* @__PURE__ */ jsx("span", { children: widget.title }), /* @__PURE__ */ jsx("button", {
64
+ type: "button",
65
+ className: "nb-dashboard-layout-controls__show-btn",
66
+ onClick: () => layout.showWidget(sectionId, widget.id),
67
+ children: "Show"
68
+ })] }, `${sectionId}-${widget.id}`))
69
+ })
70
+ }),
71
+ layout.editMode && /* @__PURE__ */ jsx(IconButton, {
72
+ icon: "ph ph-arrow-counter-clockwise",
73
+ label: "Reset layout",
74
+ onClick: layout.resetLayout
75
+ }),
76
+ /* @__PURE__ */ jsx(IconButton, {
77
+ icon: layout.editMode ? "ph ph-check" : "ph ph-sliders-horizontal",
78
+ label: layout.editMode ? "Done customizing" : "Customize dashboard",
79
+ onClick: () => layout.setEditMode(!layout.editMode)
80
+ })
81
+ ]
60
82
  });
61
- const refetch = useCallback(async () => {
62
- if (!dataUrl) {
63
- setState(EMPTY);
64
- return;
65
- }
66
- setState((prev) => ({
67
- ...prev,
68
- loading: true,
69
- error: null
70
- }));
71
- try {
72
- const response = await fetch(resolveDataUrl(dataUrl), { credentials: "include" });
73
- if (!response.ok) throw new Error(`Dashboard request failed (${response.status})`);
74
- setState({
75
- data: await response.json(),
76
- loading: false,
77
- error: null
78
- });
79
- } catch (error) {
80
- setState({
81
- data: {},
82
- loading: false,
83
- error: error instanceof Error ? error.message : "Failed to load dashboard"
84
- });
85
- }
86
- }, [dataUrl]);
87
- useEffect(() => {
88
- refetch();
89
- }, [refetch]);
90
- useEffect(() => {
91
- if (!refreshInterval || !dataUrl) return void 0;
92
- const timer = window.setInterval(() => {
93
- refetch();
94
- }, refreshInterval);
95
- return () => window.clearInterval(timer);
83
+ }
84
+ //#endregion
85
+ //#region packages/dashboard/dashboard/periodPresets.ts
86
+ const pad = (n) => String(n).padStart(2, "0");
87
+ const toIso = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
88
+ function daysAgo(today, days) {
89
+ const d = new Date(today);
90
+ d.setDate(d.getDate() - days);
91
+ return d;
92
+ }
93
+ function startOfMonth(date) {
94
+ return new Date(date.getFullYear(), date.getMonth(), 1);
95
+ }
96
+ function startOfYear(date) {
97
+ return new Date(date.getFullYear(), 0, 1);
98
+ }
99
+ const DEFAULT_PERIOD_PRESETS = [
100
+ {
101
+ key: "today",
102
+ label: "Today",
103
+ getRange: (today) => ({
104
+ start: toIso(today),
105
+ end: toIso(today)
106
+ })
107
+ },
108
+ {
109
+ key: "7d",
110
+ label: "7d",
111
+ getRange: (today) => ({
112
+ start: toIso(daysAgo(today, 6)),
113
+ end: toIso(today)
114
+ })
115
+ },
116
+ {
117
+ key: "30d",
118
+ label: "30d",
119
+ getRange: (today) => ({
120
+ start: toIso(daysAgo(today, 29)),
121
+ end: toIso(today)
122
+ })
123
+ },
124
+ {
125
+ key: "month",
126
+ label: "This month",
127
+ getRange: (today) => ({
128
+ start: toIso(startOfMonth(today)),
129
+ end: toIso(today)
130
+ })
131
+ },
132
+ {
133
+ key: "year",
134
+ label: "This year",
135
+ getRange: (today) => ({
136
+ start: toIso(startOfYear(today)),
137
+ end: toIso(today)
138
+ })
139
+ }
140
+ ];
141
+ function getPeriodPreset(key, presets = DEFAULT_PERIOD_PRESETS) {
142
+ return presets.find((preset) => preset.key === key);
143
+ }
144
+ //#endregion
145
+ //#region packages/dashboard/dashboard/useDashboardPeriod.ts
146
+ const CUSTOM_PERIOD_KEY = "custom";
147
+ function useDashboardPeriod(config) {
148
+ const presets = config?.presets ?? DEFAULT_PERIOD_PRESETS;
149
+ const defaultPreset = config?.defaultPreset ?? presets[0]?.key ?? "7d";
150
+ const allowCustomRange = config?.allowCustomRange ?? true;
151
+ const urlParam = config?.urlParam ?? "period";
152
+ const [searchParams, setSearchParams] = useSearchParams();
153
+ const presetKey = searchParams.get(urlParam) ?? defaultPreset;
154
+ const customStart = searchParams.get(`${urlParam}_from`);
155
+ const customEnd = searchParams.get(`${urlParam}_to`);
156
+ const value = useMemo(() => {
157
+ if (presetKey === "custom" && customStart && customEnd) return {
158
+ presetKey,
159
+ start: customStart,
160
+ end: customEnd
161
+ };
162
+ const preset = getPeriodPreset(presetKey, presets) ?? getPeriodPreset(defaultPreset, presets);
163
+ const range = preset?.getRange(/* @__PURE__ */ new Date()) ?? {
164
+ start: "",
165
+ end: ""
166
+ };
167
+ return {
168
+ presetKey: preset?.key ?? defaultPreset,
169
+ ...range
170
+ };
96
171
  }, [
97
- dataUrl,
98
- refreshInterval,
99
- refetch
172
+ presetKey,
173
+ customStart,
174
+ customEnd,
175
+ presets,
176
+ defaultPreset
100
177
  ]);
178
+ const setPreset = useCallback((key) => {
179
+ setSearchParams((prev) => {
180
+ const next = new URLSearchParams(prev);
181
+ next.set(urlParam, key);
182
+ next.delete(`${urlParam}_from`);
183
+ next.delete(`${urlParam}_to`);
184
+ return next;
185
+ });
186
+ }, [setSearchParams, urlParam]);
187
+ const setCustomRange = useCallback((start, end) => {
188
+ setSearchParams((prev) => {
189
+ const next = new URLSearchParams(prev);
190
+ next.set(urlParam, CUSTOM_PERIOD_KEY);
191
+ if (start) next.set(`${urlParam}_from`, start);
192
+ else next.delete(`${urlParam}_from`);
193
+ if (end) next.set(`${urlParam}_to`, end);
194
+ else next.delete(`${urlParam}_to`);
195
+ return next;
196
+ });
197
+ }, [setSearchParams, urlParam]);
198
+ if (!config) return void 0;
101
199
  return {
102
- ...state,
103
- refetch
200
+ value,
201
+ presets,
202
+ allowCustomRange,
203
+ setPreset,
204
+ setCustomRange
104
205
  };
105
206
  }
106
207
  //#endregion
208
+ //#region packages/dashboard/dashboard/DashboardPeriodFilter.tsx
209
+ function DashboardPeriodFilter({ period }) {
210
+ const { value, presets = [], allowCustomRange, setPreset, setCustomRange } = period;
211
+ const options = [...presets.map((preset) => ({
212
+ value: preset.key,
213
+ label: preset.label
214
+ })), ...allowCustomRange ? [{
215
+ value: CUSTOM_PERIOD_KEY,
216
+ label: "Custom"
217
+ }] : []];
218
+ const isCustom = value.presetKey === CUSTOM_PERIOD_KEY;
219
+ return /* @__PURE__ */ jsxs("div", {
220
+ className: "nb-dashboard-period-filter",
221
+ children: [/* @__PURE__ */ jsx(SegmentedControl, {
222
+ ariaLabel: "Period",
223
+ size: "sm",
224
+ options,
225
+ value: value.presetKey,
226
+ onChange: setPreset
227
+ }), isCustom && /* @__PURE__ */ jsx(DateRangePicker, {
228
+ startValue: value.start,
229
+ endValue: value.end,
230
+ onChange: setCustomRange,
231
+ ariaLabel: "Custom period"
232
+ })]
233
+ });
234
+ }
235
+ //#endregion
236
+ //#region packages/dashboard/dashboard/defaults.ts
237
+ const DEFAULT_PERIOD_PARAM_NAMES = {
238
+ start: "from",
239
+ end: "to"
240
+ };
241
+ //#endregion
242
+ //#region packages/dashboard/dashboard/useWidgetQuery.ts
243
+ /**
244
+ * Fetches a single widget's data independently of the dashboard's shared
245
+ * payload — its own cache entry, its own loading/error state, no head-of-line
246
+ * blocking behind slower widgets. Returns `undefined` when the widget has no
247
+ * `query` configured, so callers fall back to the dashboard's shared data.
248
+ */
249
+ function useWidgetQuery(query, period, periodParamNames = DEFAULT_PERIOD_PARAM_NAMES) {
250
+ const http = useCoreHttpClient();
251
+ const periodParams = (query?.usePeriod ?? true) && period ? {
252
+ [periodParamNames.start]: period.start,
253
+ [periodParamNames.end]: period.end
254
+ } : void 0;
255
+ const params = query ? {
256
+ ...query.params,
257
+ ...periodParams
258
+ } : void 0;
259
+ const result = useQuery({
260
+ queryKey: [
261
+ "nb-dashboard-widget",
262
+ query?.url,
263
+ params
264
+ ],
265
+ queryFn: async () => {
266
+ return (await http.get(query.url, { params })).data;
267
+ },
268
+ enabled: !!query,
269
+ refetchInterval: query?.refreshInterval,
270
+ retry: false
271
+ });
272
+ if (!query) return void 0;
273
+ return {
274
+ data: result.data ?? {},
275
+ loading: result.isLoading,
276
+ error: result.error ? result.error instanceof Error ? result.error.message : "Failed to load widget" : null
277
+ };
278
+ }
279
+ //#endregion
280
+ //#region packages/dashboard/dashboard/widgetRegistry.ts
281
+ const registry = /* @__PURE__ */ new Map();
282
+ /**
283
+ * Registers a component to render for `widget.type`. Built-in types (`stat`,
284
+ * `bar-chart`, `donut-chart`, `line-chart`, `area-chart`, `progress`, `table`)
285
+ * are registered automatically. Call this to add a new widget type — or to
286
+ * replace a built-in one — without forking `@nubitio/dashboard`.
287
+ *
288
+ * ```ts
289
+ * registerWidgetType('funnel', FunnelWidgetView);
290
+ * ```
291
+ */
292
+ function registerWidgetType(type, component) {
293
+ registry.set(type, component);
294
+ }
295
+ function getWidgetComponent(type) {
296
+ return registry.get(type);
297
+ }
298
+ function isWidgetTypeRegistered(type) {
299
+ return registry.has(type);
300
+ }
301
+ //#endregion
302
+ //#region packages/dashboard/dashboard/chartPalette.ts
303
+ const DEFAULT_CHART_COLORS = [
304
+ "var(--accent-color)",
305
+ "var(--success-color)",
306
+ "var(--warning-color)",
307
+ "var(--info-color)",
308
+ "#6b4fc8",
309
+ "#c2410c"
310
+ ];
311
+ //#endregion
107
312
  //#region packages/dashboard/dashboard/formatValue.ts
108
313
  function formatDashboardValue(value, format = "text") {
109
314
  if (value === null || value === void 0) return "—";
@@ -159,14 +364,145 @@ function resolveArray(source, path) {
159
364
  return value.filter((item) => item !== null && typeof item === "object");
160
365
  }
161
366
  //#endregion
367
+ //#region packages/dashboard/dashboard/widgets/ChartTooltip.tsx
368
+ function ChartTooltip({ active, label, payload, labelFormat, series }) {
369
+ if (!active || !payload?.length) return null;
370
+ return /* @__PURE__ */ jsxs("div", {
371
+ className: "nb-dashboard-chart-tooltip",
372
+ children: [label !== void 0 && /* @__PURE__ */ jsx("div", {
373
+ className: "nb-dashboard-chart-tooltip__label",
374
+ children: label
375
+ }), /* @__PURE__ */ jsx("ul", {
376
+ className: "nb-dashboard-chart-tooltip__items",
377
+ children: payload.map((item) => {
378
+ const seriesConfig = series?.find((s) => s.key === item.dataKey);
379
+ return /* @__PURE__ */ jsxs("li", {
380
+ className: "nb-dashboard-chart-tooltip__item",
381
+ children: [
382
+ /* @__PURE__ */ jsx("span", {
383
+ className: "nb-dashboard-chart-tooltip__swatch",
384
+ style: { background: item.color }
385
+ }),
386
+ /* @__PURE__ */ jsx("span", {
387
+ className: "nb-dashboard-chart-tooltip__name",
388
+ children: item.name
389
+ }),
390
+ /* @__PURE__ */ jsx("span", {
391
+ className: "nb-dashboard-chart-tooltip__value",
392
+ children: formatDashboardValue(item.value, seriesConfig?.valueFormat ?? labelFormat)
393
+ })
394
+ ]
395
+ }, String(item.dataKey));
396
+ })
397
+ })]
398
+ });
399
+ }
400
+ //#endregion
401
+ //#region packages/dashboard/dashboard/widgets/AreaChartWidgetView.tsx
402
+ function AreaChartWidgetView({ widget, data, loading }) {
403
+ const rows = resolveArray(data, widget.dataPath);
404
+ const height = widget.height ?? 240;
405
+ return /* @__PURE__ */ jsx(StatCard, {
406
+ title: widget.title,
407
+ headerExtra: widget.subtitle ? /* @__PURE__ */ jsx("span", {
408
+ className: "nb-dashboard-widget__subtitle",
409
+ children: widget.subtitle
410
+ }) : void 0,
411
+ menuVisible: widget.menuVisible,
412
+ isLoading: loading,
413
+ className: "nb-dashboard-chart-card",
414
+ children: rows.length === 0 ? /* @__PURE__ */ jsx("div", {
415
+ className: "nb-dashboard-chart-empty",
416
+ children: "No data"
417
+ }) : /* @__PURE__ */ jsx("div", {
418
+ style: { height },
419
+ children: /* @__PURE__ */ jsx(ResponsiveContainer, {
420
+ width: "100%",
421
+ height: "100%",
422
+ children: /* @__PURE__ */ jsxs(AreaChart, {
423
+ data: rows,
424
+ margin: {
425
+ top: 4,
426
+ right: 8,
427
+ bottom: 0,
428
+ left: 0
429
+ },
430
+ children: [
431
+ /* @__PURE__ */ jsx("defs", { children: widget.series.map((series, index) => {
432
+ const color = series.color ?? DEFAULT_CHART_COLORS[index % DEFAULT_CHART_COLORS.length];
433
+ return /* @__PURE__ */ jsxs("linearGradient", {
434
+ id: `nb-area-${widget.id}-${series.key}`,
435
+ x1: "0",
436
+ y1: "0",
437
+ x2: "0",
438
+ y2: "1",
439
+ children: [/* @__PURE__ */ jsx("stop", {
440
+ offset: "5%",
441
+ stopColor: color,
442
+ stopOpacity: .35
443
+ }), /* @__PURE__ */ jsx("stop", {
444
+ offset: "95%",
445
+ stopColor: color,
446
+ stopOpacity: .02
447
+ })]
448
+ }, series.key);
449
+ }) }),
450
+ widget.showGrid !== false && /* @__PURE__ */ jsx(CartesianGrid, {
451
+ strokeDasharray: "3 3",
452
+ stroke: "var(--border-color)",
453
+ vertical: false
454
+ }),
455
+ /* @__PURE__ */ jsx(XAxis, {
456
+ dataKey: widget.xKey,
457
+ tick: {
458
+ fontSize: 11,
459
+ fill: "var(--text-tertiary)"
460
+ },
461
+ axisLine: { stroke: "var(--border-color)" },
462
+ tickLine: false
463
+ }),
464
+ /* @__PURE__ */ jsx(YAxis, {
465
+ tick: {
466
+ fontSize: 11,
467
+ fill: "var(--text-tertiary)"
468
+ },
469
+ axisLine: false,
470
+ tickLine: false,
471
+ width: 48,
472
+ tickFormatter: (v) => formatDashboardValue(v, widget.valueFormat)
473
+ }),
474
+ /* @__PURE__ */ jsx(Tooltip, { content: /* @__PURE__ */ jsx(ChartTooltip, {
475
+ labelFormat: widget.valueFormat,
476
+ series: widget.series
477
+ }) }),
478
+ widget.showLegend && /* @__PURE__ */ jsx(Legend, { wrapperStyle: { fontSize: 12 } }),
479
+ widget.series.map((series, index) => {
480
+ const color = series.color ?? DEFAULT_CHART_COLORS[index % DEFAULT_CHART_COLORS.length];
481
+ return /* @__PURE__ */ jsx(Area, {
482
+ type: "monotone",
483
+ dataKey: series.key,
484
+ name: series.label ?? series.key,
485
+ stroke: color,
486
+ strokeWidth: 2,
487
+ fill: `url(#nb-area-${widget.id}-${series.key})`,
488
+ stackId: widget.stacked ? "stack" : void 0
489
+ }, series.key);
490
+ })
491
+ ]
492
+ })
493
+ })
494
+ })
495
+ });
496
+ }
497
+ //#endregion
162
498
  //#region packages/dashboard/dashboard/widgets/BarChartWidgetView.tsx
163
- function toNumber$1(value) {
499
+ function toNumber$2(value) {
164
500
  const numeric = typeof value === "number" ? value : Number(value);
165
501
  return Number.isFinite(numeric) ? numeric : 0;
166
502
  }
167
503
  function BarChartWidgetView({ widget, data, loading }) {
168
504
  const rows = resolveArray(data, widget.dataPath);
169
- const max = rows.reduce((peak, row) => Math.max(peak, toNumber$1(row[widget.yKey])), 0) || 1;
505
+ const max = rows.reduce((peak, row) => Math.max(peak, toNumber$2(row[widget.yKey])), 0) || 1;
170
506
  const height = widget.height ?? 200;
171
507
  return /* @__PURE__ */ jsx(StatCard, {
172
508
  title: widget.title,
@@ -187,7 +523,7 @@ function BarChartWidgetView({ widget, data, loading }) {
187
523
  "aria-label": widget.title,
188
524
  children: rows.map((row, index) => {
189
525
  const label = String(row[widget.xKey] ?? "");
190
- const value = toNumber$1(row[widget.yKey]);
526
+ const value = toNumber$2(row[widget.yKey]);
191
527
  return /* @__PURE__ */ jsxs("div", {
192
528
  className: "nb-dashboard-bar-chart__item",
193
529
  children: [/* @__PURE__ */ jsx("div", {
@@ -208,28 +544,20 @@ function BarChartWidgetView({ widget, data, loading }) {
208
544
  }
209
545
  //#endregion
210
546
  //#region packages/dashboard/dashboard/widgets/DonutChartWidgetView.tsx
211
- const DEFAULT_COLORS = [
212
- "var(--accent-color)",
213
- "var(--success-color)",
214
- "var(--warning-color)",
215
- "var(--info-color)",
216
- "#6b4fc8",
217
- "#c2410c"
218
- ];
219
- function toNumber(value) {
547
+ function toNumber$1(value) {
220
548
  const numeric = typeof value === "number" ? value : Number(value);
221
549
  return Number.isFinite(numeric) ? numeric : 0;
222
550
  }
223
551
  function DonutChartWidgetView({ widget, data, loading }) {
224
552
  const rows = resolveArray(data, widget.dataPath);
225
- const colors = widget.colors ?? DEFAULT_COLORS;
226
- const total = rows.reduce((sum, row) => sum + toNumber(row[widget.valueKey]), 0);
553
+ const colors = widget.colors ?? DEFAULT_CHART_COLORS;
554
+ const total = rows.reduce((sum, row) => sum + toNumber$1(row[widget.valueKey]), 0);
227
555
  const centerValue = widget.centerValuePath !== void 0 ? resolvePath(data, widget.centerValuePath) : total;
228
556
  const radius = 38;
229
557
  const stroke = 14;
230
558
  const circumference = 2 * Math.PI * radius;
231
559
  const arcs = rows.reduce((segments, row, index) => {
232
- const pct = toNumber(row[widget.valueKey]) / total;
560
+ const pct = toNumber$1(row[widget.valueKey]) / total;
233
561
  const offset = segments.reduce((sum, segment) => sum + segment.dash, 0);
234
562
  segments.push({
235
563
  key: `${String(row[widget.labelKey])}-${index}`,
@@ -293,7 +621,7 @@ function DonutChartWidgetView({ widget, data, loading }) {
293
621
  className: "nb-dashboard-donut__legend",
294
622
  children: rows.map((row, index) => {
295
623
  const label = String(row[widget.labelKey] ?? "");
296
- const value = toNumber(row[widget.valueKey]);
624
+ const value = toNumber$1(row[widget.valueKey]);
297
625
  const pct = total > 0 ? value / total * 100 : 0;
298
626
  return /* @__PURE__ */ jsxs("li", {
299
627
  className: "nb-dashboard-donut__legend-item",
@@ -318,6 +646,123 @@ function DonutChartWidgetView({ widget, data, loading }) {
318
646
  });
319
647
  }
320
648
  //#endregion
649
+ //#region packages/dashboard/dashboard/widgets/LineChartWidgetView.tsx
650
+ function LineChartWidgetView({ widget, data, loading }) {
651
+ const rows = resolveArray(data, widget.dataPath);
652
+ const height = widget.height ?? 240;
653
+ return /* @__PURE__ */ jsx(StatCard, {
654
+ title: widget.title,
655
+ headerExtra: widget.subtitle ? /* @__PURE__ */ jsx("span", {
656
+ className: "nb-dashboard-widget__subtitle",
657
+ children: widget.subtitle
658
+ }) : void 0,
659
+ menuVisible: widget.menuVisible,
660
+ isLoading: loading,
661
+ className: "nb-dashboard-chart-card",
662
+ children: rows.length === 0 ? /* @__PURE__ */ jsx("div", {
663
+ className: "nb-dashboard-chart-empty",
664
+ children: "No data"
665
+ }) : /* @__PURE__ */ jsx("div", {
666
+ style: { height },
667
+ children: /* @__PURE__ */ jsx(ResponsiveContainer, {
668
+ width: "100%",
669
+ height: "100%",
670
+ children: /* @__PURE__ */ jsxs(LineChart, {
671
+ data: rows,
672
+ margin: {
673
+ top: 4,
674
+ right: 8,
675
+ bottom: 0,
676
+ left: 0
677
+ },
678
+ children: [
679
+ widget.showGrid !== false && /* @__PURE__ */ jsx(CartesianGrid, {
680
+ strokeDasharray: "3 3",
681
+ stroke: "var(--border-color)",
682
+ vertical: false
683
+ }),
684
+ /* @__PURE__ */ jsx(XAxis, {
685
+ dataKey: widget.xKey,
686
+ tick: {
687
+ fontSize: 11,
688
+ fill: "var(--text-tertiary)"
689
+ },
690
+ axisLine: { stroke: "var(--border-color)" },
691
+ tickLine: false
692
+ }),
693
+ /* @__PURE__ */ jsx(YAxis, {
694
+ tick: {
695
+ fontSize: 11,
696
+ fill: "var(--text-tertiary)"
697
+ },
698
+ axisLine: false,
699
+ tickLine: false,
700
+ width: 48,
701
+ tickFormatter: (v) => formatDashboardValue(v, widget.valueFormat)
702
+ }),
703
+ /* @__PURE__ */ jsx(Tooltip, { content: /* @__PURE__ */ jsx(ChartTooltip, {
704
+ labelFormat: widget.valueFormat,
705
+ series: widget.series
706
+ }) }),
707
+ widget.showLegend && /* @__PURE__ */ jsx(Legend, { wrapperStyle: { fontSize: 12 } }),
708
+ widget.series.map((series, index) => /* @__PURE__ */ jsx(Line, {
709
+ type: widget.curved === false ? "linear" : "monotone",
710
+ dataKey: series.key,
711
+ name: series.label ?? series.key,
712
+ stroke: series.color ?? DEFAULT_CHART_COLORS[index % DEFAULT_CHART_COLORS.length],
713
+ strokeWidth: 2,
714
+ dot: false,
715
+ activeDot: { r: 4 }
716
+ }, series.key))
717
+ ]
718
+ })
719
+ })
720
+ })
721
+ });
722
+ }
723
+ //#endregion
724
+ //#region packages/dashboard/dashboard/widgets/ProgressWidgetView.tsx
725
+ function toNumber(value, fallback) {
726
+ const numeric = typeof value === "number" ? value : Number(value);
727
+ return Number.isFinite(numeric) ? numeric : fallback;
728
+ }
729
+ function ProgressWidgetView({ widget, data, loading }) {
730
+ const value = toNumber(widget.valuePath !== void 0 ? resolvePath(data, widget.valuePath) : widget.value, 0);
731
+ const max = widget.maxPath !== void 0 ? toNumber(resolvePath(data, widget.maxPath), 100) : widget.max ?? 100;
732
+ const pct = max > 0 ? Math.min(100, Math.max(0, value / max * 100)) : 0;
733
+ const tone = widget.tone ?? "accent";
734
+ return /* @__PURE__ */ jsxs(StatCard, {
735
+ title: widget.title,
736
+ headerExtra: widget.subtitle ? /* @__PURE__ */ jsx("span", {
737
+ className: "nb-dashboard-widget__subtitle",
738
+ children: widget.subtitle
739
+ }) : void 0,
740
+ menuVisible: widget.menuVisible,
741
+ isLoading: loading,
742
+ className: `nb-dashboard-progress nb-dashboard-progress--${tone}`,
743
+ children: [/* @__PURE__ */ jsx("div", {
744
+ className: "nb-dashboard-progress__meter",
745
+ role: "progressbar",
746
+ "aria-valuenow": pct,
747
+ "aria-valuemin": 0,
748
+ "aria-valuemax": 100,
749
+ children: /* @__PURE__ */ jsx("div", {
750
+ className: "nb-dashboard-progress__fill",
751
+ style: { width: `${pct}%` }
752
+ })
753
+ }), /* @__PURE__ */ jsxs("div", {
754
+ className: "nb-dashboard-progress__labels",
755
+ children: [/* @__PURE__ */ jsx("span", {
756
+ className: "nb-dashboard-progress__value",
757
+ children: formatDashboardValue(value, widget.format ?? "number")
758
+ }), /* @__PURE__ */ jsxs("span", {
759
+ className: "nb-dashboard-progress__max",
760
+ children: ["/ ", formatDashboardValue(max, widget.format ?? "number")]
761
+ })]
762
+ })]
763
+ });
764
+ }
765
+ //#endregion
321
766
  //#region packages/dashboard/dashboard/widgets/StatWidgetView.tsx
322
767
  function resolveTrend(widget, data) {
323
768
  if (!widget.trend) return { value: null };
@@ -415,73 +860,278 @@ function TableWidgetView({ widget, data, loading }) {
415
860
  });
416
861
  }
417
862
  //#endregion
863
+ //#region packages/dashboard/dashboard/widgets/registerBuiltinWidgets.ts
864
+ registerWidgetType("stat", StatWidgetView);
865
+ registerWidgetType("bar-chart", BarChartWidgetView);
866
+ registerWidgetType("donut-chart", DonutChartWidgetView);
867
+ registerWidgetType("line-chart", LineChartWidgetView);
868
+ registerWidgetType("area-chart", AreaChartWidgetView);
869
+ registerWidgetType("progress", ProgressWidgetView);
870
+ registerWidgetType("table", TableWidgetView);
871
+ //#endregion
418
872
  //#region packages/dashboard/dashboard/widgets/WidgetRenderer.tsx
873
+ const isDev = typeof process !== "undefined" && process.env?.NODE_ENV !== "production";
419
874
  function WidgetRenderer({ widget, data, loading }) {
420
- switch (widget.type) {
421
- case "stat": return /* @__PURE__ */ jsx(StatWidgetView, {
422
- widget,
423
- data,
424
- loading
425
- });
426
- case "bar-chart": return /* @__PURE__ */ jsx(BarChartWidgetView, {
427
- widget,
428
- data,
429
- loading
875
+ const Component = getWidgetComponent(widget.type);
876
+ if (!Component) {
877
+ if (isDev) console.warn(`[@nubitio/dashboard] No widget registered for type "${widget.type}".`);
878
+ return null;
879
+ }
880
+ return /* @__PURE__ */ jsx(Component, {
881
+ widget,
882
+ data,
883
+ loading
884
+ });
885
+ }
886
+ //#endregion
887
+ //#region packages/dashboard/dashboard/DashboardWidgetSlot.tsx
888
+ function DashboardWidgetSlot({ widget, data, loading, editMode, onHide, onMoveUp, onMoveDown, period, periodParamNames = DEFAULT_PERIOD_PARAM_NAMES }) {
889
+ const widgetQuery = useWidgetQuery(widget.query, period, periodParamNames);
890
+ const effectiveData = widgetQuery ? widgetQuery.data : data;
891
+ const effectiveLoading = widgetQuery ? widgetQuery.loading : loading;
892
+ const body = /* @__PURE__ */ jsxs(Fragment, { children: [widgetQuery?.error && /* @__PURE__ */ jsx("div", {
893
+ className: "nb-dashboard-widget-slot__error",
894
+ children: widgetQuery.error
895
+ }), /* @__PURE__ */ jsx(WidgetRenderer, {
896
+ widget,
897
+ data: effectiveData,
898
+ loading: effectiveLoading
899
+ })] });
900
+ if (!editMode) return body;
901
+ return /* @__PURE__ */ jsxs("div", {
902
+ className: "nb-dashboard-widget-slot",
903
+ children: [/* @__PURE__ */ jsxs("div", {
904
+ className: "nb-dashboard-widget-slot__controls",
905
+ children: [
906
+ /* @__PURE__ */ jsx("button", {
907
+ type: "button",
908
+ className: "nb-dashboard-widget-slot__btn",
909
+ "aria-label": `Move ${widget.title} earlier`,
910
+ onClick: onMoveUp,
911
+ children: /* @__PURE__ */ jsx("i", {
912
+ className: "ph ph-caret-up",
913
+ "aria-hidden": "true"
914
+ })
915
+ }),
916
+ /* @__PURE__ */ jsx("button", {
917
+ type: "button",
918
+ className: "nb-dashboard-widget-slot__btn",
919
+ "aria-label": `Move ${widget.title} later`,
920
+ onClick: onMoveDown,
921
+ children: /* @__PURE__ */ jsx("i", {
922
+ className: "ph ph-caret-down",
923
+ "aria-hidden": "true"
924
+ })
925
+ }),
926
+ /* @__PURE__ */ jsx("button", {
927
+ type: "button",
928
+ className: "nb-dashboard-widget-slot__btn nb-dashboard-widget-slot__btn--hide",
929
+ "aria-label": `Hide ${widget.title}`,
930
+ onClick: onHide,
931
+ children: /* @__PURE__ */ jsx("i", {
932
+ className: "ph ph-eye-slash",
933
+ "aria-hidden": "true"
934
+ })
935
+ })
936
+ ]
937
+ }), /* @__PURE__ */ jsx("div", {
938
+ className: "nb-dashboard-widget-slot__body",
939
+ children: body
940
+ })]
941
+ });
942
+ }
943
+ //#endregion
944
+ //#region packages/dashboard/dashboard/useDashboardData.ts
945
+ function useDashboardData(dataUrl, refreshInterval, period, periodParamNames = DEFAULT_PERIOD_PARAM_NAMES) {
946
+ const http = useCoreHttpClient();
947
+ const params = period ? {
948
+ [periodParamNames.start]: period.start,
949
+ [periodParamNames.end]: period.end
950
+ } : void 0;
951
+ const query = useQuery({
952
+ queryKey: [
953
+ "nb-dashboard",
954
+ dataUrl,
955
+ params
956
+ ],
957
+ queryFn: async () => {
958
+ return (await http.get(dataUrl, { params })).data;
959
+ },
960
+ enabled: !!dataUrl,
961
+ refetchInterval: refreshInterval,
962
+ retry: false
963
+ });
964
+ return {
965
+ data: query.data ?? {},
966
+ loading: query.isLoading,
967
+ error: query.error ? query.error instanceof Error ? query.error.message : "Failed to load dashboard" : null,
968
+ refetch: () => {
969
+ query.refetch();
970
+ }
971
+ };
972
+ }
973
+ //#endregion
974
+ //#region packages/dashboard/dashboard/useDashboardLayout.ts
975
+ function storageKey(dashboardId) {
976
+ return `nb-dashboard-layout:${dashboardId}`;
977
+ }
978
+ function readStore(dashboardId) {
979
+ try {
980
+ const raw = window.localStorage.getItem(storageKey(dashboardId));
981
+ return raw ? JSON.parse(raw) : {};
982
+ } catch {
983
+ return {};
984
+ }
985
+ }
986
+ function writeStore(dashboardId, store) {
987
+ try {
988
+ window.localStorage.setItem(storageKey(dashboardId), JSON.stringify(store));
989
+ } catch {}
990
+ }
991
+ function useDashboardLayout(dashboardId, sections, enabled) {
992
+ const [editMode, setEditMode] = useState(false);
993
+ const id = dashboardId ?? "dashboard";
994
+ const [store, setStore] = useState(() => enabled ? readStore(id) : {});
995
+ const updateSection = useCallback((sectionId, updater) => {
996
+ setStore((prev) => {
997
+ const current = prev[sectionId] ?? {
998
+ order: [],
999
+ hidden: []
1000
+ };
1001
+ const next = {
1002
+ ...prev,
1003
+ [sectionId]: updater(current)
1004
+ };
1005
+ writeStore(id, next);
1006
+ return next;
430
1007
  });
431
- case "donut-chart": return /* @__PURE__ */ jsx(DonutChartWidgetView, {
432
- widget,
433
- data,
434
- loading
1008
+ }, [id]);
1009
+ const getSectionWidgets = useCallback((section, sectionId) => {
1010
+ if (!enabled) return section.widgets;
1011
+ const layout = store[sectionId];
1012
+ if (!layout) return section.widgets;
1013
+ const byId = new Map(section.widgets.map((widget) => [widget.id, widget]));
1014
+ const ordered = layout.order.map((wid) => byId.get(wid)).filter((w) => !!w);
1015
+ const remaining = section.widgets.filter((widget) => !layout.order.includes(widget.id));
1016
+ return [...ordered, ...remaining].filter((widget) => !layout.hidden.includes(widget.id));
1017
+ }, [enabled, store]);
1018
+ const hideWidget = useCallback((sectionId, widgetId) => {
1019
+ updateSection(sectionId, (current) => ({
1020
+ ...current,
1021
+ hidden: current.hidden.includes(widgetId) ? current.hidden : [...current.hidden, widgetId]
1022
+ }));
1023
+ }, [updateSection]);
1024
+ const showWidget = useCallback((sectionId, widgetId) => {
1025
+ updateSection(sectionId, (current) => ({
1026
+ ...current,
1027
+ hidden: current.hidden.filter((wid) => wid !== widgetId)
1028
+ }));
1029
+ }, [updateSection]);
1030
+ const moveWidget = useCallback((sectionId, widgetId, direction) => {
1031
+ const section = sections.find((s) => (s.id ?? "") === sectionId);
1032
+ if (!section) return;
1033
+ updateSection(sectionId, (current) => {
1034
+ const base = current.order.length ? current.order : section.widgets.map((w) => w.id);
1035
+ const index = base.indexOf(widgetId);
1036
+ const targetIndex = index + direction;
1037
+ if (index === -1 || targetIndex < 0 || targetIndex >= base.length) return current;
1038
+ const order = [...base];
1039
+ [order[index], order[targetIndex]] = [order[targetIndex], order[index]];
1040
+ return {
1041
+ ...current,
1042
+ order
1043
+ };
435
1044
  });
436
- case "table": return /* @__PURE__ */ jsx(TableWidgetView, {
437
- widget,
438
- data,
439
- loading
1045
+ }, [sections, updateSection]);
1046
+ const resetLayout = useCallback(() => {
1047
+ setStore({});
1048
+ writeStore(id, {});
1049
+ }, [id]);
1050
+ const hiddenWidgets = useMemo(() => {
1051
+ if (!enabled) return [];
1052
+ return sections.flatMap((section) => {
1053
+ const sectionId = section.id ?? "";
1054
+ const hidden = store[sectionId]?.hidden ?? [];
1055
+ return section.widgets.filter((widget) => hidden.includes(widget.id)).map((widget) => ({
1056
+ sectionId,
1057
+ widget
1058
+ }));
440
1059
  });
441
- default: return null;
442
- }
1060
+ }, [
1061
+ enabled,
1062
+ sections,
1063
+ store
1064
+ ]);
1065
+ if (!enabled) return void 0;
1066
+ return {
1067
+ editMode,
1068
+ setEditMode,
1069
+ getSectionWidgets,
1070
+ hiddenWidgets,
1071
+ hideWidget,
1072
+ showWidget,
1073
+ moveWidget,
1074
+ resetLayout
1075
+ };
443
1076
  }
444
1077
  //#endregion
445
1078
  //#region packages/dashboard/dashboard/DashboardPage.tsx
446
1079
  function sectionClassName(section) {
447
- const layout = section.layout ?? "grid";
448
- if (layout === "grid") return (typeof section.columns === "number" ? `repeat(${section.columns}, minmax(0, 1fr))` : section.columns) ? "nb-dashboard-section nb-dashboard-section--grid" : "nb-dashboard-section nb-dashboard-section--grid";
449
- return `nb-dashboard-section nb-dashboard-section--${layout}`;
1080
+ return `nb-dashboard-section nb-dashboard-section--${section.layout ?? "grid"}`;
450
1081
  }
451
1082
  function sectionStyle(section) {
452
1083
  if (section.layout !== "grid" && section.layout !== void 0) return void 0;
453
1084
  const columns = typeof section.columns === "number" ? `repeat(${section.columns}, minmax(0, 1fr))` : section.columns;
454
1085
  if (!columns) return void 0;
455
- return { gridTemplateColumns: String(columns) };
1086
+ return { "--nb-dashboard-columns": String(columns) };
456
1087
  }
457
- function DashboardSectionView({ section, data, loading }) {
1088
+ function DashboardSectionView({ section, sectionId, data, loading, layout, period, periodParamNames }) {
1089
+ const widgets = layout ? layout.getSectionWidgets(section, sectionId) : section.widgets;
458
1090
  return /* @__PURE__ */ jsx("section", {
459
1091
  className: sectionClassName(section),
460
1092
  style: sectionStyle(section),
461
1093
  "data-section": section.id,
462
- children: section.widgets.map((widget) => /* @__PURE__ */ jsx(WidgetRenderer, {
1094
+ children: widgets.map((widget) => /* @__PURE__ */ jsx(DashboardWidgetSlot, {
463
1095
  widget,
464
1096
  data,
465
- loading
1097
+ loading,
1098
+ editMode: !!layout?.editMode,
1099
+ onHide: () => layout?.hideWidget(sectionId, widget.id),
1100
+ onMoveUp: () => layout?.moveWidget(sectionId, widget.id, -1),
1101
+ onMoveDown: () => layout?.moveWidget(sectionId, widget.id, 1),
1102
+ period,
1103
+ periodParamNames
466
1104
  }, widget.id))
467
1105
  });
468
1106
  }
469
1107
  function DashboardPage({ config }) {
470
- const fetched = useDashboardData(config.dataUrl, config.refreshInterval);
471
- const { data, loading, error, refetch } = config.useData?.() ?? fetched;
1108
+ const period = useDashboardPeriod(config.period);
1109
+ const layout = useDashboardLayout(config.id, config.sections, !!config.customizable);
1110
+ const fetched = useDashboardData(config.dataUrl, config.refreshInterval, period?.value, config.period?.paramNames);
1111
+ const { data, loading, error, refetch } = config.useData?.(period?.value) ?? fetched;
1112
+ const periodParamNames = config.period?.paramNames ?? DEFAULT_PERIOD_PARAM_NAMES;
1113
+ const toolbarExtras = /* @__PURE__ */ jsxs(Fragment, { children: [period && /* @__PURE__ */ jsx(DashboardPeriodFilter, { period }), layout && /* @__PURE__ */ jsx(DashboardLayoutControls, { layout })] });
472
1114
  return /* @__PURE__ */ jsxs("div", {
473
1115
  className: "view-wrapper-scroll nb-dashboard-page",
474
1116
  children: [/* @__PURE__ */ jsxs(AppToolbar, {
475
1117
  title: config.title,
476
1118
  onRefresh: refetch,
1119
+ additionalToolbarContent: toolbarExtras,
477
1120
  children: [error && /* @__PURE__ */ jsx("div", {
478
1121
  className: "nb-dashboard-page__error",
479
1122
  children: error
480
- }), config.sections.map((section, index) => /* @__PURE__ */ jsx(DashboardSectionView, {
481
- section,
482
- data,
483
- loading
484
- }, section.id ?? `section-${index}`))]
1123
+ }), config.sections.map((section, index) => {
1124
+ const sectionId = section.id ?? `section-${index}`;
1125
+ return /* @__PURE__ */ jsx(DashboardSectionView, {
1126
+ section,
1127
+ sectionId,
1128
+ data,
1129
+ loading,
1130
+ layout,
1131
+ period: period?.value,
1132
+ periodParamNames
1133
+ }, sectionId);
1134
+ })]
485
1135
  }), loading && /* @__PURE__ */ jsx("div", {
486
1136
  className: "nb-dashboard-page__loading",
487
1137
  "aria-hidden": "true",
@@ -523,5 +1173,32 @@ function tableWidget(config) {
523
1173
  ...config
524
1174
  };
525
1175
  }
1176
+ function lineChartWidget(config) {
1177
+ return {
1178
+ type: "line-chart",
1179
+ menuVisible: false,
1180
+ showGrid: true,
1181
+ height: 240,
1182
+ ...config
1183
+ };
1184
+ }
1185
+ function areaChartWidget(config) {
1186
+ return {
1187
+ type: "area-chart",
1188
+ menuVisible: false,
1189
+ showGrid: true,
1190
+ height: 240,
1191
+ ...config
1192
+ };
1193
+ }
1194
+ function progressWidget(config) {
1195
+ return {
1196
+ type: "progress",
1197
+ menuVisible: false,
1198
+ max: 100,
1199
+ format: "number",
1200
+ ...config
1201
+ };
1202
+ }
526
1203
  //#endregion
527
- export { DashboardPage, barChartWidget, defineDashboard, donutChartWidget, formatDashboardValue, resolveArray, resolvePath, statWidget, tableWidget, useDashboardData };
1204
+ export { CUSTOM_PERIOD_KEY, DEFAULT_CHART_COLORS, DEFAULT_PERIOD_PARAM_NAMES, DEFAULT_PERIOD_PRESETS, DashboardLayoutControls, DashboardPage, DashboardPeriodFilter, DashboardWidgetSlot, areaChartWidget, barChartWidget, defineDashboard, donutChartWidget, formatDashboardValue, getPeriodPreset, getWidgetComponent, isWidgetTypeRegistered, lineChartWidget, progressWidget, registerWidgetType, resolveArray, resolvePath, statWidget, tableWidget, useDashboardData, useDashboardLayout, useDashboardPeriod, useWidgetQuery };