@nubitio/dashboard 0.7.3 → 0.8.0

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,9 @@
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, DateRangePicker, IconButton, Popover, SegmentedControl } from "@nubitio/ui";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { useCallback, useMemo, useState } from "react";
4
+ import { useSearchParams } from "react-router-dom";
5
+ import { useQuery } from "@tanstack/react-query";
6
+ import { getCoreCurrency, getCoreLocale, useCoreHttpClient } from "@nubitio/core";
6
7
  //#region packages/dashboard/dashboard/defineDashboard.ts
7
8
  const dashboardCache = /* @__PURE__ */ new Map();
8
9
  function cacheKey(config) {
@@ -43,67 +44,270 @@ function defineDashboard(config) {
43
44
  return dashboard;
44
45
  }
45
46
  //#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
47
+ //#region packages/dashboard/dashboard/DashboardLayoutControls.tsx
48
+ function DashboardLayoutControls({ layout }) {
49
+ return /* @__PURE__ */ jsxs("div", {
50
+ className: "nb-dashboard-layout-controls",
51
+ children: [
52
+ layout.editMode && layout.hiddenWidgets.length > 0 && /* @__PURE__ */ jsx(Popover, {
53
+ ariaLabel: "Hidden widgets",
54
+ align: "end",
55
+ trigger: ({ toggle }) => /* @__PURE__ */ jsx(IconButton, {
56
+ icon: "ph ph-eye-slash",
57
+ label: `Hidden widgets (${layout.hiddenWidgets.length})`,
58
+ onClick: toggle
59
+ }),
60
+ panel: () => /* @__PURE__ */ jsx("ul", {
61
+ className: "nb-dashboard-layout-controls__hidden-list",
62
+ children: layout.hiddenWidgets.map(({ sectionId, widget }) => /* @__PURE__ */ jsxs("li", { children: [/* @__PURE__ */ jsx("span", { children: widget.title }), /* @__PURE__ */ jsx("button", {
63
+ type: "button",
64
+ className: "nb-dashboard-layout-controls__show-btn",
65
+ onClick: () => layout.showWidget(sectionId, widget.id),
66
+ children: "Show"
67
+ })] }, `${sectionId}-${widget.id}`))
68
+ })
69
+ }),
70
+ layout.editMode && /* @__PURE__ */ jsx(IconButton, {
71
+ icon: "ph ph-arrow-counter-clockwise",
72
+ label: "Reset layout",
73
+ onClick: layout.resetLayout
74
+ }),
75
+ /* @__PURE__ */ jsx(IconButton, {
76
+ icon: layout.editMode ? "ph ph-check" : "ph ph-sliders-horizontal",
77
+ label: layout.editMode ? "Done customizing" : "Customize dashboard",
78
+ onClick: () => layout.setEditMode(!layout.editMode)
79
+ })
80
+ ]
60
81
  });
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);
82
+ }
83
+ //#endregion
84
+ //#region packages/dashboard/dashboard/periodPresets.ts
85
+ const pad = (n) => String(n).padStart(2, "0");
86
+ const toIso = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
87
+ function daysAgo(today, days) {
88
+ const d = new Date(today);
89
+ d.setDate(d.getDate() - days);
90
+ return d;
91
+ }
92
+ function startOfMonth(date) {
93
+ return new Date(date.getFullYear(), date.getMonth(), 1);
94
+ }
95
+ function startOfYear(date) {
96
+ return new Date(date.getFullYear(), 0, 1);
97
+ }
98
+ const DEFAULT_PERIOD_PRESETS = [
99
+ {
100
+ key: "today",
101
+ label: "Today",
102
+ getRange: (today) => ({
103
+ start: toIso(today),
104
+ end: toIso(today)
105
+ })
106
+ },
107
+ {
108
+ key: "7d",
109
+ label: "7d",
110
+ getRange: (today) => ({
111
+ start: toIso(daysAgo(today, 6)),
112
+ end: toIso(today)
113
+ })
114
+ },
115
+ {
116
+ key: "30d",
117
+ label: "30d",
118
+ getRange: (today) => ({
119
+ start: toIso(daysAgo(today, 29)),
120
+ end: toIso(today)
121
+ })
122
+ },
123
+ {
124
+ key: "month",
125
+ label: "This month",
126
+ getRange: (today) => ({
127
+ start: toIso(startOfMonth(today)),
128
+ end: toIso(today)
129
+ })
130
+ },
131
+ {
132
+ key: "year",
133
+ label: "This year",
134
+ getRange: (today) => ({
135
+ start: toIso(startOfYear(today)),
136
+ end: toIso(today)
137
+ })
138
+ }
139
+ ];
140
+ function getPeriodPreset(key, presets = DEFAULT_PERIOD_PRESETS) {
141
+ return presets.find((preset) => preset.key === key);
142
+ }
143
+ //#endregion
144
+ //#region packages/dashboard/dashboard/useDashboardPeriod.ts
145
+ const CUSTOM_PERIOD_KEY = "custom";
146
+ function useDashboardPeriod(config) {
147
+ const presets = config?.presets ?? DEFAULT_PERIOD_PRESETS;
148
+ const defaultPreset = config?.defaultPreset ?? presets[0]?.key ?? "7d";
149
+ const allowCustomRange = config?.allowCustomRange ?? true;
150
+ const urlParam = config?.urlParam ?? "period";
151
+ const [searchParams, setSearchParams] = useSearchParams();
152
+ const presetKey = searchParams.get(urlParam) ?? defaultPreset;
153
+ const customStart = searchParams.get(`${urlParam}_from`);
154
+ const customEnd = searchParams.get(`${urlParam}_to`);
155
+ const value = useMemo(() => {
156
+ if (presetKey === "custom" && customStart && customEnd) return {
157
+ presetKey,
158
+ start: customStart,
159
+ end: customEnd
160
+ };
161
+ const preset = getPeriodPreset(presetKey, presets) ?? getPeriodPreset(defaultPreset, presets);
162
+ const range = preset?.getRange(/* @__PURE__ */ new Date()) ?? {
163
+ start: "",
164
+ end: ""
165
+ };
166
+ return {
167
+ presetKey: preset?.key ?? defaultPreset,
168
+ ...range
169
+ };
96
170
  }, [
97
- dataUrl,
98
- refreshInterval,
99
- refetch
171
+ presetKey,
172
+ customStart,
173
+ customEnd,
174
+ presets,
175
+ defaultPreset
100
176
  ]);
177
+ const setPreset = useCallback((key) => {
178
+ setSearchParams((prev) => {
179
+ const next = new URLSearchParams(prev);
180
+ next.set(urlParam, key);
181
+ next.delete(`${urlParam}_from`);
182
+ next.delete(`${urlParam}_to`);
183
+ return next;
184
+ });
185
+ }, [setSearchParams, urlParam]);
186
+ const setCustomRange = useCallback((start, end) => {
187
+ setSearchParams((prev) => {
188
+ const next = new URLSearchParams(prev);
189
+ next.set(urlParam, CUSTOM_PERIOD_KEY);
190
+ if (start) next.set(`${urlParam}_from`, start);
191
+ else next.delete(`${urlParam}_from`);
192
+ if (end) next.set(`${urlParam}_to`, end);
193
+ else next.delete(`${urlParam}_to`);
194
+ return next;
195
+ });
196
+ }, [setSearchParams, urlParam]);
197
+ if (!config) return void 0;
198
+ return {
199
+ value,
200
+ presets,
201
+ allowCustomRange,
202
+ setPreset,
203
+ setCustomRange
204
+ };
205
+ }
206
+ //#endregion
207
+ //#region packages/dashboard/dashboard/DashboardPeriodFilter.tsx
208
+ function DashboardPeriodFilter({ period }) {
209
+ const { value, presets = [], allowCustomRange, setPreset, setCustomRange } = period;
210
+ const options = [...presets.map((preset) => ({
211
+ value: preset.key,
212
+ label: preset.label
213
+ })), ...allowCustomRange ? [{
214
+ value: CUSTOM_PERIOD_KEY,
215
+ label: "Custom"
216
+ }] : []];
217
+ const isCustom = value.presetKey === CUSTOM_PERIOD_KEY;
218
+ return /* @__PURE__ */ jsxs("div", {
219
+ className: "nb-dashboard-period-filter",
220
+ children: [/* @__PURE__ */ jsx(SegmentedControl, {
221
+ ariaLabel: "Period",
222
+ size: "sm",
223
+ options,
224
+ value: value.presetKey,
225
+ onChange: setPreset
226
+ }), isCustom && /* @__PURE__ */ jsx(DateRangePicker, {
227
+ startValue: value.start,
228
+ endValue: value.end,
229
+ onChange: setCustomRange,
230
+ ariaLabel: "Custom period"
231
+ })]
232
+ });
233
+ }
234
+ //#endregion
235
+ //#region packages/dashboard/dashboard/defaults.ts
236
+ const DEFAULT_PERIOD_PARAM_NAMES = {
237
+ start: "from",
238
+ end: "to"
239
+ };
240
+ //#endregion
241
+ //#region packages/dashboard/dashboard/useWidgetQuery.ts
242
+ /**
243
+ * Fetches a single widget's data independently of the dashboard's shared
244
+ * payload — its own cache entry, its own loading/error state, no head-of-line
245
+ * blocking behind slower widgets. Returns `undefined` when the widget has no
246
+ * `query` configured, so callers fall back to the dashboard's shared data.
247
+ */
248
+ function useWidgetQuery(query, period, periodParamNames = DEFAULT_PERIOD_PARAM_NAMES) {
249
+ const http = useCoreHttpClient();
250
+ const periodParams = (query?.usePeriod ?? true) && period ? {
251
+ [periodParamNames.start]: period.start,
252
+ [periodParamNames.end]: period.end
253
+ } : void 0;
254
+ const params = query ? {
255
+ ...query.params,
256
+ ...periodParams
257
+ } : void 0;
258
+ const result = useQuery({
259
+ queryKey: [
260
+ "nb-dashboard-widget",
261
+ query?.url,
262
+ params
263
+ ],
264
+ queryFn: async () => {
265
+ return (await http.get(query.url, { params })).data;
266
+ },
267
+ enabled: !!query,
268
+ refetchInterval: query?.refreshInterval,
269
+ retry: false
270
+ });
271
+ if (!query) return void 0;
101
272
  return {
102
- ...state,
103
- refetch
273
+ data: result.data ?? {},
274
+ loading: result.isLoading,
275
+ error: result.error ? result.error instanceof Error ? result.error.message : "Failed to load widget" : null
104
276
  };
105
277
  }
106
278
  //#endregion
279
+ //#region packages/dashboard/dashboard/widgetRegistry.ts
280
+ const registry = /* @__PURE__ */ new Map();
281
+ /**
282
+ * Registers a component to render for `widget.type`. Built-in types (`stat`,
283
+ * `bar-chart`, `donut-chart`, `line-chart`, `area-chart`, `progress`, `table`)
284
+ * are registered automatically. Call this to add a new widget type — or to
285
+ * replace a built-in one — without forking `@nubitio/dashboard`.
286
+ *
287
+ * ```ts
288
+ * registerWidgetType('funnel', FunnelWidgetView);
289
+ * ```
290
+ */
291
+ function registerWidgetType(type, component) {
292
+ registry.set(type, component);
293
+ }
294
+ function getWidgetComponent(type) {
295
+ return registry.get(type);
296
+ }
297
+ function isWidgetTypeRegistered(type) {
298
+ return registry.has(type);
299
+ }
300
+ //#endregion
301
+ //#region packages/dashboard/dashboard/chartPalette.ts
302
+ const DEFAULT_CHART_COLORS = [
303
+ "var(--accent-color)",
304
+ "var(--success-color)",
305
+ "var(--warning-color)",
306
+ "var(--info-color)",
307
+ "#6b4fc8",
308
+ "#c2410c"
309
+ ];
310
+ //#endregion
107
311
  //#region packages/dashboard/dashboard/formatValue.ts
108
312
  function formatDashboardValue(value, format = "text") {
109
313
  if (value === null || value === void 0) return "—";
@@ -159,329 +363,269 @@ function resolveArray(source, path) {
159
363
  return value.filter((item) => item !== null && typeof item === "object");
160
364
  }
161
365
  //#endregion
162
- //#region packages/dashboard/dashboard/widgets/BarChartWidgetView.tsx
163
- function toNumber$1(value) {
164
- const numeric = typeof value === "number" ? value : Number(value);
165
- return Number.isFinite(numeric) ? numeric : 0;
166
- }
167
- function BarChartWidgetView({ widget, data, loading }) {
168
- const rows = resolveArray(data, widget.dataPath);
169
- const max = rows.reduce((peak, row) => Math.max(peak, toNumber$1(row[widget.yKey])), 0) || 1;
170
- const height = widget.height ?? 200;
171
- return /* @__PURE__ */ jsx(StatCard, {
172
- title: widget.title,
173
- headerExtra: widget.subtitle ? /* @__PURE__ */ jsx("span", {
174
- className: "nb-dashboard-widget__subtitle",
175
- children: widget.subtitle
176
- }) : void 0,
177
- menuVisible: widget.menuVisible,
178
- isLoading: loading,
179
- className: "nb-dashboard-chart-card",
180
- children: rows.length === 0 ? /* @__PURE__ */ jsx("div", {
181
- className: "nb-dashboard-chart-empty",
182
- children: "No data"
183
- }) : /* @__PURE__ */ jsx("div", {
184
- className: "nb-dashboard-bar-chart",
185
- style: { height },
186
- role: "img",
187
- "aria-label": widget.title,
188
- children: rows.map((row, index) => {
189
- const label = String(row[widget.xKey] ?? "");
190
- const value = toNumber$1(row[widget.yKey]);
191
- return /* @__PURE__ */ jsxs("div", {
192
- className: "nb-dashboard-bar-chart__item",
193
- children: [/* @__PURE__ */ jsx("div", {
194
- className: "nb-dashboard-bar-chart__bar-wrap",
195
- children: /* @__PURE__ */ jsx("div", {
196
- className: "nb-dashboard-bar-chart__bar",
197
- style: { height: `${Math.max(4, value / max * 100)}%` },
198
- title: `${label}: ${formatDashboardValue(value, widget.valueFormat)}`
199
- })
200
- }), /* @__PURE__ */ jsx("span", {
201
- className: "nb-dashboard-bar-chart__label",
202
- children: label
203
- })]
204
- }, `${label}-${index}`);
205
- })
206
- })
366
+ //#region packages/dashboard/dashboard/widgets/WidgetRenderer.tsx
367
+ const isDev = typeof process !== "undefined" && process.env?.NODE_ENV !== "production";
368
+ function WidgetRenderer({ widget, data, loading }) {
369
+ const Component = getWidgetComponent(widget.type);
370
+ if (!Component) {
371
+ if (isDev) console.warn(`[@nubitio/dashboard] No widget registered for type "${widget.type}".`);
372
+ return null;
373
+ }
374
+ return /* @__PURE__ */ jsx(Component, {
375
+ widget,
376
+ data,
377
+ loading
207
378
  });
208
379
  }
209
380
  //#endregion
210
- //#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) {
220
- const numeric = typeof value === "number" ? value : Number(value);
221
- return Number.isFinite(numeric) ? numeric : 0;
222
- }
223
- function DonutChartWidgetView({ widget, data, loading }) {
224
- 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);
227
- const centerValue = widget.centerValuePath !== void 0 ? resolvePath(data, widget.centerValuePath) : total;
228
- const radius = 38;
229
- const stroke = 14;
230
- const circumference = 2 * Math.PI * radius;
231
- const arcs = rows.reduce((segments, row, index) => {
232
- const pct = toNumber(row[widget.valueKey]) / total;
233
- const offset = segments.reduce((sum, segment) => sum + segment.dash, 0);
234
- segments.push({
235
- key: `${String(row[widget.labelKey])}-${index}`,
236
- dash: pct * circumference,
237
- offset,
238
- color: colors[index % colors.length]
239
- });
240
- return segments;
241
- }, []);
242
- return /* @__PURE__ */ jsx(StatCard, {
243
- title: widget.title,
244
- headerExtra: widget.subtitle ? /* @__PURE__ */ jsx("span", {
245
- className: "nb-dashboard-widget__subtitle",
246
- children: widget.subtitle
247
- }) : void 0,
248
- menuVisible: widget.menuVisible,
249
- isLoading: loading,
250
- className: "nb-dashboard-chart-card",
251
- children: rows.length === 0 || total <= 0 ? /* @__PURE__ */ jsx("div", {
252
- className: "nb-dashboard-chart-empty",
253
- children: "No data"
254
- }) : /* @__PURE__ */ jsxs("div", {
255
- className: "nb-dashboard-donut",
256
- children: [/* @__PURE__ */ jsxs("div", {
257
- className: "nb-dashboard-donut__chart",
258
- role: "img",
259
- "aria-label": widget.title,
260
- children: [/* @__PURE__ */ jsxs("svg", {
261
- viewBox: "0 0 100 100",
262
- className: "nb-dashboard-donut__svg",
263
- children: [/* @__PURE__ */ jsx("circle", {
264
- cx: "50",
265
- cy: "50",
266
- r: radius,
267
- fill: "none",
268
- stroke: "var(--surface-3)",
269
- strokeWidth: stroke
270
- }), arcs.map((arc) => /* @__PURE__ */ jsx("circle", {
271
- cx: "50",
272
- cy: "50",
273
- r: radius,
274
- fill: "none",
275
- stroke: arc.color,
276
- strokeWidth: stroke,
277
- strokeDasharray: `${arc.dash} ${circumference - arc.dash}`,
278
- strokeDashoffset: -arc.offset,
279
- transform: "rotate(-90 50 50)",
280
- strokeLinecap: "butt"
281
- }, arc.key))]
282
- }), /* @__PURE__ */ jsxs("div", {
283
- className: "nb-dashboard-donut__center",
284
- children: [widget.centerLabel && /* @__PURE__ */ jsx("span", {
285
- className: "nb-dashboard-donut__center-label",
286
- children: widget.centerLabel
287
- }), /* @__PURE__ */ jsx("span", {
288
- className: "nb-dashboard-donut__center-value",
289
- children: formatDashboardValue(centerValue, widget.valueFormat)
290
- })]
291
- })]
292
- }), widget.showLegend !== false && /* @__PURE__ */ jsx("ul", {
293
- className: "nb-dashboard-donut__legend",
294
- children: rows.map((row, index) => {
295
- const label = String(row[widget.labelKey] ?? "");
296
- const value = toNumber(row[widget.valueKey]);
297
- const pct = total > 0 ? value / total * 100 : 0;
298
- return /* @__PURE__ */ jsxs("li", {
299
- className: "nb-dashboard-donut__legend-item",
300
- children: [
301
- /* @__PURE__ */ jsx("span", {
302
- className: "nb-dashboard-donut__legend-swatch",
303
- style: { background: colors[index % colors.length] }
304
- }),
305
- /* @__PURE__ */ jsx("span", {
306
- className: "nb-dashboard-donut__legend-label",
307
- children: label
308
- }),
309
- /* @__PURE__ */ jsxs("span", {
310
- className: "nb-dashboard-donut__legend-value",
311
- children: [pct.toFixed(0), "%"]
312
- })
313
- ]
314
- }, `${label}-${index}`);
381
+ //#region packages/dashboard/dashboard/DashboardWidgetSlot.tsx
382
+ function DashboardWidgetSlot({ widget, data, loading, editMode, onHide, onMoveUp, onMoveDown, period, periodParamNames = DEFAULT_PERIOD_PARAM_NAMES }) {
383
+ const widgetQuery = useWidgetQuery(widget.query, period, periodParamNames);
384
+ const effectiveData = widgetQuery ? widgetQuery.data : data;
385
+ const effectiveLoading = widgetQuery ? widgetQuery.loading : loading;
386
+ const body = /* @__PURE__ */ jsxs(Fragment, { children: [widgetQuery?.error && /* @__PURE__ */ jsx("div", {
387
+ className: "nb-dashboard-widget-slot__error",
388
+ children: widgetQuery.error
389
+ }), /* @__PURE__ */ jsx(WidgetRenderer, {
390
+ widget,
391
+ data: effectiveData,
392
+ loading: effectiveLoading
393
+ })] });
394
+ if (!editMode) return body;
395
+ return /* @__PURE__ */ jsxs("div", {
396
+ className: "nb-dashboard-widget-slot",
397
+ children: [/* @__PURE__ */ jsxs("div", {
398
+ className: "nb-dashboard-widget-slot__controls",
399
+ children: [
400
+ /* @__PURE__ */ jsx("button", {
401
+ type: "button",
402
+ className: "nb-dashboard-widget-slot__btn",
403
+ "aria-label": `Move ${widget.title} earlier`,
404
+ onClick: onMoveUp,
405
+ children: /* @__PURE__ */ jsx("i", {
406
+ className: "ph ph-caret-up",
407
+ "aria-hidden": "true"
408
+ })
409
+ }),
410
+ /* @__PURE__ */ jsx("button", {
411
+ type: "button",
412
+ className: "nb-dashboard-widget-slot__btn",
413
+ "aria-label": `Move ${widget.title} later`,
414
+ onClick: onMoveDown,
415
+ children: /* @__PURE__ */ jsx("i", {
416
+ className: "ph ph-caret-down",
417
+ "aria-hidden": "true"
418
+ })
419
+ }),
420
+ /* @__PURE__ */ jsx("button", {
421
+ type: "button",
422
+ className: "nb-dashboard-widget-slot__btn nb-dashboard-widget-slot__btn--hide",
423
+ "aria-label": `Hide ${widget.title}`,
424
+ onClick: onHide,
425
+ children: /* @__PURE__ */ jsx("i", {
426
+ className: "ph ph-eye-slash",
427
+ "aria-hidden": "true"
428
+ })
315
429
  })
316
- })]
317
- })
430
+ ]
431
+ }), /* @__PURE__ */ jsx("div", {
432
+ className: "nb-dashboard-widget-slot__body",
433
+ children: body
434
+ })]
318
435
  });
319
436
  }
320
437
  //#endregion
321
- //#region packages/dashboard/dashboard/widgets/StatWidgetView.tsx
322
- function resolveTrend(widget, data) {
323
- if (!widget.trend) return { value: null };
324
- const raw = widget.trend.valuePath !== void 0 ? resolvePath(data, widget.trend.valuePath) : widget.trend.value;
325
- const numeric = typeof raw === "number" ? raw : Number(raw);
438
+ //#region packages/dashboard/dashboard/useDashboardData.ts
439
+ function useDashboardData(dataUrl, refreshInterval, period, periodParamNames = DEFAULT_PERIOD_PARAM_NAMES) {
440
+ const http = useCoreHttpClient();
441
+ const params = period ? {
442
+ [periodParamNames.start]: period.start,
443
+ [periodParamNames.end]: period.end
444
+ } : void 0;
445
+ const query = useQuery({
446
+ queryKey: [
447
+ "nb-dashboard",
448
+ dataUrl,
449
+ params
450
+ ],
451
+ queryFn: async () => {
452
+ return (await http.get(dataUrl, { params })).data;
453
+ },
454
+ enabled: !!dataUrl,
455
+ refetchInterval: refreshInterval,
456
+ retry: false
457
+ });
326
458
  return {
327
- value: Number.isFinite(numeric) ? numeric : null,
328
- label: widget.trend.label,
329
- invert: widget.trend.invertColors
459
+ data: query.data ?? {},
460
+ loading: query.isLoading,
461
+ error: query.error ? query.error instanceof Error ? query.error.message : "Failed to load dashboard" : null,
462
+ refetch: () => {
463
+ query.refetch();
464
+ }
330
465
  };
331
466
  }
332
- function StatWidgetView({ widget, data, loading }) {
333
- const valueText = formatDashboardValue(widget.valuePath !== void 0 ? resolvePath(data, widget.valuePath) : widget.value, widget.format ?? "text");
334
- const trend = resolveTrend(widget, data);
335
- const trendDirection = trend.value === null || trend.value === 0 ? "flat" : trend.value > 0 ? "up" : "down";
336
- const trendClass = trendDirection === "flat" ? "nb-stat-card__delta--flat" : trendDirection === "up" ? trend.invert ? "nb-stat-card__delta--down" : "nb-stat-card__delta--up" : trend.invert ? "nb-stat-card__delta--up" : "nb-stat-card__delta--down";
337
- const trendArrow = trendDirection === "up" ? "▲" : trendDirection === "down" ? "▼" : "—";
338
- const trendText = trend.value === null ? null : `${trendArrow} ${formatDashboardValue(Math.abs(trend.value), "percent")}${trend.label ? ` ${trend.label}` : ""}`;
339
- return /* @__PURE__ */ jsx(StatCard, {
340
- title: widget.title,
341
- menuVisible: widget.menuVisible,
342
- isLoading: loading,
343
- className: `nb-dashboard-stat nb-dashboard-stat--${widget.iconTone ?? "accent"}`,
344
- children: /* @__PURE__ */ jsxs("div", {
345
- className: "nb-dashboard-stat__content",
346
- children: [widget.icon && /* @__PURE__ */ jsx("span", {
347
- className: `nb-dashboard-stat__icon nb-dashboard-stat__icon--${widget.iconTone ?? "accent"}`,
348
- children: /* @__PURE__ */ jsx("i", {
349
- className: `ph ${widget.icon}`,
350
- "aria-hidden": "true"
351
- })
352
- }), /* @__PURE__ */ jsxs("div", {
353
- className: "nb-dashboard-stat__metrics",
354
- children: [/* @__PURE__ */ jsx("span", {
355
- className: "nb-stat-card__value nb-stat-card__value--2xl",
356
- children: valueText
357
- }), trendText && /* @__PURE__ */ jsx("span", {
358
- className: `nb-stat-card__delta ${trendClass}`,
359
- children: trendText
360
- })]
361
- })]
362
- })
363
- });
364
- }
365
467
  //#endregion
366
- //#region packages/dashboard/dashboard/widgets/TableWidgetView.tsx
367
- function renderCell(row, column) {
368
- const raw = row[column.key];
369
- if (column.badge) {
370
- const key = raw == null ? "" : String(raw);
371
- return /* @__PURE__ */ jsx(Badge, {
372
- variant: column.badge[key] ?? "secondary",
373
- size: "sm",
374
- children: column.badgeLabels?.[key] ?? key.replace(/_/g, " ")
375
- });
468
+ //#region packages/dashboard/dashboard/useDashboardLayout.ts
469
+ function storageKey(dashboardId) {
470
+ return `nb-dashboard-layout:${dashboardId}`;
471
+ }
472
+ function readStore(dashboardId) {
473
+ try {
474
+ const raw = window.localStorage.getItem(storageKey(dashboardId));
475
+ return raw ? JSON.parse(raw) : {};
476
+ } catch {
477
+ return {};
376
478
  }
377
- return formatDashboardValue(raw, column.format ?? "text");
378
- }
379
- function TableWidgetView({ widget, data, loading }) {
380
- const rows = resolveArray(data, widget.dataPath);
381
- return /* @__PURE__ */ jsx(StatCard, {
382
- title: widget.title,
383
- headerExtra: /* @__PURE__ */ jsxs("div", {
384
- className: "nb-dashboard-table__header-extra",
385
- children: [widget.subtitle && /* @__PURE__ */ jsx("span", {
386
- className: "nb-dashboard-widget__subtitle",
387
- children: widget.subtitle
388
- }), widget.viewAll && /* @__PURE__ */ jsx(Link, {
389
- to: widget.viewAll.to,
390
- className: "nb-dashboard-table__view-all",
391
- children: widget.viewAll.label ?? "View all"
392
- })]
393
- }),
394
- menuVisible: widget.menuVisible,
395
- isLoading: loading,
396
- className: "nb-dashboard-table-card",
397
- children: rows.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
398
- size: "sm",
399
- icon: "ph ph-table",
400
- title: widget.emptyTitle ?? "No records yet",
401
- description: widget.emptyDescription
402
- }) : /* @__PURE__ */ jsx("div", {
403
- className: "nb-dashboard-table-wrap",
404
- children: /* @__PURE__ */ jsxs("table", {
405
- className: "nb-dashboard-table",
406
- children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: widget.columns.map((column) => /* @__PURE__ */ jsx("th", {
407
- className: column.align ? `nb-dashboard-table__cell--${column.align}` : void 0,
408
- children: column.label
409
- }, column.key)) }) }), /* @__PURE__ */ jsx("tbody", { children: rows.map((row, rowIndex) => /* @__PURE__ */ jsx("tr", { children: widget.columns.map((column) => /* @__PURE__ */ jsx("td", {
410
- className: column.align ? `nb-dashboard-table__cell--${column.align}` : void 0,
411
- children: renderCell(row, column)
412
- }, column.key)) }, rowIndex)) })]
413
- })
414
- })
415
- });
416
479
  }
417
- //#endregion
418
- //#region packages/dashboard/dashboard/widgets/WidgetRenderer.tsx
419
- 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
480
+ function writeStore(dashboardId, store) {
481
+ try {
482
+ window.localStorage.setItem(storageKey(dashboardId), JSON.stringify(store));
483
+ } catch {}
484
+ }
485
+ function useDashboardLayout(dashboardId, sections, enabled) {
486
+ const [editMode, setEditMode] = useState(false);
487
+ const id = dashboardId ?? "dashboard";
488
+ const [store, setStore] = useState(() => enabled ? readStore(id) : {});
489
+ const updateSection = useCallback((sectionId, updater) => {
490
+ setStore((prev) => {
491
+ const current = prev[sectionId] ?? {
492
+ order: [],
493
+ hidden: []
494
+ };
495
+ const next = {
496
+ ...prev,
497
+ [sectionId]: updater(current)
498
+ };
499
+ writeStore(id, next);
500
+ return next;
430
501
  });
431
- case "donut-chart": return /* @__PURE__ */ jsx(DonutChartWidgetView, {
432
- widget,
433
- data,
434
- loading
502
+ }, [id]);
503
+ const getSectionWidgets = useCallback((section, sectionId) => {
504
+ if (!enabled) return section.widgets;
505
+ const layout = store[sectionId];
506
+ if (!layout) return section.widgets;
507
+ const byId = new Map(section.widgets.map((widget) => [widget.id, widget]));
508
+ const ordered = layout.order.map((wid) => byId.get(wid)).filter((w) => !!w);
509
+ const remaining = section.widgets.filter((widget) => !layout.order.includes(widget.id));
510
+ return [...ordered, ...remaining].filter((widget) => !layout.hidden.includes(widget.id));
511
+ }, [enabled, store]);
512
+ const hideWidget = useCallback((sectionId, widgetId) => {
513
+ updateSection(sectionId, (current) => ({
514
+ ...current,
515
+ hidden: current.hidden.includes(widgetId) ? current.hidden : [...current.hidden, widgetId]
516
+ }));
517
+ }, [updateSection]);
518
+ const showWidget = useCallback((sectionId, widgetId) => {
519
+ updateSection(sectionId, (current) => ({
520
+ ...current,
521
+ hidden: current.hidden.filter((wid) => wid !== widgetId)
522
+ }));
523
+ }, [updateSection]);
524
+ const moveWidget = useCallback((sectionId, widgetId, direction) => {
525
+ const section = sections.find((s) => (s.id ?? "") === sectionId);
526
+ if (!section) return;
527
+ updateSection(sectionId, (current) => {
528
+ const base = current.order.length ? current.order : section.widgets.map((w) => w.id);
529
+ const index = base.indexOf(widgetId);
530
+ const targetIndex = index + direction;
531
+ if (index === -1 || targetIndex < 0 || targetIndex >= base.length) return current;
532
+ const order = [...base];
533
+ [order[index], order[targetIndex]] = [order[targetIndex], order[index]];
534
+ return {
535
+ ...current,
536
+ order
537
+ };
435
538
  });
436
- case "table": return /* @__PURE__ */ jsx(TableWidgetView, {
437
- widget,
438
- data,
439
- loading
539
+ }, [sections, updateSection]);
540
+ const resetLayout = useCallback(() => {
541
+ setStore({});
542
+ writeStore(id, {});
543
+ }, [id]);
544
+ const hiddenWidgets = useMemo(() => {
545
+ if (!enabled) return [];
546
+ return sections.flatMap((section) => {
547
+ const sectionId = section.id ?? "";
548
+ const hidden = store[sectionId]?.hidden ?? [];
549
+ return section.widgets.filter((widget) => hidden.includes(widget.id)).map((widget) => ({
550
+ sectionId,
551
+ widget
552
+ }));
440
553
  });
441
- default: return null;
442
- }
554
+ }, [
555
+ enabled,
556
+ sections,
557
+ store
558
+ ]);
559
+ if (!enabled) return void 0;
560
+ return {
561
+ editMode,
562
+ setEditMode,
563
+ getSectionWidgets,
564
+ hiddenWidgets,
565
+ hideWidget,
566
+ showWidget,
567
+ moveWidget,
568
+ resetLayout
569
+ };
443
570
  }
444
571
  //#endregion
445
572
  //#region packages/dashboard/dashboard/DashboardPage.tsx
446
573
  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}`;
574
+ return `nb-dashboard-section nb-dashboard-section--${section.layout ?? "grid"}`;
450
575
  }
451
576
  function sectionStyle(section) {
452
577
  if (section.layout !== "grid" && section.layout !== void 0) return void 0;
453
578
  const columns = typeof section.columns === "number" ? `repeat(${section.columns}, minmax(0, 1fr))` : section.columns;
454
579
  if (!columns) return void 0;
455
- return { gridTemplateColumns: String(columns) };
580
+ return { "--nb-dashboard-columns": String(columns) };
456
581
  }
457
- function DashboardSectionView({ section, data, loading }) {
582
+ function DashboardSectionView({ section, sectionId, data, loading, layout, period, periodParamNames }) {
583
+ const widgets = layout ? layout.getSectionWidgets(section, sectionId) : section.widgets;
458
584
  return /* @__PURE__ */ jsx("section", {
459
585
  className: sectionClassName(section),
460
586
  style: sectionStyle(section),
461
587
  "data-section": section.id,
462
- children: section.widgets.map((widget) => /* @__PURE__ */ jsx(WidgetRenderer, {
588
+ children: widgets.map((widget) => /* @__PURE__ */ jsx(DashboardWidgetSlot, {
463
589
  widget,
464
590
  data,
465
- loading
591
+ loading,
592
+ editMode: !!layout?.editMode,
593
+ onHide: () => layout?.hideWidget(sectionId, widget.id),
594
+ onMoveUp: () => layout?.moveWidget(sectionId, widget.id, -1),
595
+ onMoveDown: () => layout?.moveWidget(sectionId, widget.id, 1),
596
+ period,
597
+ periodParamNames
466
598
  }, widget.id))
467
599
  });
468
600
  }
469
601
  function DashboardPage({ config }) {
470
- const fetched = useDashboardData(config.dataUrl, config.refreshInterval);
471
- const { data, loading, error, refetch } = config.useData?.() ?? fetched;
602
+ const period = useDashboardPeriod(config.period);
603
+ const layout = useDashboardLayout(config.id, config.sections, !!config.customizable);
604
+ const fetched = useDashboardData(config.dataUrl, config.refreshInterval, period?.value, config.period?.paramNames);
605
+ const { data, loading, error, refetch } = config.useData?.(period?.value) ?? fetched;
606
+ const periodParamNames = config.period?.paramNames ?? DEFAULT_PERIOD_PARAM_NAMES;
607
+ const toolbarExtras = /* @__PURE__ */ jsxs(Fragment, { children: [period && /* @__PURE__ */ jsx(DashboardPeriodFilter, { period }), layout && /* @__PURE__ */ jsx(DashboardLayoutControls, { layout })] });
472
608
  return /* @__PURE__ */ jsxs("div", {
473
609
  className: "view-wrapper-scroll nb-dashboard-page",
474
610
  children: [/* @__PURE__ */ jsxs(AppToolbar, {
475
611
  title: config.title,
476
612
  onRefresh: refetch,
613
+ additionalToolbarContent: toolbarExtras,
477
614
  children: [error && /* @__PURE__ */ jsx("div", {
478
615
  className: "nb-dashboard-page__error",
479
616
  children: error
480
- }), config.sections.map((section, index) => /* @__PURE__ */ jsx(DashboardSectionView, {
481
- section,
482
- data,
483
- loading
484
- }, section.id ?? `section-${index}`))]
617
+ }), config.sections.map((section, index) => {
618
+ const sectionId = section.id ?? `section-${index}`;
619
+ return /* @__PURE__ */ jsx(DashboardSectionView, {
620
+ section,
621
+ sectionId,
622
+ data,
623
+ loading,
624
+ layout,
625
+ period: period?.value,
626
+ periodParamNames
627
+ }, sectionId);
628
+ })]
485
629
  }), loading && /* @__PURE__ */ jsx("div", {
486
630
  className: "nb-dashboard-page__loading",
487
631
  "aria-hidden": "true",
@@ -523,5 +667,32 @@ function tableWidget(config) {
523
667
  ...config
524
668
  };
525
669
  }
670
+ function lineChartWidget(config) {
671
+ return {
672
+ type: "line-chart",
673
+ menuVisible: false,
674
+ showGrid: true,
675
+ height: 240,
676
+ ...config
677
+ };
678
+ }
679
+ function areaChartWidget(config) {
680
+ return {
681
+ type: "area-chart",
682
+ menuVisible: false,
683
+ showGrid: true,
684
+ height: 240,
685
+ ...config
686
+ };
687
+ }
688
+ function progressWidget(config) {
689
+ return {
690
+ type: "progress",
691
+ menuVisible: false,
692
+ max: 100,
693
+ format: "number",
694
+ ...config
695
+ };
696
+ }
526
697
  //#endregion
527
- export { DashboardPage, barChartWidget, defineDashboard, donutChartWidget, formatDashboardValue, resolveArray, resolvePath, statWidget, tableWidget, useDashboardData };
698
+ 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 };