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