@burdenoff/microfe-bigconsole 2026.915.1 → 2026.916.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.
|
@@ -1,115 +1,177 @@
|
|
|
1
|
-
import e from "
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import { useEffect as
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
1
|
+
import { GetParserDocument as e, ListWidgetsByDashboardDocument as t } from "../../../generated/wspace-operations.js";
|
|
2
|
+
import n from "../datasink/DataSinkTableViewer.js";
|
|
3
|
+
import { normalizeWidget as r } from "../../hooks/useWidgetOperations.js";
|
|
4
|
+
import i from "../../hooks/useDataSinkOperations.js";
|
|
5
|
+
import a from "../widgets/WidgetWrapper.js";
|
|
6
|
+
import o from "../DrilldownDashboardRenderer.js";
|
|
7
|
+
import { useEffect as s, useRef as c, useState as l } from "react";
|
|
8
|
+
import { useApolloClient as u } from "@apollo/client/react";
|
|
9
|
+
import { Spinner as d } from "@burdenoff/fe-libs/ui";
|
|
10
|
+
import { jsx as f, jsxs as p } from "react/jsx-runtime";
|
|
10
11
|
//#region src/bigconsole/components/preview/AiPreviewContent.tsx
|
|
11
|
-
var
|
|
12
|
-
function
|
|
13
|
-
return /* @__PURE__ */
|
|
14
|
-
className:
|
|
15
|
-
|
|
12
|
+
var m = 4e3, h = 6e4, g = "flex min-h-[6rem] min-w-0 items-center justify-center gap-2 rounded-card bg-bg-sunken px-3 py-6 text-center text-sm text-text-muted";
|
|
13
|
+
function _({ label: e, testId: t }) {
|
|
14
|
+
return /* @__PURE__ */ p("div", {
|
|
15
|
+
className: g,
|
|
16
|
+
"data-testid": t,
|
|
17
|
+
children: [/* @__PURE__ */ f(d, { className: "size-4 shrink-0" }), e]
|
|
16
18
|
});
|
|
17
19
|
}
|
|
18
|
-
function
|
|
19
|
-
return /* @__PURE__ */
|
|
20
|
-
className:
|
|
20
|
+
function v({ text: e, testId: t }) {
|
|
21
|
+
return /* @__PURE__ */ f("p", {
|
|
22
|
+
className: g,
|
|
23
|
+
"data-testid": t,
|
|
21
24
|
children: e
|
|
22
25
|
});
|
|
23
26
|
}
|
|
24
|
-
function
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
function y({ text: e, testId: t }) {
|
|
28
|
+
return /* @__PURE__ */ f("p", {
|
|
29
|
+
className: `${g} text-status-error-text`,
|
|
30
|
+
"data-testid": t,
|
|
31
|
+
children: e
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
function b(e, t, n) {
|
|
35
|
+
let [r, i] = l(null), [a, o] = l(!!t), [u, d] = l(null), [f, p] = l(t), g = c(e);
|
|
36
|
+
return g.current = e, t !== f && (p(t), i(null), d(null), o(!!t)), s(() => {
|
|
37
|
+
if (!t) return;
|
|
31
38
|
let e = !1, r = Date.now(), a = async () => {
|
|
32
|
-
|
|
33
|
-
|
|
39
|
+
try {
|
|
40
|
+
let t = await g.current();
|
|
41
|
+
if (e) return;
|
|
42
|
+
t != null && i(t), d(null);
|
|
43
|
+
} catch (t) {
|
|
44
|
+
if (e) return;
|
|
45
|
+
d(t instanceof Error ? t : /* @__PURE__ */ Error("Failed to load preview content"));
|
|
46
|
+
} finally {
|
|
47
|
+
e || o(!1);
|
|
48
|
+
}
|
|
34
49
|
};
|
|
35
50
|
a();
|
|
36
|
-
let
|
|
37
|
-
!n || Date.now() - r >
|
|
38
|
-
},
|
|
51
|
+
let s = window.setInterval(() => {
|
|
52
|
+
!n || Date.now() - r > h || typeof document < "u" && document.visibilityState !== "visible" || a();
|
|
53
|
+
}, m);
|
|
39
54
|
return () => {
|
|
40
|
-
e = !0, window.clearInterval(
|
|
55
|
+
e = !0, window.clearInterval(s);
|
|
41
56
|
};
|
|
42
57
|
}, [t, n]), {
|
|
43
58
|
data: r,
|
|
44
|
-
loading: a
|
|
59
|
+
loading: a,
|
|
60
|
+
error: u
|
|
45
61
|
};
|
|
46
62
|
}
|
|
47
|
-
function
|
|
48
|
-
let { getDataSinkData:
|
|
49
|
-
let
|
|
50
|
-
return
|
|
51
|
-
},
|
|
52
|
-
return
|
|
63
|
+
function x({ id: e, live: t }) {
|
|
64
|
+
let { getDataSinkData: r } = i({ skipFetch: !0 }), { data: a, loading: o, error: s } = b(async () => {
|
|
65
|
+
let t = await r({ id: e }, { limit: 50 });
|
|
66
|
+
return t ? t.raw : null;
|
|
67
|
+
}, e, t);
|
|
68
|
+
return e ? s ? /* @__PURE__ */ f(y, {
|
|
69
|
+
text: "Could not load the data sink's rows.",
|
|
70
|
+
testId: "ai-preview-datasink-error"
|
|
71
|
+
}) : o ? /* @__PURE__ */ f(_, {
|
|
72
|
+
label: "Loading the data sink’s data…",
|
|
73
|
+
testId: "ai-preview-datasink-loading"
|
|
74
|
+
}) : /* @__PURE__ */ f("div", {
|
|
53
75
|
"data-testid": "ai-preview-content-datasink",
|
|
54
76
|
className: "min-w-0",
|
|
55
|
-
children: /* @__PURE__ */
|
|
77
|
+
children: /* @__PURE__ */ f(n, {
|
|
56
78
|
data: a,
|
|
57
79
|
maxHeight: "300px"
|
|
58
80
|
})
|
|
59
|
-
}) : /* @__PURE__ */
|
|
81
|
+
}) : /* @__PURE__ */ f(v, {
|
|
82
|
+
text: "Waiting for the data sink to be created…",
|
|
83
|
+
testId: "ai-preview-datasink-waiting"
|
|
84
|
+
});
|
|
60
85
|
}
|
|
61
|
-
function
|
|
62
|
-
return e ? /* @__PURE__ */
|
|
86
|
+
function S({ dashboardId: e }) {
|
|
87
|
+
return e ? /* @__PURE__ */ f("div", {
|
|
63
88
|
"data-testid": "ai-preview-content-dashboard",
|
|
64
89
|
className: "min-w-0",
|
|
65
|
-
children: /* @__PURE__ */
|
|
90
|
+
children: /* @__PURE__ */ f(o, {
|
|
66
91
|
dashboardId: e,
|
|
67
92
|
params: {}
|
|
68
93
|
})
|
|
69
|
-
}) : /* @__PURE__ */
|
|
94
|
+
}) : /* @__PURE__ */ f(v, {
|
|
95
|
+
text: "Waiting for the dashboard to be created…",
|
|
96
|
+
testId: "ai-preview-dashboard-waiting"
|
|
97
|
+
});
|
|
70
98
|
}
|
|
71
|
-
function
|
|
72
|
-
let {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
99
|
+
function C({ parserId: t, live: r }) {
|
|
100
|
+
let a = u(), { getDataSinkData: o } = i({ skipFetch: !0 }), { data: s, loading: c, error: l } = b(async () => {
|
|
101
|
+
if (!t) return null;
|
|
102
|
+
let n = (await a.query({
|
|
103
|
+
query: e,
|
|
104
|
+
variables: { id: t },
|
|
105
|
+
fetchPolicy: "network-only"
|
|
106
|
+
})).data?.parser?.outputKey;
|
|
107
|
+
if (!n) return null;
|
|
108
|
+
let r = await o({ key: n }, { limit: 50 });
|
|
109
|
+
return r ? r.raw : null;
|
|
110
|
+
}, t, r);
|
|
111
|
+
return t ? l ? /* @__PURE__ */ f(y, {
|
|
112
|
+
text: "Could not read the parser's output.",
|
|
113
|
+
testId: "ai-preview-parser-error"
|
|
114
|
+
}) : c ? /* @__PURE__ */ f(_, {
|
|
115
|
+
label: "Loading the parser’s output…",
|
|
116
|
+
testId: "ai-preview-parser-loading"
|
|
117
|
+
}) : /* @__PURE__ */ f("div", {
|
|
77
118
|
"data-testid": "ai-preview-content-parser",
|
|
78
119
|
className: "min-w-0",
|
|
79
|
-
children: /* @__PURE__ */
|
|
80
|
-
data:
|
|
120
|
+
children: /* @__PURE__ */ f(n, {
|
|
121
|
+
data: s,
|
|
81
122
|
maxHeight: "280px"
|
|
82
123
|
})
|
|
83
|
-
}) : /* @__PURE__ */
|
|
124
|
+
}) : /* @__PURE__ */ f(v, {
|
|
125
|
+
text: "No parser in this build — the rows were already shaped.",
|
|
126
|
+
testId: "ai-preview-parser-waiting"
|
|
127
|
+
});
|
|
84
128
|
}
|
|
85
|
-
function
|
|
129
|
+
function w(e) {
|
|
86
130
|
let t = e.toUpperCase();
|
|
87
131
|
return t.includes("METRIC") || t.includes("KPI") || t.includes("CARD") || t.includes("STAT") ? "min(160px, 40vh)" : t.includes("TABLE") || t.includes("LIST") ? "min(280px, 50vh)" : "min(320px, 50vh)";
|
|
88
132
|
}
|
|
89
|
-
function
|
|
90
|
-
let {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
133
|
+
function T(e, n) {
|
|
134
|
+
let i = u(), { data: a, loading: o, error: s } = b(async () => e ? ((await i.query({
|
|
135
|
+
query: t,
|
|
136
|
+
variables: { dashboardId: e },
|
|
137
|
+
fetchPolicy: "network-only"
|
|
138
|
+
})).data?.listWidgetsByDashboard || []).map(r) : null, e, n);
|
|
139
|
+
return {
|
|
140
|
+
widgets: a ?? [],
|
|
141
|
+
loading: o,
|
|
142
|
+
error: s
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function E({ dashboardId: e, live: t }) {
|
|
146
|
+
let { widgets: n, loading: r, error: i } = T(e, t);
|
|
147
|
+
return e ? i ? /* @__PURE__ */ f(y, {
|
|
148
|
+
text: "Could not load this dashboard's widgets.",
|
|
149
|
+
testId: "ai-preview-widget-error"
|
|
150
|
+
}) : r && n.length === 0 ? /* @__PURE__ */ f(_, {
|
|
151
|
+
label: "Loading widgets…",
|
|
152
|
+
testId: "ai-preview-widget-loading"
|
|
153
|
+
}) : n.length === 0 ? /* @__PURE__ */ f(v, {
|
|
154
|
+
text: "No widgets on this dashboard yet.",
|
|
155
|
+
testId: "ai-preview-widget-empty"
|
|
156
|
+
}) : /* @__PURE__ */ f("div", {
|
|
98
157
|
"data-testid": "ai-preview-content-widget",
|
|
99
158
|
className: "flex min-w-0 flex-col gap-list-gap",
|
|
100
|
-
children:
|
|
159
|
+
children: n.map((e) => /* @__PURE__ */ f("div", {
|
|
101
160
|
className: "min-w-0 overflow-hidden rounded-card border border-[var(--color-border-subtle)] bg-bg-canvas",
|
|
102
|
-
style: { height:
|
|
103
|
-
children: /* @__PURE__ */
|
|
161
|
+
style: { height: w(e.type) },
|
|
162
|
+
children: /* @__PURE__ */ f(a, {
|
|
104
163
|
widget: e,
|
|
105
164
|
isLoading: !1,
|
|
106
165
|
error: null,
|
|
107
166
|
filterValues: {}
|
|
108
167
|
})
|
|
109
168
|
}, e.id))
|
|
110
|
-
}) : /* @__PURE__ */
|
|
169
|
+
}) : /* @__PURE__ */ f(v, {
|
|
170
|
+
text: "Waiting for the dashboard — widgets live on it.",
|
|
171
|
+
testId: "ai-preview-widget-waiting"
|
|
172
|
+
});
|
|
111
173
|
}
|
|
112
174
|
//#endregion
|
|
113
|
-
export {
|
|
175
|
+
export { S as DashboardContent, x as DataSinkContent, C as ParserContent, E as WidgetsContent };
|
|
114
176
|
|
|
115
177
|
//# sourceMappingURL=AiPreviewContent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AiPreviewContent.js","names":[],"sources":["../../../../src/bigconsole/components/preview/AiPreviewContent.tsx"],"sourcesContent":["/**\n * Live content renderers for the AI preview tabs.\n *\n * Each tab shows the REAL content of the entity the assistant just built —\n * the data sink's rows, the live dashboard, the parser's transformed output,\n * the rendered widget charts — not a list with an Open button. They reuse the\n * same components the real pages use (DataSinkTableViewer, DrilldownDashboard-\n * Renderer, WidgetWrapper) so what you see in the preview is what you get.\n *\n * These require Apollo + the BigConsole providers, which is why they live only\n * in the full AiPreviewPanel (mounted inside BigConsoleRoot), never in the\n * store-only app-shell mini panel.\n */\nimport { useEffect, useRef, useState } from 'react';\nimport { Spinner } from '@burdenoff/fe-libs/ui';\n\nimport { DataSinkTableViewer } from '../datasink/DataSinkTableViewer';\nimport { DrilldownDashboardRenderer } from '../DrilldownDashboardRenderer';\nimport { WidgetWrapper } from '../widgets/WidgetWrapper';\nimport { useDataSinkOperations } from '../../hooks/useDataSinkOperations';\nimport { useParserOperations } from '../../hooks/useParserOperations';\nimport { useWidgetOperations } from '../../hooks/useWidgetOperations';\n\n/** While the build is live, re-pull content on this cadence so it fills in. */\nconst CONTENT_POLL_MS = 4000;\n/** Stop the live re-pull after this long even if the turn is still running. */\nconst CONTENT_POLL_WINDOW_MS = 60_000;\n\n/**\n * Loading and waiting states share one recessed, height-reserved block so the\n * panel does not jump every time a tab fills in — previously each tab had its\n * own bare paragraph and its own height.\n */\nconst PLACEHOLDER_BOX =\n 'flex min-h-[6rem] min-w-0 items-center justify-center gap-2 rounded-card bg-bg-sunken px-3 py-6 text-center text-sm text-text-muted';\n\nfunction CenteredSpinner({ label }: { label: string }) {\n return (\n <div className={PLACEHOLDER_BOX}>\n <Spinner className=\"size-4 shrink-0\" />\n {label}\n </div>\n );\n}\n\nfunction Waiting({ text }: { text: string }) {\n return <p className={PLACEHOLDER_BOX}>{text}</p>;\n}\n\n/**\n * Fetch-on-mount, then re-fetch every CONTENT_POLL_MS while `live`, bounded to\n * CONTENT_POLL_WINDOW_MS. Returns { data, loading, done }. `fetcher` must be\n * stable-ish; we hold it in a ref so the effect keys only on `key`/`live`.\n */\nfunction useLiveContent<T>(fetcher: () => Promise<T | null>, key: string | undefined, live: boolean) {\n const [data, setData] = useState<T | null>(null);\n const [loading, setLoading] = useState(true);\n const fetcherRef = useRef(fetcher);\n fetcherRef.current = fetcher;\n\n useEffect(() => {\n if (!key) {\n setLoading(false);\n return;\n }\n let cancelled = false;\n const startedAt = Date.now();\n const pull = async () => {\n const result = await fetcherRef.current();\n if (cancelled) return;\n if (result !== null && result !== undefined) setData(result);\n setLoading(false);\n };\n void pull();\n const intervalId = window.setInterval(() => {\n if (!live || Date.now() - startedAt > CONTENT_POLL_WINDOW_MS) return;\n if (typeof document !== 'undefined' && document.visibilityState !== 'visible') return;\n void pull();\n }, CONTENT_POLL_MS);\n return () => {\n cancelled = true;\n window.clearInterval(intervalId);\n };\n }, [key, live]);\n\n return { data, loading };\n}\n\nexport function DataSinkContent({ id, live }: { id?: string; live: boolean }) {\n const { getDataSinkData } = useDataSinkOperations({ skipFetch: true });\n const { data, loading } = useLiveContent(\n async () => {\n const res = await getDataSinkData({ id }, { limit: 50 });\n return res ? res.raw : null;\n },\n id,\n live\n );\n\n if (!id) return <Waiting text=\"Waiting for the data sink to be created…\" />;\n if (loading) return <CenteredSpinner label=\"Loading the data sink’s data…\" />;\n return (\n <div data-testid=\"ai-preview-content-datasink\" className=\"min-w-0\">\n <DataSinkTableViewer data={data} maxHeight=\"300px\" />\n </div>\n );\n}\n\nexport function DashboardContent({ dashboardId }: { dashboardId?: string }) {\n if (!dashboardId) return <Waiting text=\"Waiting for the dashboard to be created…\" />;\n // No inner `max-h + overflow-y-auto`: the panel already owns a vertical\n // scroll, and nesting a second one put two scrollbars in ~440px of space.\n return (\n <div data-testid=\"ai-preview-content-dashboard\" className=\"min-w-0\">\n <DrilldownDashboardRenderer dashboardId={dashboardId} params={{}} />\n </div>\n );\n}\n\nexport function ParserContent({ parserId, live }: { parserId?: string; live: boolean }) {\n const { executeParser } = useParserOperations({ skipFetch: true });\n const { data, loading } = useLiveContent(\n async () => {\n const res = await executeParser(parserId ?? '');\n return res ? res.output : null;\n },\n parserId,\n live\n );\n\n if (!parserId) return <Waiting text=\"No parser in this build — the rows were already shaped.\" />;\n if (loading) return <CenteredSpinner label=\"Running the parser…\" />;\n // The \"Parser output (transformed rows)\" caption used to sit here; it now\n // lives on the section header, so the tab does not label itself twice.\n return (\n <div data-testid=\"ai-preview-content-parser\" className=\"min-w-0\">\n <DataSinkTableViewer data={data} maxHeight=\"280px\" />\n </div>\n );\n}\n\n/**\n * Recharts needs a definite height or it renders 0px tall, but a hard 320px box\n * eats a short viewport whole. `min(px, vh)` keeps the definite height Recharts\n * needs while letting the box shrink on small screens.\n */\nfunction widgetBoxHeight(type: string): string {\n const t = type.toUpperCase();\n if (t.includes('METRIC') || t.includes('KPI') || t.includes('CARD') || t.includes('STAT')) return 'min(160px, 40vh)';\n if (t.includes('TABLE') || t.includes('LIST')) return 'min(280px, 50vh)';\n return 'min(320px, 50vh)';\n}\n\nexport function WidgetsContent({ dashboardId, live }: { dashboardId?: string; live: boolean }) {\n const { widgets, loading, refetch } = useWidgetOperations(undefined, dashboardId, {\n skipFetch: !dashboardId,\n });\n\n const refetchRef = useRef(refetch);\n refetchRef.current = refetch;\n useEffect(() => {\n if (!dashboardId) return;\n const startedAt = Date.now();\n const intervalId = window.setInterval(() => {\n if (!live || Date.now() - startedAt > CONTENT_POLL_WINDOW_MS) return;\n if (typeof document !== 'undefined' && document.visibilityState !== 'visible') return;\n void refetchRef.current();\n }, CONTENT_POLL_MS);\n return () => window.clearInterval(intervalId);\n }, [dashboardId, live]);\n\n if (!dashboardId) return <Waiting text=\"Waiting for the dashboard — widgets live on it.\" />;\n if (loading && widgets.length === 0) return <CenteredSpinner label=\"Loading widgets…\" />;\n if (widgets.length === 0) return <Waiting text=\"No widgets on this dashboard yet.\" />;\n\n return (\n <div data-testid=\"ai-preview-content-widget\" className=\"flex min-w-0 flex-col gap-list-gap\">\n {widgets.map((widget) => (\n <div\n key={widget.id}\n // `border-border-subtle` is registered as a frozen light hex in this\n // shell, so the box kept a light border in dark mode.\n className=\"min-w-0 overflow-hidden rounded-card border border-[var(--color-border-subtle)] bg-bg-canvas\"\n style={{ height: widgetBoxHeight(widget.type) }}\n >\n <WidgetWrapper widget={widget} isLoading={false} error={null} filterValues={{}} />\n </div>\n ))}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAM,IAAkB,KAElB,IAAyB,KAOzB,IACJ;AAEF,SAAS,EAAgB,EAAE,YAA4B;AACrD,QACE,kBAAC,OAAD;EAAK,WAAW;YAAhB,CACE,kBAAC,GAAD,EAAS,WAAU,mBAAoB,CAAA,EACtC,EACG;;;AAIV,SAAS,EAAQ,EAAE,WAA0B;AAC3C,QAAO,kBAAC,KAAD;EAAG,WAAW;YAAkB;EAAS,CAAA;;AAQlD,SAAS,EAAkB,GAAkC,GAAyB,GAAe;CACnG,IAAM,CAAC,GA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M,oBAAqB,CAAA,GACpF,EAAQ,WAAW,IAAU,kBAAC,GAAD,EAAS,MAAK,qCAAsC,CAAA,GAGnF,kBAAC,OAAD;EAAK,eAAY;EAA4B,WAAU;YACpD,EAAQ,KAAK,MACZ,kBAAC,OAAD;GAIE,WAAU;GACV,OAAO,EAAE,QAAQ,EAAgB,EAAO,KAAK,EAAE;aAE/C,kBAAC,GAAD;IAAuB;IAAQ,WAAW;IAAO,OAAO;IAAM,cAAc,EAAE;IAAI,CAAA;GAC9E,EAPC,EAAO,GAOR,CACN;EACE,CAAA,GAjBiB,kBAAC,GAAD,EAAS,MAAK,mDAAoD,CAAA"}
|
|
1
|
+
{"version":3,"file":"AiPreviewContent.js","names":[],"sources":["../../../../src/bigconsole/components/preview/AiPreviewContent.tsx"],"sourcesContent":["/**\n * Live content renderers for the AI preview tabs.\n *\n * Each tab shows the REAL content of the entity the assistant just built —\n * the data sink's rows, the live dashboard, the parser's transformed output,\n * the rendered widget charts — not a list with an Open button. They reuse the\n * same components the real pages use (DataSinkTableViewer, DrilldownDashboard-\n * Renderer, WidgetWrapper) so what you see in the preview is what you get.\n *\n * These require Apollo + the BigConsole providers, which is why they live only\n * in the full AiPreviewPanel (mounted inside BigConsoleRoot), never in the\n * store-only app-shell mini panel.\n *\n * ── BC0 (BOFF-7333; BOFF-7270, BOFF-7271) ────────────────────────────────────\n * A PREVIEW MUST OBSERVE, NEVER MUTATE, AND NEVER PUBLISH.\n *\n * Three defects made this panel change the system it was previewing:\n *\n * 1. The Parser tab polled `executeParser` — a MUTATION — every 4s for 60s,\n * re-running the transform server-side up to ~15 times per turn. It now\n * reads the parser (query), follows its `outputKey`, and reads that sink\n * read-only. Zero mutations.\n * 2. The Widgets tab went through `useWidgetOperations`, which publishes into\n * the GLOBAL widget store — so opening the preview overwrote the widgets an\n * already-open dashboard was rendering. It now holds widgets in local state.\n * 3. `useLiveContent` never reset on key change, so the PREVIOUS entity's rows\n * stayed on screen as though current, and an un-caught rejection left the\n * tab spinning forever with no error surface.\n *\n * ★ Deliberately NOT changed: the other `executeParser` callers\n * (`ParserViewPage`, `CustomWidgetBuilderSheet`, `PropertiesPanel`). Those are\n * user-initiated \"run this parser\" actions where executing IS the intent. Only\n * the passive preview had no business mutating.\n */\nimport { useEffect, useRef, useState } from 'react';\nimport { useApolloClient } from '@apollo/client/react';\nimport { Spinner } from '@burdenoff/fe-libs/ui';\n\nimport { DataSinkTableViewer } from '../datasink/DataSinkTableViewer';\nimport { DrilldownDashboardRenderer } from '../DrilldownDashboardRenderer';\nimport { WidgetWrapper } from '../widgets/WidgetWrapper';\nimport { useDataSinkOperations } from '../../hooks/useDataSinkOperations';\nimport { normalizeWidget } from '../../hooks/useWidgetOperations';\nimport { GetParserDocument, ListWidgetsByDashboardDocument } from '../../../generated/wspace-operations';\nimport type { Parser, Widget } from '../../types';\n\n/** While the build is live, re-pull content on this cadence so it fills in. */\nconst CONTENT_POLL_MS = 4000;\n/** Stop the live re-pull after this long even if the turn is still running. */\nconst CONTENT_POLL_WINDOW_MS = 60_000;\n\n/**\n * Loading and waiting states share one recessed, height-reserved block so the\n * panel does not jump every time a tab fills in — previously each tab had its\n * own bare paragraph and its own height.\n */\nconst PLACEHOLDER_BOX =\n 'flex min-h-[6rem] min-w-0 items-center justify-center gap-2 rounded-card bg-bg-sunken px-3 py-6 text-center text-sm text-text-muted';\n\nfunction CenteredSpinner({ label, testId }: { label: string; testId?: string }) {\n return (\n <div className={PLACEHOLDER_BOX} data-testid={testId}>\n <Spinner className=\"size-4 shrink-0\" />\n {label}\n </div>\n );\n}\n\nfunction Waiting({ text, testId }: { text: string; testId?: string }) {\n return (\n <p className={PLACEHOLDER_BOX} data-testid={testId}>\n {text}\n </p>\n );\n}\n\n/**\n * ★ BC0: the tab had no error surface at all. An un-caught rejection inside the\n * poller left `loading` true forever, so a failed read was indistinguishable\n * from a slow one — and it surfaced as an unhandled promise rejection.\n */\nfunction ErrorBox({ text, testId }: { text: string; testId?: string }) {\n return (\n <p className={`${PLACEHOLDER_BOX} text-status-error-text`} data-testid={testId}>\n {text}\n </p>\n );\n}\n\n/**\n * Fetch-on-mount, then re-fetch every CONTENT_POLL_MS while `live`, bounded to\n * CONTENT_POLL_WINDOW_MS. Returns { data, loading, error }. `fetcher` must be\n * stable-ish; we hold it in a ref so the effect keys only on `key`/`live`.\n *\n * ★★ BC0: RESETS ON KEY CHANGE. Previously `data` survived a key change, so\n * switching to a different entity rendered the PREVIOUS entity's rows as though\n * they were the new one's — with `loading` already false, nothing said otherwise.\n */\nfunction useLiveContent<T>(fetcher: () => Promise<T | null>, key: string | undefined, live: boolean) {\n const [data, setData] = useState<T | null>(null);\n const [loading, setLoading] = useState(Boolean(key));\n const [error, setError] = useState<Error | null>(null);\n const [renderedKey, setRenderedKey] = useState(key);\n const fetcherRef = useRef(fetcher);\n fetcherRef.current = fetcher;\n\n // ★★ The reset happens DURING RENDER, not in an effect. An effect-based reset\n // commits one frame carrying the PREVIOUS entity's rows before clearing them —\n // which is the very defect being fixed here. Adjusting state while rendering is\n // React's supported pattern for \"a prop changed, discard the derived state\": it\n // re-runs this component immediately, before anything reaches the DOM, so the\n // stale rows are never painted. A key going undefined clears the render too.\n if (key !== renderedKey) {\n setRenderedKey(key);\n setData(null);\n setError(null);\n setLoading(Boolean(key));\n }\n\n useEffect(() => {\n if (!key) return;\n\n let cancelled = false;\n const startedAt = Date.now();\n const pull = async () => {\n try {\n const result = await fetcherRef.current();\n if (cancelled) return;\n if (result !== null && result !== undefined) setData(result);\n setError(null);\n } catch (err) {\n if (cancelled) return;\n // A later successful poll clears this, so a transient blip does not\n // strand the tab on an error.\n setError(err instanceof Error ? err : new Error('Failed to load preview content'));\n } finally {\n if (!cancelled) setLoading(false);\n }\n };\n void pull();\n const intervalId = window.setInterval(() => {\n if (!live || Date.now() - startedAt > CONTENT_POLL_WINDOW_MS) return;\n if (typeof document !== 'undefined' && document.visibilityState !== 'visible') return;\n void pull();\n }, CONTENT_POLL_MS);\n return () => {\n cancelled = true;\n window.clearInterval(intervalId);\n };\n }, [key, live]);\n\n return { data, loading, error };\n}\n\nexport function DataSinkContent({ id, live }: { id?: string; live: boolean }) {\n const { getDataSinkData } = useDataSinkOperations({ skipFetch: true });\n const { data, loading, error } = useLiveContent(\n async () => {\n const res = await getDataSinkData({ id }, { limit: 50 });\n return res ? res.raw : null;\n },\n id,\n live\n );\n\n if (!id) return <Waiting text=\"Waiting for the data sink to be created…\" testId=\"ai-preview-datasink-waiting\" />;\n if (error) return <ErrorBox text=\"Could not load the data sink's rows.\" testId=\"ai-preview-datasink-error\" />;\n if (loading) return <CenteredSpinner label=\"Loading the data sink’s data…\" testId=\"ai-preview-datasink-loading\" />;\n return (\n <div data-testid=\"ai-preview-content-datasink\" className=\"min-w-0\">\n <DataSinkTableViewer data={data} maxHeight=\"300px\" />\n </div>\n );\n}\n\nexport function DashboardContent({ dashboardId }: { dashboardId?: string }) {\n if (!dashboardId)\n return <Waiting text=\"Waiting for the dashboard to be created…\" testId=\"ai-preview-dashboard-waiting\" />;\n // No inner `max-h + overflow-y-auto`: the panel already owns a vertical\n // scroll, and nesting a second one put two scrollbars in ~440px of space.\n return (\n <div data-testid=\"ai-preview-content-dashboard\" className=\"min-w-0\">\n <DrilldownDashboardRenderer dashboardId={dashboardId} params={{}} />\n </div>\n );\n}\n\n/**\n * ★★★ BC0 — READ-ONLY. This tab used to call `executeParser`, a mutation, on\n * every poll: ~15 server-side re-executions per turn purely to look at output.\n *\n * A parser writes its transformed rows into a data sink named by its own\n * `outputKey` (`ParserCoreFields`), and `getDataSinkData` accepts `{ key }`. So\n * the output is fully readable without executing anything: read the parser,\n * follow `outputKey`, read the sink.\n *\n * ★ Apollo is queried directly rather than via `useParserOperations.fetchParser`,\n * because that helper calls `addParser()` and would publish into the global\n * parser store — trading defect 2's leak for the same leak one store over.\n */\nexport function ParserContent({ parserId, live }: { parserId?: string; live: boolean }) {\n const client = useApolloClient();\n const { getDataSinkData } = useDataSinkOperations({ skipFetch: true });\n const { data, loading, error } = useLiveContent(\n async () => {\n if (!parserId) return null;\n const res = await client.query<{ parser?: Parser | null }>({\n query: GetParserDocument,\n variables: { id: parserId },\n fetchPolicy: 'network-only',\n });\n const outputKey = res.data?.parser?.outputKey;\n if (!outputKey) return null;\n const sink = await getDataSinkData({ key: outputKey }, { limit: 50 });\n return sink ? sink.raw : null;\n },\n parserId,\n live\n );\n\n if (!parserId)\n return (\n <Waiting text=\"No parser in this build — the rows were already shaped.\" testId=\"ai-preview-parser-waiting\" />\n );\n if (error) return <ErrorBox text=\"Could not read the parser's output.\" testId=\"ai-preview-parser-error\" />;\n // \"Running the parser…\" would now be a lie — nothing is executed.\n if (loading) return <CenteredSpinner label=\"Loading the parser’s output…\" testId=\"ai-preview-parser-loading\" />;\n // The \"Parser output (transformed rows)\" caption used to sit here; it now\n // lives on the section header, so the tab does not label itself twice.\n return (\n <div data-testid=\"ai-preview-content-parser\" className=\"min-w-0\">\n <DataSinkTableViewer data={data} maxHeight=\"280px\" />\n </div>\n );\n}\n\n/**\n * Recharts needs a definite height or it renders 0px tall, but a hard 320px box\n * eats a short viewport whole. `min(px, vh)` keeps the definite height Recharts\n * needs while letting the box shrink on small screens.\n */\nfunction widgetBoxHeight(type: string): string {\n const t = type.toUpperCase();\n if (t.includes('METRIC') || t.includes('KPI') || t.includes('CARD') || t.includes('STAT')) return 'min(160px, 40vh)';\n if (t.includes('TABLE') || t.includes('LIST')) return 'min(280px, 50vh)';\n return 'min(320px, 50vh)';\n}\n\n/**\n * ★★★ BC0 — COMPONENT-LOCAL widgets.\n *\n * `useWidgetOperations` publishes every fetch into the GLOBAL widget store, so\n * merely opening this preview replaced the widget set an already-open dashboard\n * was rendering. The query and the normalisation are reused — `normalizeWidget`\n * is exported from that hook precisely so the two paths cannot drift — but the\n * result stays here, in this component's state.\n *\n * It also inherits `useLiveContent`'s bounded window and visibility check,\n * replacing the bespoke interval this tab used to run.\n */\nfunction usePreviewWidgets(dashboardId: string | undefined, live: boolean) {\n const client = useApolloClient();\n const { data, loading, error } = useLiveContent<Widget[]>(\n async () => {\n if (!dashboardId) return null;\n const result = await client.query<Record<string, unknown>>({\n query: ListWidgetsByDashboardDocument,\n variables: { dashboardId },\n fetchPolicy: 'network-only',\n });\n const list = (result.data?.listWidgetsByDashboard as Record<string, unknown>[]) || [];\n return list.map(normalizeWidget);\n },\n dashboardId,\n live\n );\n return { widgets: data ?? [], loading, error };\n}\n\nexport function WidgetsContent({ dashboardId, live }: { dashboardId?: string; live: boolean }) {\n const { widgets, loading, error } = usePreviewWidgets(dashboardId, live);\n\n if (!dashboardId)\n return <Waiting text=\"Waiting for the dashboard — widgets live on it.\" testId=\"ai-preview-widget-waiting\" />;\n if (error) return <ErrorBox text=\"Could not load this dashboard's widgets.\" testId=\"ai-preview-widget-error\" />;\n if (loading && widgets.length === 0)\n return <CenteredSpinner label=\"Loading widgets…\" testId=\"ai-preview-widget-loading\" />;\n if (widgets.length === 0)\n return <Waiting text=\"No widgets on this dashboard yet.\" testId=\"ai-preview-widget-empty\" />;\n\n return (\n <div data-testid=\"ai-preview-content-widget\" className=\"flex min-w-0 flex-col gap-list-gap\">\n {widgets.map((widget) => (\n <div\n key={widget.id}\n // `border-border-subtle` is registered as a frozen light hex in this\n // shell, so the box kept a light border in dark mode.\n className=\"min-w-0 overflow-hidden rounded-card border border-[var(--color-border-subtle)] bg-bg-canvas\"\n style={{ height: widgetBoxHeight(widget.type) }}\n >\n <WidgetWrapper widget={widget} isLoading={false} error={null} filterValues={{}} />\n </div>\n ))}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;AA+CA,IAAM,IAAkB,KAElB,IAAyB,KAOzB,IACJ;AAEF,SAAS,EAAgB,EAAE,UAAO,aAA8C;AAC9E,QACE,kBAAC,OAAD;EAAK,WAAW;EAAiB,eAAa;YAA9C,CACE,kBAAC,GAAD,EAAS,WAAU,mBAAoB,CAAA,EACtC,EACG;;;AAIV,SAAS,EAAQ,EAAE,SAAM,aAA6C;AACpE,QACE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,QAAQ,EAAgB,EAAO,KAAK,EAAE;aAE/C,kBAAC,GAAD;IAAuB;IAAQ,WAAW;IAAO,OAAO;IAAM,cAAc,EAAE;IAAI,CAAA;GAC9E,EAPC,EAAO,GAOR,CACN;EACE,CAAA,GApBC,kBAAC,GAAD;EAAS,MAAK;EAAkD,QAAO;EAA8B,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useWidgetOperations.js","names":[],"sources":["../../../src/bigconsole/hooks/useWidgetOperations.ts"],"sourcesContent":["/**\n * useWidgetOperations Hook\n *\n * Provides CRUD operations for widgets using GraphQL.\n */\n\nimport { useCallback, useState, useMemo, useEffect } from 'react';\nimport { useApolloClient } from '@apollo/client/react';\nimport type {\n Widget,\n WidgetType,\n WidgetPosition,\n ResponsivePosition,\n ResponsivePositionInput,\n RendererType,\n} from '../types';\nimport { useWidgetStore } from '../store';\nimport { normalizeWidgetTypeForApi, mapFromFederationWidgetType } from '../utils/widgetTypeMapping';\nimport {\n ListWidgetsForPageDocument,\n ListWidgetsByDashboardDocument,\n CreateWidgetDocument,\n UpdateWidgetDocument,\n DeleteWidgetDocument,\n DuplicateWidgetDocument,\n BatchUpdateWidgetPositionsDocument,\n RefreshWidgetDataDocument,\n} from '../../generated/wspace-operations';\nimport { useBigConsoleAnalytics } from './useBigConsoleAnalytics';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ninterface CreateWidgetInput {\n pageId: string;\n dashboardId?: string;\n type: WidgetType;\n title: string;\n description?: string;\n // v2.0: Renderer and template support\n renderer?: RendererType;\n template?: Record<string, unknown> | null;\n // v2.0: Data source fields (DataSink → Parser → Widget)\n dataSinkId?: string;\n datasetId?: string;\n parserId?: string;\n parserRules?: string;\n config?: Record<string, unknown>;\n // Fixed Grid Position (legacy v1.2)\n position: WidgetPosition;\n // Responsive Position (v1.0 spec)\n positionResponsive?: ResponsivePositionInput;\n rowOrder?: number;\n refreshInterval?: number;\n metadata?: Record<string, unknown>;\n}\n\ninterface UpdateWidgetInput {\n id: string;\n title?: string;\n description?: string;\n // v2.0: Renderer and template support\n renderer?: RendererType;\n template?: Record<string, unknown> | null;\n // v2.0: Data source fields (DataSink → Parser → Widget)\n dataSinkId?: string;\n datasetId?: string;\n parserId?: string;\n parserRules?: string;\n config?: Record<string, unknown>;\n // Fixed Grid Position (legacy v1.2)\n position?: WidgetPosition;\n // Responsive Position (v1.0 spec)\n positionResponsive?: ResponsivePositionInput;\n rowOrder?: number;\n refreshInterval?: number | null;\n cacheTTL?: number | null;\n metadata?: Record<string, unknown>;\n}\n\ninterface WidgetOperationsResult {\n // Query state\n loading: boolean;\n error: Error | null;\n widgets: Widget[];\n\n // Operations\n createWidget: (input: CreateWidgetInput) => Promise<Widget | null>;\n updateWidget: (input: UpdateWidgetInput) => Promise<Widget | null>;\n deleteWidget: (id: string) => Promise<boolean>;\n duplicateWidget: (id: string, newPosition?: WidgetPosition, newTitle?: string) => Promise<Widget | null>;\n batchUpdatePositions: (updates: Array<{ id: string; position: WidgetPosition }>) => Promise<boolean>;\n refreshWidgetData: (widgetId: string) => Promise<void>;\n refetch: () => Promise<void>;\n}\n\n// ============================================================================\n// Helper: Normalize widget from GraphQL response\n// ============================================================================\n\nfunction normalizeWidget(widget: Record<string, unknown>): Widget {\n const actions = widget.actions as unknown[] | undefined;\n const metadata = widget.metadata as Record<string, unknown> | undefined;\n const respPos = widget.positionResponsive as Record<string, unknown> | undefined;\n\n // Debug: Log raw widget from GraphQL\n\n // Fixed Grid Position (legacy v1.2)\n const position = (widget.position as WidgetPosition) || {\n x: (widget.positionX as number) ?? 0,\n y: (widget.positionY as number) ?? 0,\n width: (widget.positionWidth as number) ?? 4,\n height: (widget.positionHeight as number) ?? 4,\n };\n\n // Responsive Position (v1.0 spec)\n const positionResponsive: ResponsivePosition | null = respPos\n ? {\n xs: (respPos.xs as number) ?? 12,\n sm: (respPos.sm as number) ?? 6,\n md: (respPos.md as number) ?? 4,\n lg: (respPos.lg as number) ?? 3,\n // xl is optional; fall back to lg when absent (server has no xl tier yet)\n ...(respPos.xl !== undefined && respPos.xl !== null ? { xl: respPos.xl as number } : {}),\n }\n : null;\n\n // Read description from metadata if not directly available\n const description = (widget.description as string) || (metadata?.description as string) || '';\n\n // Get the config object\n const config = (widget.config as Record<string, unknown>) || {};\n\n // Check for stored internal widget type in config (preserves original type like 'gauge', 'progress', etc.)\n // This is needed because multiple internal types map to the same federation type (e.g., gauge -> KPI)\n const internalType = config._internalWidgetType as string | undefined;\n\n return {\n id: widget.id,\n pageId: widget.pageId || 'local',\n dashboardId: widget.dashboardId,\n // Use stored internal type if available, otherwise map from federation type\n type: internalType || mapFromFederationWidgetType((widget.type as string) || 'KPI'),\n title: widget.title || 'Untitled Widget',\n description: description,\n // v2.0: Renderer and template support\n renderer: widget.renderer || 'BIGCONSOLE',\n template: widget.template || null,\n // v2.0: Data source fields (DataSink → Parser → Widget)\n dataSinkId: widget.dataSinkId || null,\n datasetId: widget.datasetId || null,\n parserId: widget.parserId || null,\n parserRules: widget.parserRules || null,\n config: config,\n // Fixed Grid Position (legacy v1.2)\n position,\n positionX: position.x,\n positionY: position.y,\n positionWidth: position.width,\n positionHeight: position.height,\n // Responsive Position (v1.0 spec)\n positionResponsive,\n rowOrder: (widget.rowOrder as number | null) ?? null,\n refreshInterval: widget.refreshInterval,\n lastRefreshedAt: widget.lastRefreshedAt,\n cacheTTL: (widget.cacheTTL as number | null) ?? null,\n metadata: metadata,\n context: widget.context,\n drilldown: widget.drilldown,\n translations: widget.translations || [],\n // v2.0: Widget actions\n actions: actions || [],\n // Include widget data from backend\n data: widget.data || null,\n createdAt: widget.createdAt || new Date().toISOString(),\n updatedAt: widget.updatedAt || new Date().toISOString(),\n } as Widget;\n}\n\n// ============================================================================\n// Hook\n// ============================================================================\n\ninterface UseWidgetOperationsOptions {\n /** Skip auto-fetching widgets on mount (use when parent already fetches) */\n skipFetch?: boolean;\n}\n\nexport function useWidgetOperations(\n pageId?: string,\n dashboardId?: string,\n options: UseWidgetOperationsOptions = {}\n): WidgetOperationsResult {\n const { skipFetch = false } = options;\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Get Apollo Client from context\n const apolloClient = useApolloClient();\n const emitBigConsoleEvent = useBigConsoleAnalytics();\n\n // Store actions\n const widgetsMap = useWidgetStore((state) => state.widgets);\n const setWidgets = useWidgetStore((state) => state.setWidgets);\n const addWidgetToStore = useWidgetStore((state) => state.addWidget);\n const updateWidgetInStore = useWidgetStore((state) => state.updateWidget);\n const removeWidgetFromStore = useWidgetStore((state) => state.removeWidget);\n\n // Get widgets array from store - memoized\n const widgets = useMemo(() => Array.from(widgetsMap.values()), [widgetsMap]);\n\n // Fetch widgets from backend\n const fetchWidgets = useCallback(async () => {\n if (!pageId && !dashboardId) {\n return;\n }\n\n try {\n setLoading(true);\n setError(null);\n\n if (dashboardId) {\n const result = await apolloClient.query<Record<string, unknown>>({\n query: ListWidgetsByDashboardDocument,\n variables: { dashboardId },\n fetchPolicy: 'network-only',\n });\n const widgetsList = (result.data?.listWidgetsByDashboard as Record<string, unknown>[]) || [];\n setWidgets(widgetsList.map(normalizeWidget));\n } else if (pageId) {\n const result = await apolloClient.query<Record<string, unknown>>({\n query: ListWidgetsForPageDocument,\n variables: { pageId },\n fetchPolicy: 'network-only',\n });\n const listResult = result.data?.listWidgets as Record<string, unknown> | undefined;\n const edges = (listResult?.edges as { node: Record<string, unknown> }[]) || [];\n const widgetsList = edges.map((edge: { node: Record<string, unknown> }) => edge.node);\n setWidgets(widgetsList.map(normalizeWidget));\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to fetch widgets');\n setError(error);\n } finally {\n setLoading(false);\n }\n }, [apolloClient, pageId, dashboardId, setWidgets]);\n\n // Fetch on mount and when pageId/dashboardId changes (unless skipFetch is true)\n useEffect(() => {\n if (!skipFetch) {\n fetchWidgets();\n }\n }, [fetchWidgets, skipFetch]);\n\n // Create widget\n const createWidget = useCallback(\n async (input: CreateWidgetInput): Promise<Widget | null> => {\n try {\n setLoading(true);\n setError(null);\n\n // Build mutation input\n // Map internal widget type to federation-accessible type for API calls\n const federationType = normalizeWidgetTypeForApi(input.type);\n\n // Store the original internal widget type in config for proper restoration\n // This is needed because multiple internal types (gauge, progress, text, etc.)\n // map to the same federation type (KPI), but we need to preserve the original\n // type for correct widget rendering\n const configWithInternalType = {\n ...(input.config || {}),\n _internalWidgetType: input.type,\n };\n\n const mutationInput: Record<string, unknown> = {\n pageId: input.pageId,\n type: federationType,\n title: input.title,\n // v2.0: Renderer and template support\n renderer: input.renderer || 'BIGCONSOLE',\n template: input.template || null,\n // v2.0: Data source fields (DataSink → Parser → Widget)\n dataSinkId: input.dataSinkId,\n datasetId: input.datasetId,\n parserId: input.parserId,\n parserRules: input.parserRules,\n config: configWithInternalType,\n // Fixed Grid Position (legacy v1.2)\n position: {\n x: input.position.x,\n y: input.position.y,\n width: input.position.width,\n height: input.position.height,\n },\n refreshInterval: input.refreshInterval,\n metadata: input.metadata,\n };\n\n // Add Responsive Position if provided (v1.0 spec)\n if (input.positionResponsive) {\n mutationInput.positionResponsive = {\n xs: input.positionResponsive.xs ?? 12,\n sm: input.positionResponsive.sm ?? 6,\n md: input.positionResponsive.md ?? 4,\n lg: input.positionResponsive.lg ?? 3,\n };\n }\n\n // Add rowOrder if provided\n if (input.rowOrder !== undefined) {\n mutationInput.rowOrder = input.rowOrder;\n }\n\n emitBigConsoleEvent('bigconsole.widget.create_clicked', {\n dashboardId: input.dashboardId || dashboardId,\n pageId: input.pageId,\n widgetType: input.type,\n });\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: CreateWidgetDocument,\n variables: { input: mutationInput },\n });\n\n const createResult = result.data?.createBigConsoleWidget as Record<string, unknown> | undefined;\n if (createResult) {\n const newWidget = normalizeWidget(createResult);\n addWidgetToStore(newWidget);\n emitBigConsoleEvent('bigconsole.widget.created', {\n dashboardId: newWidget.dashboardId || input.dashboardId || dashboardId,\n pageId: newWidget.pageId,\n widgetId: newWidget.id,\n widgetType: newWidget.type,\n });\n return newWidget;\n }\n\n return null;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to create widget');\n setError(error);\n return null;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, addWidgetToStore, dashboardId, emitBigConsoleEvent]\n );\n\n // Update widget\n const updateWidget = useCallback(\n async (input: UpdateWidgetInput): Promise<Widget | null> => {\n try {\n setLoading(true);\n setError(null);\n\n // Get latest widget from store (avoid stale closure)\n const currentWidgetsMap = useWidgetStore.getState().widgets;\n const existingWidget = currentWidgetsMap.get(input.id);\n if (!existingWidget) {\n throw new Error(`Widget not found: ${input.id}`);\n }\n\n const updateInput: Record<string, unknown> = { id: input.id };\n if (input.title !== undefined) updateInput.title = input.title;\n // v2.0: Renderer and template support\n if (input.renderer !== undefined) updateInput.renderer = input.renderer;\n if (input.template !== undefined) updateInput.template = input.template;\n // v2.0: Data source fields (DataSink → Parser → Widget)\n if (input.dataSinkId !== undefined) updateInput.dataSinkId = input.dataSinkId;\n if (input.datasetId !== undefined) updateInput.datasetId = input.datasetId;\n if (input.parserId !== undefined) updateInput.parserId = input.parserId;\n if (input.parserRules !== undefined) updateInput.parserRules = input.parserRules;\n if (input.config !== undefined) updateInput.config = input.config;\n if (input.refreshInterval !== undefined) updateInput.refreshInterval = input.refreshInterval;\n if (input.metadata !== undefined) updateInput.metadata = input.metadata;\n\n // Fixed Grid Position (legacy v1.2)\n if (input.position) {\n updateInput.position = {\n x: input.position.x,\n y: input.position.y,\n width: input.position.width,\n height: input.position.height,\n };\n }\n\n // Responsive Position (v1.0 spec)\n if (input.positionResponsive) {\n updateInput.positionResponsive = {\n xs: input.positionResponsive.xs,\n sm: input.positionResponsive.sm,\n md: input.positionResponsive.md,\n lg: input.positionResponsive.lg,\n };\n }\n\n // Row order\n if (input.rowOrder !== undefined) {\n updateInput.rowOrder = input.rowOrder;\n }\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: UpdateWidgetDocument,\n variables: { input: updateInput },\n });\n\n if (result.error) {\n throw result.error;\n }\n\n const updateResult = result.data?.updateBigConsoleWidget as Record<string, unknown> | undefined;\n if (updateResult) {\n const updatedWidget = normalizeWidget(updateResult);\n updateWidgetInStore(input.id, updatedWidget);\n return updatedWidget;\n }\n\n return null;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to update widget');\n setError(error);\n return null;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, updateWidgetInStore]\n );\n\n // Delete widget\n const deleteWidget = useCallback(\n async (id: string): Promise<boolean> => {\n try {\n setLoading(true);\n setError(null);\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: DeleteWidgetDocument,\n variables: { id },\n });\n\n if (result.data?.deleteBigConsoleWidget) {\n removeWidgetFromStore(id);\n return true;\n }\n\n return false;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to delete widget');\n setError(error);\n return false;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, removeWidgetFromStore]\n );\n\n // Duplicate widget\n const duplicateWidget = useCallback(\n async (id: string, newPosition?: WidgetPosition, newTitle?: string): Promise<Widget | null> => {\n try {\n setLoading(true);\n setError(null);\n\n // Get latest widget from store (avoid stale closure)\n const currentWidgetsMap = useWidgetStore.getState().widgets;\n const existingWidget = currentWidgetsMap.get(id);\n if (!existingWidget) {\n throw new Error(`Widget not found: ${id}`);\n }\n\n emitBigConsoleEvent('bigconsole.widget.duplicate_clicked', {\n dashboardId: existingWidget.dashboardId || dashboardId,\n pageId: existingWidget.pageId,\n sourceWidgetId: id,\n widgetType: existingWidget.type,\n });\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: DuplicateWidgetDocument,\n variables: {\n id,\n newPosition: newPosition\n ? {\n x: newPosition.x,\n y: newPosition.y,\n width: newPosition.width,\n height: newPosition.height,\n }\n : undefined,\n newTitle,\n },\n });\n\n if (result.error) {\n throw result.error;\n }\n\n const dupResult = result.data?.duplicateWidget as Record<string, unknown> | undefined;\n if (dupResult) {\n const duplicatedWidget = normalizeWidget(dupResult);\n addWidgetToStore(duplicatedWidget);\n emitBigConsoleEvent('bigconsole.widget.duplicated', {\n dashboardId: duplicatedWidget.dashboardId || existingWidget.dashboardId || dashboardId,\n pageId: duplicatedWidget.pageId,\n widgetId: duplicatedWidget.id,\n sourceWidgetId: id,\n widgetType: duplicatedWidget.type,\n });\n return duplicatedWidget;\n }\n\n return null;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to duplicate widget');\n setError(error);\n return null;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, addWidgetToStore, dashboardId, emitBigConsoleEvent]\n );\n\n // Batch update positions\n const batchUpdatePositions = useCallback(\n async (updates: Array<{ id: string; position: WidgetPosition }>): Promise<boolean> => {\n try {\n setLoading(true);\n setError(null);\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: BatchUpdateWidgetPositionsDocument,\n variables: {\n updates: updates.map((u) => ({\n id: u.id,\n position: {\n x: u.position.x,\n y: u.position.y,\n width: u.position.width,\n height: u.position.height,\n },\n })),\n },\n });\n\n if (result.data?.batchUpdateWidgetPositions) {\n // Update local store with results\n updates.forEach((update) => {\n updateWidgetInStore(update.id, {\n position: update.position,\n positionX: update.position.x,\n positionY: update.position.y,\n positionWidth: update.position.width,\n positionHeight: update.position.height,\n updatedAt: new Date().toISOString(),\n });\n });\n return true;\n }\n\n return false;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to batch update positions');\n setError(error);\n return false;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, updateWidgetInStore]\n );\n\n // Refresh widget data\n const refreshWidgetData = useCallback(\n async (widgetId: string): Promise<void> => {\n try {\n await apolloClient.mutate<Record<string, unknown>>({\n mutation: RefreshWidgetDataDocument,\n variables: { widgetId },\n });\n } catch (err) {}\n },\n [apolloClient]\n );\n\n // Refetch\n const refetch = useCallback(async (): Promise<void> => {\n await fetchWidgets();\n }, [fetchWidgets]);\n\n return {\n loading,\n error,\n widgets,\n createWidget,\n updateWidget,\n deleteWidget,\n duplicateWidget,\n batchUpdatePositions,\n refreshWidgetData,\n refetch,\n };\n}\n\nexport default useWidgetOperations;\n"],"mappings":";;;;;;;;AAqGA,SAAS,EAAgB,GAAyC;CAChE,IAAM,IAAU,EAAO,SACjB,IAAW,EAAO,UAClB,IAAU,EAAO,oBAKjB,IAAY,EAAO,YAA+B;EACtD,GAAI,EAAO,aAAwB;EACnC,GAAI,EAAO,aAAwB;EACnC,OAAQ,EAAO,iBAA4B;EAC3C,QAAS,EAAO,kBAA6B;EAC9C,EAGK,IAAgD,IAClD;EACE,IAAK,EAAQ,MAAiB;EAC9B,IAAK,EAAQ,MAAiB;EAC9B,IAAK,EAAQ,MAAiB;EAC9B,IAAK,EAAQ,MAAiB;EAE9B,GAAI,EAAQ,OAAO,KAAA,KAAa,EAAQ,OAAO,OAAO,EAAE,IAAI,EAAQ,IAAc,GAAG,EAAE;EACxF,GACD,MAGE,IAAe,EAAO,eAA2B,GAAU,eAA0B,IAGrF,IAAU,EAAO,UAAsC,EAAE,EAIzD,IAAe,EAAO;AAE5B,QAAO;EACL,IAAI,EAAO;EACX,QAAQ,EAAO,UAAU;EACzB,aAAa,EAAO;EAEpB,MAAM,KAAgB,EAA6B,EAAO,QAAmB,MAAM;EACnF,OAAO,EAAO,SAAS;EACV;EAEb,UAAU,EAAO,YAAY;EAC7B,UAAU,EAAO,YAAY;EAE7B,YAAY,EAAO,cAAc;EACjC,WAAW,EAAO,aAAa;EAC/B,UAAU,EAAO,YAAY;EAC7B,aAAa,EAAO,eAAe;EAC3B;EAER;EACA,WAAW,EAAS;EACpB,WAAW,EAAS;EACpB,eAAe,EAAS;EACxB,gBAAgB,EAAS;EAEzB;EACA,UAAW,EAAO,YAA8B;EAChD,iBAAiB,EAAO;EACxB,iBAAiB,EAAO;EACxB,UAAW,EAAO,YAA8B;EACtC;EACV,SAAS,EAAO;EAChB,WAAW,EAAO;EAClB,cAAc,EAAO,gBAAgB,EA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AAI;AACF,UAAM,EAAa,OAAgC;KACjD,UAAU;KACV,WAAW,EAAE,aAAU;KACxB,CAAC;WACU;KAEhB,CAAC,EAAa,CACf;EAiBC,SAdc,EAAY,YAA2B;AACrD,SAAM,GAAc;KACnB,CAAC,EAAa,CAAC;EAajB"}
|
|
1
|
+
{"version":3,"file":"useWidgetOperations.js","names":[],"sources":["../../../src/bigconsole/hooks/useWidgetOperations.ts"],"sourcesContent":["/**\n * useWidgetOperations Hook\n *\n * Provides CRUD operations for widgets using GraphQL.\n */\n\nimport { useCallback, useState, useMemo, useEffect } from 'react';\nimport { useApolloClient } from '@apollo/client/react';\nimport type {\n Widget,\n WidgetType,\n WidgetPosition,\n ResponsivePosition,\n ResponsivePositionInput,\n RendererType,\n} from '../types';\nimport { useWidgetStore } from '../store';\nimport { normalizeWidgetTypeForApi, mapFromFederationWidgetType } from '../utils/widgetTypeMapping';\nimport {\n ListWidgetsForPageDocument,\n ListWidgetsByDashboardDocument,\n CreateWidgetDocument,\n UpdateWidgetDocument,\n DeleteWidgetDocument,\n DuplicateWidgetDocument,\n BatchUpdateWidgetPositionsDocument,\n RefreshWidgetDataDocument,\n} from '../../generated/wspace-operations';\nimport { useBigConsoleAnalytics } from './useBigConsoleAnalytics';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ninterface CreateWidgetInput {\n pageId: string;\n dashboardId?: string;\n type: WidgetType;\n title: string;\n description?: string;\n // v2.0: Renderer and template support\n renderer?: RendererType;\n template?: Record<string, unknown> | null;\n // v2.0: Data source fields (DataSink → Parser → Widget)\n dataSinkId?: string;\n datasetId?: string;\n parserId?: string;\n parserRules?: string;\n config?: Record<string, unknown>;\n // Fixed Grid Position (legacy v1.2)\n position: WidgetPosition;\n // Responsive Position (v1.0 spec)\n positionResponsive?: ResponsivePositionInput;\n rowOrder?: number;\n refreshInterval?: number;\n metadata?: Record<string, unknown>;\n}\n\ninterface UpdateWidgetInput {\n id: string;\n title?: string;\n description?: string;\n // v2.0: Renderer and template support\n renderer?: RendererType;\n template?: Record<string, unknown> | null;\n // v2.0: Data source fields (DataSink → Parser → Widget)\n dataSinkId?: string;\n datasetId?: string;\n parserId?: string;\n parserRules?: string;\n config?: Record<string, unknown>;\n // Fixed Grid Position (legacy v1.2)\n position?: WidgetPosition;\n // Responsive Position (v1.0 spec)\n positionResponsive?: ResponsivePositionInput;\n rowOrder?: number;\n refreshInterval?: number | null;\n cacheTTL?: number | null;\n metadata?: Record<string, unknown>;\n}\n\ninterface WidgetOperationsResult {\n // Query state\n loading: boolean;\n error: Error | null;\n widgets: Widget[];\n\n // Operations\n createWidget: (input: CreateWidgetInput) => Promise<Widget | null>;\n updateWidget: (input: UpdateWidgetInput) => Promise<Widget | null>;\n deleteWidget: (id: string) => Promise<boolean>;\n duplicateWidget: (id: string, newPosition?: WidgetPosition, newTitle?: string) => Promise<Widget | null>;\n batchUpdatePositions: (updates: Array<{ id: string; position: WidgetPosition }>) => Promise<boolean>;\n refreshWidgetData: (widgetId: string) => Promise<void>;\n refetch: () => Promise<void>;\n}\n\n// ============================================================================\n// Helper: Normalize widget from GraphQL response\n// ============================================================================\n\n/**\n * Shape a raw GraphQL widget into the app's `Widget`.\n *\n * ★ Exported (BC0, BOFF-7333) so the AI preview can render widgets from its OWN\n * local state instead of going through this hook, which publishes into the\n * GLOBAL widget store. Opening the preview used to overwrite the widgets an\n * already-open dashboard was showing. Exporting the pure mapper keeps the two\n * paths on one normalisation rather than letting a copy drift.\n */\nexport function normalizeWidget(widget: Record<string, unknown>): Widget {\n const actions = widget.actions as unknown[] | undefined;\n const metadata = widget.metadata as Record<string, unknown> | undefined;\n const respPos = widget.positionResponsive as Record<string, unknown> | undefined;\n\n // Debug: Log raw widget from GraphQL\n\n // Fixed Grid Position (legacy v1.2)\n const position = (widget.position as WidgetPosition) || {\n x: (widget.positionX as number) ?? 0,\n y: (widget.positionY as number) ?? 0,\n width: (widget.positionWidth as number) ?? 4,\n height: (widget.positionHeight as number) ?? 4,\n };\n\n // Responsive Position (v1.0 spec)\n const positionResponsive: ResponsivePosition | null = respPos\n ? {\n xs: (respPos.xs as number) ?? 12,\n sm: (respPos.sm as number) ?? 6,\n md: (respPos.md as number) ?? 4,\n lg: (respPos.lg as number) ?? 3,\n // xl is optional; fall back to lg when absent (server has no xl tier yet)\n ...(respPos.xl !== undefined && respPos.xl !== null ? { xl: respPos.xl as number } : {}),\n }\n : null;\n\n // Read description from metadata if not directly available\n const description = (widget.description as string) || (metadata?.description as string) || '';\n\n // Get the config object\n const config = (widget.config as Record<string, unknown>) || {};\n\n // Check for stored internal widget type in config (preserves original type like 'gauge', 'progress', etc.)\n // This is needed because multiple internal types map to the same federation type (e.g., gauge -> KPI)\n const internalType = config._internalWidgetType as string | undefined;\n\n return {\n id: widget.id,\n pageId: widget.pageId || 'local',\n dashboardId: widget.dashboardId,\n // Use stored internal type if available, otherwise map from federation type\n type: internalType || mapFromFederationWidgetType((widget.type as string) || 'KPI'),\n title: widget.title || 'Untitled Widget',\n description: description,\n // v2.0: Renderer and template support\n renderer: widget.renderer || 'BIGCONSOLE',\n template: widget.template || null,\n // v2.0: Data source fields (DataSink → Parser → Widget)\n dataSinkId: widget.dataSinkId || null,\n datasetId: widget.datasetId || null,\n parserId: widget.parserId || null,\n parserRules: widget.parserRules || null,\n config: config,\n // Fixed Grid Position (legacy v1.2)\n position,\n positionX: position.x,\n positionY: position.y,\n positionWidth: position.width,\n positionHeight: position.height,\n // Responsive Position (v1.0 spec)\n positionResponsive,\n rowOrder: (widget.rowOrder as number | null) ?? null,\n refreshInterval: widget.refreshInterval,\n lastRefreshedAt: widget.lastRefreshedAt,\n cacheTTL: (widget.cacheTTL as number | null) ?? null,\n metadata: metadata,\n context: widget.context,\n drilldown: widget.drilldown,\n translations: widget.translations || [],\n // v2.0: Widget actions\n actions: actions || [],\n // Include widget data from backend\n data: widget.data || null,\n createdAt: widget.createdAt || new Date().toISOString(),\n updatedAt: widget.updatedAt || new Date().toISOString(),\n } as Widget;\n}\n\n// ============================================================================\n// Hook\n// ============================================================================\n\ninterface UseWidgetOperationsOptions {\n /** Skip auto-fetching widgets on mount (use when parent already fetches) */\n skipFetch?: boolean;\n}\n\nexport function useWidgetOperations(\n pageId?: string,\n dashboardId?: string,\n options: UseWidgetOperationsOptions = {}\n): WidgetOperationsResult {\n const { skipFetch = false } = options;\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Get Apollo Client from context\n const apolloClient = useApolloClient();\n const emitBigConsoleEvent = useBigConsoleAnalytics();\n\n // Store actions\n const widgetsMap = useWidgetStore((state) => state.widgets);\n const setWidgets = useWidgetStore((state) => state.setWidgets);\n const addWidgetToStore = useWidgetStore((state) => state.addWidget);\n const updateWidgetInStore = useWidgetStore((state) => state.updateWidget);\n const removeWidgetFromStore = useWidgetStore((state) => state.removeWidget);\n\n // Get widgets array from store - memoized\n const widgets = useMemo(() => Array.from(widgetsMap.values()), [widgetsMap]);\n\n // Fetch widgets from backend\n const fetchWidgets = useCallback(async () => {\n if (!pageId && !dashboardId) {\n return;\n }\n\n try {\n setLoading(true);\n setError(null);\n\n if (dashboardId) {\n const result = await apolloClient.query<Record<string, unknown>>({\n query: ListWidgetsByDashboardDocument,\n variables: { dashboardId },\n fetchPolicy: 'network-only',\n });\n const widgetsList = (result.data?.listWidgetsByDashboard as Record<string, unknown>[]) || [];\n setWidgets(widgetsList.map(normalizeWidget));\n } else if (pageId) {\n const result = await apolloClient.query<Record<string, unknown>>({\n query: ListWidgetsForPageDocument,\n variables: { pageId },\n fetchPolicy: 'network-only',\n });\n const listResult = result.data?.listWidgets as Record<string, unknown> | undefined;\n const edges = (listResult?.edges as { node: Record<string, unknown> }[]) || [];\n const widgetsList = edges.map((edge: { node: Record<string, unknown> }) => edge.node);\n setWidgets(widgetsList.map(normalizeWidget));\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to fetch widgets');\n setError(error);\n } finally {\n setLoading(false);\n }\n }, [apolloClient, pageId, dashboardId, setWidgets]);\n\n // Fetch on mount and when pageId/dashboardId changes (unless skipFetch is true)\n useEffect(() => {\n if (!skipFetch) {\n fetchWidgets();\n }\n }, [fetchWidgets, skipFetch]);\n\n // Create widget\n const createWidget = useCallback(\n async (input: CreateWidgetInput): Promise<Widget | null> => {\n try {\n setLoading(true);\n setError(null);\n\n // Build mutation input\n // Map internal widget type to federation-accessible type for API calls\n const federationType = normalizeWidgetTypeForApi(input.type);\n\n // Store the original internal widget type in config for proper restoration\n // This is needed because multiple internal types (gauge, progress, text, etc.)\n // map to the same federation type (KPI), but we need to preserve the original\n // type for correct widget rendering\n const configWithInternalType = {\n ...(input.config || {}),\n _internalWidgetType: input.type,\n };\n\n const mutationInput: Record<string, unknown> = {\n pageId: input.pageId,\n type: federationType,\n title: input.title,\n // v2.0: Renderer and template support\n renderer: input.renderer || 'BIGCONSOLE',\n template: input.template || null,\n // v2.0: Data source fields (DataSink → Parser → Widget)\n dataSinkId: input.dataSinkId,\n datasetId: input.datasetId,\n parserId: input.parserId,\n parserRules: input.parserRules,\n config: configWithInternalType,\n // Fixed Grid Position (legacy v1.2)\n position: {\n x: input.position.x,\n y: input.position.y,\n width: input.position.width,\n height: input.position.height,\n },\n refreshInterval: input.refreshInterval,\n metadata: input.metadata,\n };\n\n // Add Responsive Position if provided (v1.0 spec)\n if (input.positionResponsive) {\n mutationInput.positionResponsive = {\n xs: input.positionResponsive.xs ?? 12,\n sm: input.positionResponsive.sm ?? 6,\n md: input.positionResponsive.md ?? 4,\n lg: input.positionResponsive.lg ?? 3,\n };\n }\n\n // Add rowOrder if provided\n if (input.rowOrder !== undefined) {\n mutationInput.rowOrder = input.rowOrder;\n }\n\n emitBigConsoleEvent('bigconsole.widget.create_clicked', {\n dashboardId: input.dashboardId || dashboardId,\n pageId: input.pageId,\n widgetType: input.type,\n });\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: CreateWidgetDocument,\n variables: { input: mutationInput },\n });\n\n const createResult = result.data?.createBigConsoleWidget as Record<string, unknown> | undefined;\n if (createResult) {\n const newWidget = normalizeWidget(createResult);\n addWidgetToStore(newWidget);\n emitBigConsoleEvent('bigconsole.widget.created', {\n dashboardId: newWidget.dashboardId || input.dashboardId || dashboardId,\n pageId: newWidget.pageId,\n widgetId: newWidget.id,\n widgetType: newWidget.type,\n });\n return newWidget;\n }\n\n return null;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to create widget');\n setError(error);\n return null;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, addWidgetToStore, dashboardId, emitBigConsoleEvent]\n );\n\n // Update widget\n const updateWidget = useCallback(\n async (input: UpdateWidgetInput): Promise<Widget | null> => {\n try {\n setLoading(true);\n setError(null);\n\n // Get latest widget from store (avoid stale closure)\n const currentWidgetsMap = useWidgetStore.getState().widgets;\n const existingWidget = currentWidgetsMap.get(input.id);\n if (!existingWidget) {\n throw new Error(`Widget not found: ${input.id}`);\n }\n\n const updateInput: Record<string, unknown> = { id: input.id };\n if (input.title !== undefined) updateInput.title = input.title;\n // v2.0: Renderer and template support\n if (input.renderer !== undefined) updateInput.renderer = input.renderer;\n if (input.template !== undefined) updateInput.template = input.template;\n // v2.0: Data source fields (DataSink → Parser → Widget)\n if (input.dataSinkId !== undefined) updateInput.dataSinkId = input.dataSinkId;\n if (input.datasetId !== undefined) updateInput.datasetId = input.datasetId;\n if (input.parserId !== undefined) updateInput.parserId = input.parserId;\n if (input.parserRules !== undefined) updateInput.parserRules = input.parserRules;\n if (input.config !== undefined) updateInput.config = input.config;\n if (input.refreshInterval !== undefined) updateInput.refreshInterval = input.refreshInterval;\n if (input.metadata !== undefined) updateInput.metadata = input.metadata;\n\n // Fixed Grid Position (legacy v1.2)\n if (input.position) {\n updateInput.position = {\n x: input.position.x,\n y: input.position.y,\n width: input.position.width,\n height: input.position.height,\n };\n }\n\n // Responsive Position (v1.0 spec)\n if (input.positionResponsive) {\n updateInput.positionResponsive = {\n xs: input.positionResponsive.xs,\n sm: input.positionResponsive.sm,\n md: input.positionResponsive.md,\n lg: input.positionResponsive.lg,\n };\n }\n\n // Row order\n if (input.rowOrder !== undefined) {\n updateInput.rowOrder = input.rowOrder;\n }\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: UpdateWidgetDocument,\n variables: { input: updateInput },\n });\n\n if (result.error) {\n throw result.error;\n }\n\n const updateResult = result.data?.updateBigConsoleWidget as Record<string, unknown> | undefined;\n if (updateResult) {\n const updatedWidget = normalizeWidget(updateResult);\n updateWidgetInStore(input.id, updatedWidget);\n return updatedWidget;\n }\n\n return null;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to update widget');\n setError(error);\n return null;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, updateWidgetInStore]\n );\n\n // Delete widget\n const deleteWidget = useCallback(\n async (id: string): Promise<boolean> => {\n try {\n setLoading(true);\n setError(null);\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: DeleteWidgetDocument,\n variables: { id },\n });\n\n if (result.data?.deleteBigConsoleWidget) {\n removeWidgetFromStore(id);\n return true;\n }\n\n return false;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to delete widget');\n setError(error);\n return false;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, removeWidgetFromStore]\n );\n\n // Duplicate widget\n const duplicateWidget = useCallback(\n async (id: string, newPosition?: WidgetPosition, newTitle?: string): Promise<Widget | null> => {\n try {\n setLoading(true);\n setError(null);\n\n // Get latest widget from store (avoid stale closure)\n const currentWidgetsMap = useWidgetStore.getState().widgets;\n const existingWidget = currentWidgetsMap.get(id);\n if (!existingWidget) {\n throw new Error(`Widget not found: ${id}`);\n }\n\n emitBigConsoleEvent('bigconsole.widget.duplicate_clicked', {\n dashboardId: existingWidget.dashboardId || dashboardId,\n pageId: existingWidget.pageId,\n sourceWidgetId: id,\n widgetType: existingWidget.type,\n });\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: DuplicateWidgetDocument,\n variables: {\n id,\n newPosition: newPosition\n ? {\n x: newPosition.x,\n y: newPosition.y,\n width: newPosition.width,\n height: newPosition.height,\n }\n : undefined,\n newTitle,\n },\n });\n\n if (result.error) {\n throw result.error;\n }\n\n const dupResult = result.data?.duplicateWidget as Record<string, unknown> | undefined;\n if (dupResult) {\n const duplicatedWidget = normalizeWidget(dupResult);\n addWidgetToStore(duplicatedWidget);\n emitBigConsoleEvent('bigconsole.widget.duplicated', {\n dashboardId: duplicatedWidget.dashboardId || existingWidget.dashboardId || dashboardId,\n pageId: duplicatedWidget.pageId,\n widgetId: duplicatedWidget.id,\n sourceWidgetId: id,\n widgetType: duplicatedWidget.type,\n });\n return duplicatedWidget;\n }\n\n return null;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to duplicate widget');\n setError(error);\n return null;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, addWidgetToStore, dashboardId, emitBigConsoleEvent]\n );\n\n // Batch update positions\n const batchUpdatePositions = useCallback(\n async (updates: Array<{ id: string; position: WidgetPosition }>): Promise<boolean> => {\n try {\n setLoading(true);\n setError(null);\n\n const result = await apolloClient.mutate<Record<string, unknown>>({\n mutation: BatchUpdateWidgetPositionsDocument,\n variables: {\n updates: updates.map((u) => ({\n id: u.id,\n position: {\n x: u.position.x,\n y: u.position.y,\n width: u.position.width,\n height: u.position.height,\n },\n })),\n },\n });\n\n if (result.data?.batchUpdateWidgetPositions) {\n // Update local store with results\n updates.forEach((update) => {\n updateWidgetInStore(update.id, {\n position: update.position,\n positionX: update.position.x,\n positionY: update.position.y,\n positionWidth: update.position.width,\n positionHeight: update.position.height,\n updatedAt: new Date().toISOString(),\n });\n });\n return true;\n }\n\n return false;\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to batch update positions');\n setError(error);\n return false;\n } finally {\n setLoading(false);\n }\n },\n [apolloClient, updateWidgetInStore]\n );\n\n // Refresh widget data\n const refreshWidgetData = useCallback(\n async (widgetId: string): Promise<void> => {\n try {\n await apolloClient.mutate<Record<string, unknown>>({\n mutation: RefreshWidgetDataDocument,\n variables: { widgetId },\n });\n } catch (err) {}\n },\n [apolloClient]\n );\n\n // Refetch\n const refetch = useCallback(async (): Promise<void> => {\n await fetchWidgets();\n }, [fetchWidgets]);\n\n return {\n loading,\n error,\n widgets,\n createWidget,\n updateWidget,\n deleteWidget,\n duplicateWidget,\n batchUpdatePositions,\n refreshWidgetData,\n refetch,\n };\n}\n\nexport default useWidgetOperations;\n"],"mappings":";;;;;;;;AA8GA,SAAgB,EAAgB,GAAyC;CACvE,IAAM,IAAU,EAAO,SACjB,IAAW,EAAO,UAClB,IAAU,EAAO,oBAKjB,IAAY,EAAO,YAA+B;EACtD,GAAI,EAAO,aAAwB;EACnC,GAAI,EAAO,aAAwB;EACnC,OAAQ,EAAO,iBAA4B;EAC3C,QAAS,EAAO,kBAA6B;EAC9C,EAGK,IAAgD,IAClD;EACE,IAAK,EAAQ,MAAiB;EAC9B,IAAK,EAAQ,MAAiB;EAC9B,IAAK,EAAQ,MAAiB;EAC9B,IAAK,EAAQ,MAAiB;EAE9B,GAAI,EAAQ,OAAO,KAAA,KAAa,EAAQ,OAAO,OAAO,EAAE,IAAI,EAAQ,IAAc,GAAG,EAAE;EACxF,GACD,MAGE,IAAe,EAAO,eAA2B,GAAU,eAA0B,IAGrF,IAAU,EAAO,UAAsC,EAAE,EAIzD,IAAe,EAAO;AAE5B,QAAO;EACL,IAAI,EAAO;EACX,QAAQ,EAAO,UAAU;EACzB,aAAa,EAAO;EAEpB,MAAM,KAAgB,EAA6B,EAAO,QAAmB,MAAM;EACnF,OAAO,EAAO,SAAS;EACV;EAEb,UAAU,EAAO,YAAY;EAC7B,UAAU,EAAO,YAAY;EAE7B,YAAY,EAAO,cAAc;EACjC,WAAW,EAAO,aAAa;EAC/B,UAAU,EAAO,YAAY;EAC7B,aAAa,EAAO,eAAe;EAC3B;EAER;EACA,WAAW,EAAS;EACpB,WAAW,EAAS;EACpB,eAAe,EAAS;EACxB,gBAAgB,EAAS;EAEzB;EACA,U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