@xmachines/json-render-react 0.19.0-xm.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +543 -0
- package/dist/chunk-WYDS23XB.mjs +87 -0
- package/dist/chunk-WYDS23XB.mjs.map +1 -0
- package/dist/index.d.mts +762 -0
- package/dist/index.d.ts +762 -0
- package/dist/index.js +1916 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1832 -0
- package/dist/index.mjs.map +1 -0
- package/dist/schema.d.mts +102 -0
- package/dist/schema.d.ts +102 -0
- package/dist/schema.js +112 -0
- package/dist/schema.js.map +1 -0
- package/dist/schema.mjs +9 -0
- package/dist/schema.mjs.map +1 -0
- package/package.json +66 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1916 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
ActionProvider: () => ActionProvider,
|
|
34
|
+
ConfirmDialog: () => ConfirmDialog,
|
|
35
|
+
JSONUIProvider: () => JSONUIProvider,
|
|
36
|
+
Renderer: () => Renderer,
|
|
37
|
+
RepeatScopeProvider: () => RepeatScopeProvider,
|
|
38
|
+
StateProvider: () => StateProvider,
|
|
39
|
+
ValidationProvider: () => ValidationProvider,
|
|
40
|
+
VisibilityProvider: () => VisibilityProvider,
|
|
41
|
+
buildSpecFromParts: () => buildSpecFromParts,
|
|
42
|
+
createRenderer: () => createRenderer,
|
|
43
|
+
createStateStore: () => import_core8.createStateStore,
|
|
44
|
+
defineRegistry: () => defineRegistry,
|
|
45
|
+
elementTreeSchema: () => elementTreeSchema,
|
|
46
|
+
flatToTree: () => flatToTree,
|
|
47
|
+
getTextFromParts: () => getTextFromParts,
|
|
48
|
+
schema: () => schema,
|
|
49
|
+
useAction: () => useAction,
|
|
50
|
+
useActions: () => useActions,
|
|
51
|
+
useBoundProp: () => useBoundProp,
|
|
52
|
+
useChatUI: () => useChatUI,
|
|
53
|
+
useFieldValidation: () => useFieldValidation,
|
|
54
|
+
useIsVisible: () => useIsVisible,
|
|
55
|
+
useJsonRenderMessage: () => useJsonRenderMessage,
|
|
56
|
+
useOptionalValidation: () => useOptionalValidation,
|
|
57
|
+
useRepeatScope: () => useRepeatScope,
|
|
58
|
+
useStateBinding: () => useStateBinding,
|
|
59
|
+
useStateStore: () => useStateStore,
|
|
60
|
+
useStateValue: () => useStateValue,
|
|
61
|
+
useUIStream: () => useUIStream,
|
|
62
|
+
useValidation: () => useValidation,
|
|
63
|
+
useVisibility: () => useVisibility
|
|
64
|
+
});
|
|
65
|
+
module.exports = __toCommonJS(index_exports);
|
|
66
|
+
|
|
67
|
+
// ../react-state/dist/index.mjs
|
|
68
|
+
var import_react = require("react");
|
|
69
|
+
var import_core = require("@xmachines/json-render-core");
|
|
70
|
+
var import_store_utils = require("@xmachines/json-render-core/store-utils");
|
|
71
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
72
|
+
var StateContext = (0, import_react.createContext)(null);
|
|
73
|
+
function computeInitialFlat(isControlled, initialState) {
|
|
74
|
+
if (isControlled) return null;
|
|
75
|
+
if (Object.keys(initialState).length === 0) return {};
|
|
76
|
+
return (0, import_store_utils.flattenToPointers)(initialState);
|
|
77
|
+
}
|
|
78
|
+
function StateProvider({
|
|
79
|
+
store: externalStore,
|
|
80
|
+
initialState = {},
|
|
81
|
+
onStateChange,
|
|
82
|
+
children
|
|
83
|
+
}) {
|
|
84
|
+
const internalStoreRef = (0, import_react.useRef)(void 0);
|
|
85
|
+
if (!externalStore && !internalStoreRef.current) {
|
|
86
|
+
internalStoreRef.current = (0, import_core.createStateStore)(initialState);
|
|
87
|
+
}
|
|
88
|
+
const store = externalStore ?? internalStoreRef.current;
|
|
89
|
+
const storeRef = (0, import_react.useRef)(store);
|
|
90
|
+
storeRef.current = store;
|
|
91
|
+
const isControlledRef = (0, import_react.useRef)(!!externalStore);
|
|
92
|
+
isControlledRef.current = !!externalStore;
|
|
93
|
+
const initialModeRef = (0, import_react.useRef)(externalStore ? "controlled" : "uncontrolled");
|
|
94
|
+
const modeWarnedRef = (0, import_react.useRef)(false);
|
|
95
|
+
if (process.env.NODE_ENV !== "production") {
|
|
96
|
+
const currentMode = externalStore ? "controlled" : "uncontrolled";
|
|
97
|
+
if (currentMode !== initialModeRef.current && !modeWarnedRef.current) {
|
|
98
|
+
modeWarnedRef.current = true;
|
|
99
|
+
console.warn(
|
|
100
|
+
`StateProvider: switching from ${initialModeRef.current} to ${currentMode} mode is not supported.`
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const prevInitialStateRef = (0, import_react.useRef)(initialState);
|
|
105
|
+
const prevFlatRef = (0, import_react.useRef)(
|
|
106
|
+
computeInitialFlat(!!externalStore, initialState)
|
|
107
|
+
);
|
|
108
|
+
(0, import_react.useEffect)(() => {
|
|
109
|
+
if (externalStore) return;
|
|
110
|
+
if (initialState === prevInitialStateRef.current) return;
|
|
111
|
+
prevInitialStateRef.current = initialState;
|
|
112
|
+
const nextFlat = initialState && Object.keys(initialState).length > 0 ? (0, import_store_utils.flattenToPointers)(initialState) : {};
|
|
113
|
+
const prevFlat = prevFlatRef.current ?? {};
|
|
114
|
+
const allKeys = /* @__PURE__ */ new Set([
|
|
115
|
+
...Object.keys(prevFlat),
|
|
116
|
+
...Object.keys(nextFlat)
|
|
117
|
+
]);
|
|
118
|
+
const updates = {};
|
|
119
|
+
for (const key of allKeys) {
|
|
120
|
+
if (prevFlat[key] !== nextFlat[key]) {
|
|
121
|
+
updates[key] = key in nextFlat ? nextFlat[key] : void 0;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
prevFlatRef.current = nextFlat;
|
|
125
|
+
if (Object.keys(updates).length > 0) {
|
|
126
|
+
store.update(updates);
|
|
127
|
+
}
|
|
128
|
+
}, [externalStore, initialState, store]);
|
|
129
|
+
const state = (0, import_react.useSyncExternalStore)(
|
|
130
|
+
store.subscribe,
|
|
131
|
+
store.getSnapshot,
|
|
132
|
+
store.getServerSnapshot ?? store.getSnapshot
|
|
133
|
+
);
|
|
134
|
+
const onStateChangeRef = (0, import_react.useRef)(onStateChange);
|
|
135
|
+
onStateChangeRef.current = onStateChange;
|
|
136
|
+
const set = (0, import_react.useCallback)((path, value2) => {
|
|
137
|
+
const s = storeRef.current;
|
|
138
|
+
const prev = s.getSnapshot();
|
|
139
|
+
s.set(path, value2);
|
|
140
|
+
if (!isControlledRef.current && s.getSnapshot() !== prev) {
|
|
141
|
+
onStateChangeRef.current?.([{ path, value: value2 }]);
|
|
142
|
+
}
|
|
143
|
+
}, []);
|
|
144
|
+
const update = (0, import_react.useCallback)((updates) => {
|
|
145
|
+
const s = storeRef.current;
|
|
146
|
+
const prev = s.getSnapshot();
|
|
147
|
+
s.update(updates);
|
|
148
|
+
if (!isControlledRef.current && s.getSnapshot() !== prev) {
|
|
149
|
+
const changes = [];
|
|
150
|
+
for (const [path, value2] of Object.entries(updates)) {
|
|
151
|
+
if ((0, import_core.getByPath)(prev, path) !== value2) {
|
|
152
|
+
changes.push({ path, value: value2 });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (changes.length > 0) {
|
|
156
|
+
onStateChangeRef.current?.(changes);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}, []);
|
|
160
|
+
const get = (0, import_react.useCallback)((path) => storeRef.current.get(path), []);
|
|
161
|
+
const getSnapshot = (0, import_react.useCallback)(() => storeRef.current.getSnapshot(), []);
|
|
162
|
+
const value = (0, import_react.useMemo)(
|
|
163
|
+
() => ({ state, get, set, update, getSnapshot }),
|
|
164
|
+
[state, get, set, update, getSnapshot]
|
|
165
|
+
);
|
|
166
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StateContext.Provider, { value, children });
|
|
167
|
+
}
|
|
168
|
+
function useStateStore() {
|
|
169
|
+
const ctx = (0, import_react.useContext)(StateContext);
|
|
170
|
+
if (!ctx) {
|
|
171
|
+
throw new Error("useStateStore must be used within a StateProvider");
|
|
172
|
+
}
|
|
173
|
+
return ctx;
|
|
174
|
+
}
|
|
175
|
+
function useStateValue(path) {
|
|
176
|
+
const { state } = useStateStore();
|
|
177
|
+
return (0, import_core.getByPath)(state, path);
|
|
178
|
+
}
|
|
179
|
+
function useStateBinding(path) {
|
|
180
|
+
const { state, set } = useStateStore();
|
|
181
|
+
const value = (0, import_core.getByPath)(state, path);
|
|
182
|
+
const setValue = (0, import_react.useCallback)(
|
|
183
|
+
(newValue) => set(path, newValue),
|
|
184
|
+
[path, set]
|
|
185
|
+
);
|
|
186
|
+
return [value, setValue];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// src/contexts/visibility.tsx
|
|
190
|
+
var import_react2 = require("react");
|
|
191
|
+
var import_core2 = require("@xmachines/json-render-core");
|
|
192
|
+
var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
193
|
+
var VisibilityContext = (0, import_react2.createContext)(null);
|
|
194
|
+
function VisibilityProvider({ children }) {
|
|
195
|
+
const { state } = useStateStore();
|
|
196
|
+
const ctx = (0, import_react2.useMemo)(
|
|
197
|
+
() => ({
|
|
198
|
+
stateModel: state
|
|
199
|
+
}),
|
|
200
|
+
[state]
|
|
201
|
+
);
|
|
202
|
+
const isVisible = (0, import_react2.useMemo)(
|
|
203
|
+
() => (condition) => (0, import_core2.evaluateVisibility)(condition, ctx),
|
|
204
|
+
[ctx]
|
|
205
|
+
);
|
|
206
|
+
const value = (0, import_react2.useMemo)(
|
|
207
|
+
() => ({ isVisible, ctx }),
|
|
208
|
+
[isVisible, ctx]
|
|
209
|
+
);
|
|
210
|
+
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(VisibilityContext.Provider, { value, children });
|
|
211
|
+
}
|
|
212
|
+
function useVisibility() {
|
|
213
|
+
const ctx = (0, import_react2.useContext)(VisibilityContext);
|
|
214
|
+
if (!ctx) {
|
|
215
|
+
throw new Error("useVisibility must be used within a VisibilityProvider");
|
|
216
|
+
}
|
|
217
|
+
return ctx;
|
|
218
|
+
}
|
|
219
|
+
function useIsVisible(condition) {
|
|
220
|
+
const { isVisible } = useVisibility();
|
|
221
|
+
return isVisible(condition);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// src/contexts/actions.tsx
|
|
225
|
+
var import_react4 = require("react");
|
|
226
|
+
var import_core4 = require("@xmachines/json-render-core");
|
|
227
|
+
|
|
228
|
+
// src/contexts/validation.tsx
|
|
229
|
+
var import_react3 = __toESM(require("react"));
|
|
230
|
+
var import_core3 = require("@xmachines/json-render-core");
|
|
231
|
+
var import_jsx_runtime3 = require("react/jsx-runtime");
|
|
232
|
+
var ValidationContext = (0, import_react3.createContext)(null);
|
|
233
|
+
function dynamicArgsEqual(a, b) {
|
|
234
|
+
if (a === b) return true;
|
|
235
|
+
if (!a || !b) return false;
|
|
236
|
+
const keysA = Object.keys(a);
|
|
237
|
+
const keysB = Object.keys(b);
|
|
238
|
+
if (keysA.length !== keysB.length) return false;
|
|
239
|
+
for (const key of keysA) {
|
|
240
|
+
const va = a[key];
|
|
241
|
+
const vb = b[key];
|
|
242
|
+
if (va === vb) continue;
|
|
243
|
+
if (typeof va === "object" && va !== null && typeof vb === "object" && vb !== null) {
|
|
244
|
+
const sa = va.$state;
|
|
245
|
+
const sb = vb.$state;
|
|
246
|
+
if (typeof sa === "string" && sa === sb) continue;
|
|
247
|
+
}
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
function validationConfigEqual(a, b) {
|
|
253
|
+
if (a === b) return true;
|
|
254
|
+
if (a.validateOn !== b.validateOn) return false;
|
|
255
|
+
const ac = a.checks ?? [];
|
|
256
|
+
const bc = b.checks ?? [];
|
|
257
|
+
if (ac.length !== bc.length) return false;
|
|
258
|
+
for (let i = 0; i < ac.length; i++) {
|
|
259
|
+
const ca = ac[i];
|
|
260
|
+
const cb = bc[i];
|
|
261
|
+
if (ca.type !== cb.type) return false;
|
|
262
|
+
if (ca.message !== cb.message) return false;
|
|
263
|
+
if (!dynamicArgsEqual(ca.args, cb.args)) return false;
|
|
264
|
+
}
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
function ValidationProvider({
|
|
268
|
+
customFunctions = {},
|
|
269
|
+
children
|
|
270
|
+
}) {
|
|
271
|
+
const { state, getSnapshot } = useStateStore();
|
|
272
|
+
const [fieldStates, setFieldStates] = (0, import_react3.useState)({});
|
|
273
|
+
const fieldStatesRef = (0, import_react3.useRef)({});
|
|
274
|
+
const [fieldConfigs, setFieldConfigs] = (0, import_react3.useState)({});
|
|
275
|
+
const registerField = (0, import_react3.useCallback)(
|
|
276
|
+
(path, config) => {
|
|
277
|
+
setFieldConfigs((prev) => {
|
|
278
|
+
const existing = prev[path];
|
|
279
|
+
if (existing && validationConfigEqual(existing, config)) {
|
|
280
|
+
return prev;
|
|
281
|
+
}
|
|
282
|
+
return { ...prev, [path]: config };
|
|
283
|
+
});
|
|
284
|
+
},
|
|
285
|
+
[]
|
|
286
|
+
);
|
|
287
|
+
const validate = (0, import_react3.useCallback)(
|
|
288
|
+
(path, config) => {
|
|
289
|
+
const currentState = getSnapshot();
|
|
290
|
+
const segments = path.split("/").filter(Boolean);
|
|
291
|
+
let value2 = currentState;
|
|
292
|
+
for (const seg of segments) {
|
|
293
|
+
if (value2 != null && typeof value2 === "object") {
|
|
294
|
+
value2 = value2[seg];
|
|
295
|
+
} else {
|
|
296
|
+
value2 = void 0;
|
|
297
|
+
break;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const result = (0, import_core3.runValidation)(config, {
|
|
301
|
+
value: value2,
|
|
302
|
+
stateModel: currentState,
|
|
303
|
+
customFunctions
|
|
304
|
+
});
|
|
305
|
+
const newFieldState = {
|
|
306
|
+
touched: fieldStatesRef.current[path]?.touched ?? true,
|
|
307
|
+
validated: true,
|
|
308
|
+
result
|
|
309
|
+
};
|
|
310
|
+
fieldStatesRef.current = {
|
|
311
|
+
...fieldStatesRef.current,
|
|
312
|
+
[path]: newFieldState
|
|
313
|
+
};
|
|
314
|
+
setFieldStates(fieldStatesRef.current);
|
|
315
|
+
return result;
|
|
316
|
+
},
|
|
317
|
+
[customFunctions, getSnapshot]
|
|
318
|
+
);
|
|
319
|
+
const touch = (0, import_react3.useCallback)((path) => {
|
|
320
|
+
fieldStatesRef.current = {
|
|
321
|
+
...fieldStatesRef.current,
|
|
322
|
+
[path]: {
|
|
323
|
+
...fieldStatesRef.current[path],
|
|
324
|
+
touched: true,
|
|
325
|
+
validated: fieldStatesRef.current[path]?.validated ?? false,
|
|
326
|
+
result: fieldStatesRef.current[path]?.result ?? null
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
setFieldStates(fieldStatesRef.current);
|
|
330
|
+
}, []);
|
|
331
|
+
const clear = (0, import_react3.useCallback)((path) => {
|
|
332
|
+
const { [path]: _, ...rest } = fieldStatesRef.current;
|
|
333
|
+
fieldStatesRef.current = rest;
|
|
334
|
+
setFieldStates(rest);
|
|
335
|
+
}, []);
|
|
336
|
+
const validateAll = (0, import_react3.useCallback)(() => {
|
|
337
|
+
let allValid = true;
|
|
338
|
+
for (const [path, config] of Object.entries(fieldConfigs)) {
|
|
339
|
+
const result = validate(path, config);
|
|
340
|
+
if (!result.valid) {
|
|
341
|
+
allValid = false;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return allValid;
|
|
345
|
+
}, [fieldConfigs, validate]);
|
|
346
|
+
const value = (0, import_react3.useMemo)(
|
|
347
|
+
() => ({
|
|
348
|
+
customFunctions,
|
|
349
|
+
// Getter returns the mutable ref so callers that read fieldStates
|
|
350
|
+
// synchronously after validateAll() see the latest values.
|
|
351
|
+
get fieldStates() {
|
|
352
|
+
return fieldStatesRef.current;
|
|
353
|
+
},
|
|
354
|
+
validate,
|
|
355
|
+
touch,
|
|
356
|
+
clear,
|
|
357
|
+
validateAll,
|
|
358
|
+
registerField
|
|
359
|
+
}),
|
|
360
|
+
[
|
|
361
|
+
customFunctions,
|
|
362
|
+
// fieldStates (React state) stays in deps so the context value object
|
|
363
|
+
// is recreated on re-render, triggering downstream consumers.
|
|
364
|
+
fieldStates,
|
|
365
|
+
validate,
|
|
366
|
+
touch,
|
|
367
|
+
clear,
|
|
368
|
+
validateAll,
|
|
369
|
+
registerField
|
|
370
|
+
]
|
|
371
|
+
);
|
|
372
|
+
return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ValidationContext.Provider, { value, children });
|
|
373
|
+
}
|
|
374
|
+
function useValidation() {
|
|
375
|
+
const ctx = (0, import_react3.useContext)(ValidationContext);
|
|
376
|
+
if (!ctx) {
|
|
377
|
+
throw new Error("useValidation must be used within a ValidationProvider");
|
|
378
|
+
}
|
|
379
|
+
return ctx;
|
|
380
|
+
}
|
|
381
|
+
function useOptionalValidation() {
|
|
382
|
+
return (0, import_react3.useContext)(ValidationContext);
|
|
383
|
+
}
|
|
384
|
+
function useFieldValidation(path, config) {
|
|
385
|
+
const {
|
|
386
|
+
fieldStates,
|
|
387
|
+
validate: validateField,
|
|
388
|
+
touch: touchField,
|
|
389
|
+
clear: clearField,
|
|
390
|
+
registerField
|
|
391
|
+
} = useValidation();
|
|
392
|
+
import_react3.default.useEffect(() => {
|
|
393
|
+
if (path && config) {
|
|
394
|
+
registerField(path, config);
|
|
395
|
+
}
|
|
396
|
+
}, [path, config, registerField]);
|
|
397
|
+
const state = fieldStates[path] ?? {
|
|
398
|
+
touched: false,
|
|
399
|
+
validated: false,
|
|
400
|
+
result: null
|
|
401
|
+
};
|
|
402
|
+
const validate = (0, import_react3.useCallback)(
|
|
403
|
+
() => validateField(path, config ?? { checks: [] }),
|
|
404
|
+
[path, config, validateField]
|
|
405
|
+
);
|
|
406
|
+
const touch = (0, import_react3.useCallback)(() => touchField(path), [path, touchField]);
|
|
407
|
+
const clear = (0, import_react3.useCallback)(() => clearField(path), [path, clearField]);
|
|
408
|
+
return {
|
|
409
|
+
state,
|
|
410
|
+
validate,
|
|
411
|
+
touch,
|
|
412
|
+
clear,
|
|
413
|
+
errors: state.result?.errors ?? [],
|
|
414
|
+
isValid: state.result?.valid ?? true
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// src/contexts/actions.tsx
|
|
419
|
+
var import_jsx_runtime4 = require("react/jsx-runtime");
|
|
420
|
+
var idCounter = 0;
|
|
421
|
+
function generateUniqueId() {
|
|
422
|
+
idCounter += 1;
|
|
423
|
+
return `${Date.now()}-${idCounter}`;
|
|
424
|
+
}
|
|
425
|
+
function deepResolveValue(value, get) {
|
|
426
|
+
if (value === null || value === void 0) return value;
|
|
427
|
+
if (value === "$id") {
|
|
428
|
+
return generateUniqueId();
|
|
429
|
+
}
|
|
430
|
+
if (typeof value === "object" && !Array.isArray(value)) {
|
|
431
|
+
const obj = value;
|
|
432
|
+
const keys = Object.keys(obj);
|
|
433
|
+
if (keys.length === 1 && typeof obj.$state === "string") {
|
|
434
|
+
return get(obj.$state);
|
|
435
|
+
}
|
|
436
|
+
if (keys.length === 1 && "$id" in obj) {
|
|
437
|
+
return generateUniqueId();
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
if (Array.isArray(value)) {
|
|
441
|
+
return value.map((item) => deepResolveValue(item, get));
|
|
442
|
+
}
|
|
443
|
+
if (typeof value === "object") {
|
|
444
|
+
const resolved = {};
|
|
445
|
+
for (const [key, val] of Object.entries(value)) {
|
|
446
|
+
resolved[key] = deepResolveValue(val, get);
|
|
447
|
+
}
|
|
448
|
+
return resolved;
|
|
449
|
+
}
|
|
450
|
+
return value;
|
|
451
|
+
}
|
|
452
|
+
var ActionContext = (0, import_react4.createContext)(null);
|
|
453
|
+
function ActionProvider({
|
|
454
|
+
handlers: initialHandlers = {},
|
|
455
|
+
navigate,
|
|
456
|
+
children
|
|
457
|
+
}) {
|
|
458
|
+
const { get, set, getSnapshot } = useStateStore();
|
|
459
|
+
const validation = useOptionalValidation();
|
|
460
|
+
const [handlers, setHandlers] = (0, import_react4.useState)(initialHandlers);
|
|
461
|
+
const [loadingActions, setLoadingActions] = (0, import_react4.useState)(/* @__PURE__ */ new Set());
|
|
462
|
+
const [pendingConfirmation, setPendingConfirmation] = (0, import_react4.useState)(null);
|
|
463
|
+
const registerHandler = (0, import_react4.useCallback)(
|
|
464
|
+
(name, handler) => {
|
|
465
|
+
setHandlers((prev) => ({ ...prev, [name]: handler }));
|
|
466
|
+
},
|
|
467
|
+
[]
|
|
468
|
+
);
|
|
469
|
+
const execute = (0, import_react4.useCallback)(
|
|
470
|
+
async (binding) => {
|
|
471
|
+
const resolved = (0, import_core4.resolveAction)(binding, getSnapshot());
|
|
472
|
+
const dispatchId = (0, import_core4.nextActionDispatchId)();
|
|
473
|
+
const dispatchedAt = Date.now();
|
|
474
|
+
(0, import_core4.notifyActionDispatch)({
|
|
475
|
+
id: dispatchId,
|
|
476
|
+
name: resolved.action,
|
|
477
|
+
params: resolved.params,
|
|
478
|
+
at: dispatchedAt
|
|
479
|
+
});
|
|
480
|
+
let __ok = true;
|
|
481
|
+
let __error = void 0;
|
|
482
|
+
try {
|
|
483
|
+
if (resolved.action === "setState" && resolved.params) {
|
|
484
|
+
const statePath = resolved.params.statePath;
|
|
485
|
+
const value2 = resolved.params.value;
|
|
486
|
+
if (statePath) {
|
|
487
|
+
set(statePath, value2);
|
|
488
|
+
}
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (resolved.action === "pushState" && resolved.params) {
|
|
492
|
+
const statePath = resolved.params.statePath;
|
|
493
|
+
const rawValue = resolved.params.value;
|
|
494
|
+
if (statePath) {
|
|
495
|
+
const resolvedValue = deepResolveValue(rawValue, get);
|
|
496
|
+
const arr = get(statePath) ?? [];
|
|
497
|
+
set(statePath, [...arr, resolvedValue]);
|
|
498
|
+
const clearStatePath = resolved.params.clearStatePath;
|
|
499
|
+
if (clearStatePath) {
|
|
500
|
+
set(clearStatePath, "");
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
if (resolved.action === "removeState" && resolved.params) {
|
|
506
|
+
const statePath = resolved.params.statePath;
|
|
507
|
+
const index = resolved.params.index;
|
|
508
|
+
if (statePath !== void 0 && index !== void 0) {
|
|
509
|
+
const arr = get(statePath) ?? [];
|
|
510
|
+
set(
|
|
511
|
+
statePath,
|
|
512
|
+
arr.filter((_, i) => i !== index)
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
if (resolved.action === "push" && resolved.params) {
|
|
518
|
+
const screen = resolved.params.screen;
|
|
519
|
+
if (screen) {
|
|
520
|
+
const currentScreen = get("/currentScreen");
|
|
521
|
+
const navStack = get("/navStack") ?? [];
|
|
522
|
+
if (currentScreen) {
|
|
523
|
+
set("/navStack", [...navStack, currentScreen]);
|
|
524
|
+
} else {
|
|
525
|
+
set("/navStack", [...navStack, ""]);
|
|
526
|
+
}
|
|
527
|
+
set("/currentScreen", screen);
|
|
528
|
+
}
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (resolved.action === "pop") {
|
|
532
|
+
const navStack = get("/navStack") ?? [];
|
|
533
|
+
if (navStack.length > 0) {
|
|
534
|
+
const previousScreen = navStack[navStack.length - 1];
|
|
535
|
+
set("/navStack", navStack.slice(0, -1));
|
|
536
|
+
if (previousScreen) {
|
|
537
|
+
set("/currentScreen", previousScreen);
|
|
538
|
+
} else {
|
|
539
|
+
set("/currentScreen", void 0);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
if (resolved.action === "validateForm") {
|
|
545
|
+
const validateAll = validation?.validateAll;
|
|
546
|
+
if (!validateAll) {
|
|
547
|
+
console.warn(
|
|
548
|
+
"validateForm action was dispatched but no ValidationProvider is connected. Ensure ValidationProvider is rendered inside the provider tree."
|
|
549
|
+
);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const valid = validateAll();
|
|
553
|
+
const errors = {};
|
|
554
|
+
for (const [path, fs] of Object.entries(validation.fieldStates)) {
|
|
555
|
+
if (fs.result && !fs.result.valid) {
|
|
556
|
+
errors[path] = fs.result.errors;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
const statePath = resolved.params?.statePath || "/formValidation";
|
|
560
|
+
set(statePath, { valid, errors });
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
const handler = handlers[resolved.action];
|
|
564
|
+
if (!handler) {
|
|
565
|
+
console.warn(`No handler registered for action: ${resolved.action}`);
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
if (resolved.confirm) {
|
|
569
|
+
return new Promise((resolve, reject) => {
|
|
570
|
+
setPendingConfirmation({
|
|
571
|
+
action: resolved,
|
|
572
|
+
handler,
|
|
573
|
+
resolve: () => {
|
|
574
|
+
setPendingConfirmation(null);
|
|
575
|
+
resolve();
|
|
576
|
+
},
|
|
577
|
+
reject: () => {
|
|
578
|
+
setPendingConfirmation(null);
|
|
579
|
+
reject(new Error("Action cancelled"));
|
|
580
|
+
}
|
|
581
|
+
});
|
|
582
|
+
}).then(async () => {
|
|
583
|
+
setLoadingActions((prev) => new Set(prev).add(resolved.action));
|
|
584
|
+
try {
|
|
585
|
+
await (0, import_core4.executeAction)({
|
|
586
|
+
action: resolved,
|
|
587
|
+
handler,
|
|
588
|
+
setState: set,
|
|
589
|
+
navigate,
|
|
590
|
+
executeAction: async (name) => {
|
|
591
|
+
const subBinding = { action: name };
|
|
592
|
+
await execute(subBinding);
|
|
593
|
+
}
|
|
594
|
+
});
|
|
595
|
+
} finally {
|
|
596
|
+
setLoadingActions((prev) => {
|
|
597
|
+
const next = new Set(prev);
|
|
598
|
+
next.delete(resolved.action);
|
|
599
|
+
return next;
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
setLoadingActions((prev) => new Set(prev).add(resolved.action));
|
|
605
|
+
try {
|
|
606
|
+
await (0, import_core4.executeAction)({
|
|
607
|
+
action: resolved,
|
|
608
|
+
handler,
|
|
609
|
+
setState: set,
|
|
610
|
+
navigate,
|
|
611
|
+
executeAction: async (name) => {
|
|
612
|
+
const subBinding = { action: name };
|
|
613
|
+
await execute(subBinding);
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
} finally {
|
|
617
|
+
setLoadingActions((prev) => {
|
|
618
|
+
const next = new Set(prev);
|
|
619
|
+
next.delete(resolved.action);
|
|
620
|
+
return next;
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
} catch (err) {
|
|
624
|
+
__ok = false;
|
|
625
|
+
__error = err;
|
|
626
|
+
throw err;
|
|
627
|
+
} finally {
|
|
628
|
+
const now = Date.now();
|
|
629
|
+
(0, import_core4.notifyActionSettle)({
|
|
630
|
+
id: dispatchId,
|
|
631
|
+
name: resolved.action,
|
|
632
|
+
ok: __ok,
|
|
633
|
+
at: now,
|
|
634
|
+
durationMs: now - dispatchedAt,
|
|
635
|
+
error: __error
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
},
|
|
639
|
+
[handlers, get, set, getSnapshot, navigate, validation]
|
|
640
|
+
);
|
|
641
|
+
const confirm = (0, import_react4.useCallback)(() => {
|
|
642
|
+
pendingConfirmation?.resolve();
|
|
643
|
+
}, [pendingConfirmation]);
|
|
644
|
+
const cancel = (0, import_react4.useCallback)(() => {
|
|
645
|
+
pendingConfirmation?.reject();
|
|
646
|
+
}, [pendingConfirmation]);
|
|
647
|
+
const value = (0, import_react4.useMemo)(
|
|
648
|
+
() => ({
|
|
649
|
+
handlers,
|
|
650
|
+
loadingActions,
|
|
651
|
+
pendingConfirmation,
|
|
652
|
+
execute,
|
|
653
|
+
confirm,
|
|
654
|
+
cancel,
|
|
655
|
+
registerHandler
|
|
656
|
+
}),
|
|
657
|
+
[
|
|
658
|
+
handlers,
|
|
659
|
+
loadingActions,
|
|
660
|
+
pendingConfirmation,
|
|
661
|
+
execute,
|
|
662
|
+
confirm,
|
|
663
|
+
cancel,
|
|
664
|
+
registerHandler
|
|
665
|
+
]
|
|
666
|
+
);
|
|
667
|
+
return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ActionContext.Provider, { value, children });
|
|
668
|
+
}
|
|
669
|
+
function useActions() {
|
|
670
|
+
const ctx = (0, import_react4.useContext)(ActionContext);
|
|
671
|
+
if (!ctx) {
|
|
672
|
+
throw new Error("useActions must be used within an ActionProvider");
|
|
673
|
+
}
|
|
674
|
+
return ctx;
|
|
675
|
+
}
|
|
676
|
+
function useAction(binding) {
|
|
677
|
+
const { execute, loadingActions } = useActions();
|
|
678
|
+
const isLoading = loadingActions.has(binding.action);
|
|
679
|
+
const executeAction2 = (0, import_react4.useCallback)(() => execute(binding), [execute, binding]);
|
|
680
|
+
return { execute: executeAction2, isLoading };
|
|
681
|
+
}
|
|
682
|
+
function ConfirmDialog({
|
|
683
|
+
confirm,
|
|
684
|
+
onConfirm,
|
|
685
|
+
onCancel
|
|
686
|
+
}) {
|
|
687
|
+
const isDanger = confirm.variant === "danger";
|
|
688
|
+
return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
689
|
+
"div",
|
|
690
|
+
{
|
|
691
|
+
style: {
|
|
692
|
+
position: "fixed",
|
|
693
|
+
inset: 0,
|
|
694
|
+
backgroundColor: "rgba(0, 0, 0, 0.5)",
|
|
695
|
+
display: "flex",
|
|
696
|
+
alignItems: "center",
|
|
697
|
+
justifyContent: "center",
|
|
698
|
+
zIndex: 50
|
|
699
|
+
},
|
|
700
|
+
onClick: onCancel,
|
|
701
|
+
children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
|
|
702
|
+
"div",
|
|
703
|
+
{
|
|
704
|
+
style: {
|
|
705
|
+
backgroundColor: "white",
|
|
706
|
+
borderRadius: "8px",
|
|
707
|
+
padding: "24px",
|
|
708
|
+
maxWidth: "400px",
|
|
709
|
+
width: "100%",
|
|
710
|
+
boxShadow: "0 20px 25px -5px rgba(0, 0, 0, 0.1)"
|
|
711
|
+
},
|
|
712
|
+
onClick: (e) => e.stopPropagation(),
|
|
713
|
+
children: [
|
|
714
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
715
|
+
"h3",
|
|
716
|
+
{
|
|
717
|
+
style: {
|
|
718
|
+
margin: "0 0 8px 0",
|
|
719
|
+
fontSize: "18px",
|
|
720
|
+
fontWeight: 600
|
|
721
|
+
},
|
|
722
|
+
children: confirm.title
|
|
723
|
+
}
|
|
724
|
+
),
|
|
725
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
726
|
+
"p",
|
|
727
|
+
{
|
|
728
|
+
style: {
|
|
729
|
+
margin: "0 0 24px 0",
|
|
730
|
+
color: "#6b7280"
|
|
731
|
+
},
|
|
732
|
+
children: confirm.message
|
|
733
|
+
}
|
|
734
|
+
),
|
|
735
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
|
|
736
|
+
"div",
|
|
737
|
+
{
|
|
738
|
+
style: {
|
|
739
|
+
display: "flex",
|
|
740
|
+
gap: "12px",
|
|
741
|
+
justifyContent: "flex-end"
|
|
742
|
+
},
|
|
743
|
+
children: [
|
|
744
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
745
|
+
"button",
|
|
746
|
+
{
|
|
747
|
+
onClick: onCancel,
|
|
748
|
+
style: {
|
|
749
|
+
padding: "8px 16px",
|
|
750
|
+
borderRadius: "6px",
|
|
751
|
+
border: "1px solid #d1d5db",
|
|
752
|
+
backgroundColor: "white",
|
|
753
|
+
cursor: "pointer"
|
|
754
|
+
},
|
|
755
|
+
children: confirm.cancelLabel ?? "Cancel"
|
|
756
|
+
}
|
|
757
|
+
),
|
|
758
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
759
|
+
"button",
|
|
760
|
+
{
|
|
761
|
+
onClick: onConfirm,
|
|
762
|
+
style: {
|
|
763
|
+
padding: "8px 16px",
|
|
764
|
+
borderRadius: "6px",
|
|
765
|
+
border: "none",
|
|
766
|
+
backgroundColor: isDanger ? "#dc2626" : "#3b82f6",
|
|
767
|
+
color: "white",
|
|
768
|
+
cursor: "pointer"
|
|
769
|
+
},
|
|
770
|
+
children: confirm.confirmLabel ?? "Confirm"
|
|
771
|
+
}
|
|
772
|
+
)
|
|
773
|
+
]
|
|
774
|
+
}
|
|
775
|
+
)
|
|
776
|
+
]
|
|
777
|
+
}
|
|
778
|
+
)
|
|
779
|
+
}
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// src/contexts/repeat-scope.tsx
|
|
784
|
+
var import_react5 = require("react");
|
|
785
|
+
var import_jsx_runtime5 = require("react/jsx-runtime");
|
|
786
|
+
var RepeatScopeContext = (0, import_react5.createContext)(null);
|
|
787
|
+
function RepeatScopeProvider({
|
|
788
|
+
item,
|
|
789
|
+
index,
|
|
790
|
+
basePath,
|
|
791
|
+
children
|
|
792
|
+
}) {
|
|
793
|
+
return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(RepeatScopeContext.Provider, { value: { item, index, basePath }, children });
|
|
794
|
+
}
|
|
795
|
+
function useRepeatScope() {
|
|
796
|
+
return (0, import_react5.useContext)(RepeatScopeContext);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// src/schema.ts
|
|
800
|
+
var import_core5 = require("@xmachines/json-render-core");
|
|
801
|
+
var schema = (0, import_core5.defineSchema)(
|
|
802
|
+
(s) => ({
|
|
803
|
+
// What the AI-generated SPEC looks like
|
|
804
|
+
spec: s.object({
|
|
805
|
+
/** Root element key */
|
|
806
|
+
root: s.string(),
|
|
807
|
+
/** Flat map of elements by key */
|
|
808
|
+
elements: s.record(
|
|
809
|
+
s.object({
|
|
810
|
+
/** Component type from catalog */
|
|
811
|
+
type: s.ref("catalog.components"),
|
|
812
|
+
/** Component props */
|
|
813
|
+
props: s.propsOf("catalog.components"),
|
|
814
|
+
/** Child element keys (flat reference) */
|
|
815
|
+
children: s.array(s.string()),
|
|
816
|
+
/** Visibility condition */
|
|
817
|
+
visible: s.any()
|
|
818
|
+
})
|
|
819
|
+
)
|
|
820
|
+
}),
|
|
821
|
+
// What the CATALOG must provide
|
|
822
|
+
catalog: s.object({
|
|
823
|
+
/** Component definitions */
|
|
824
|
+
components: s.map({
|
|
825
|
+
/** Zod schema for component props */
|
|
826
|
+
props: s.zod(),
|
|
827
|
+
/** Slots for this component. Use ['default'] for children, or named slots like ['header', 'footer'] */
|
|
828
|
+
slots: s.array(s.string()),
|
|
829
|
+
/** Description for AI generation hints */
|
|
830
|
+
description: s.string(),
|
|
831
|
+
/** Example prop values used in prompt examples (auto-generated from Zod schema if omitted) */
|
|
832
|
+
example: s.any()
|
|
833
|
+
}),
|
|
834
|
+
/** Action definitions (optional) */
|
|
835
|
+
actions: s.map({
|
|
836
|
+
/** Zod schema for action params */
|
|
837
|
+
params: s.zod(),
|
|
838
|
+
/** Description for AI generation hints */
|
|
839
|
+
description: s.string()
|
|
840
|
+
})
|
|
841
|
+
})
|
|
842
|
+
}),
|
|
843
|
+
{
|
|
844
|
+
builtInActions: [
|
|
845
|
+
{
|
|
846
|
+
name: "setState",
|
|
847
|
+
description: "Update a value in the state model at the given statePath. Params: { statePath: string, value: any }"
|
|
848
|
+
},
|
|
849
|
+
{
|
|
850
|
+
name: "pushState",
|
|
851
|
+
description: 'Append an item to an array in state. Params: { statePath: string, value: any, clearStatePath?: string }. Value can contain {"$state":"/path"} refs and "$id" for auto IDs.'
|
|
852
|
+
},
|
|
853
|
+
{
|
|
854
|
+
name: "removeState",
|
|
855
|
+
description: "Remove an item from an array in state by index. Params: { statePath: string, index: number }"
|
|
856
|
+
},
|
|
857
|
+
{
|
|
858
|
+
name: "validateForm",
|
|
859
|
+
description: "Validate all registered form fields and write the result to state. Params: { statePath?: string }. Defaults to /formValidation. Result: { valid: boolean, errors: Record<string, string[]> }."
|
|
860
|
+
}
|
|
861
|
+
],
|
|
862
|
+
defaultRules: [
|
|
863
|
+
// Element integrity
|
|
864
|
+
"CRITICAL INTEGRITY CHECK: Before outputting ANY element that references children, you MUST have already output (or will output) each child as its own element. If an element has children: ['a', 'b'], then elements 'a' and 'b' MUST exist. A missing child element causes that entire branch of the UI to be invisible.",
|
|
865
|
+
"SELF-CHECK: After generating all elements, mentally walk the tree from root. Every key in every children array must resolve to a defined element. If you find a gap, output the missing element immediately.",
|
|
866
|
+
// Field placement
|
|
867
|
+
'CRITICAL: The "visible" field goes on the ELEMENT object, NOT inside "props". Correct: {"type":"<ComponentName>","props":{},"visible":{"$state":"/tab","eq":"home"},"children":[...]}.',
|
|
868
|
+
'CRITICAL: The "on" field goes on the ELEMENT object, NOT inside "props". Use on.press, on.change, on.submit etc. NEVER put action/actionParams inside props.',
|
|
869
|
+
// State and data
|
|
870
|
+
"When the user asks for a UI that displays data (e.g. blog posts, products, users), ALWAYS include a state field with realistic sample data. The state field is a top-level field on the spec (sibling of root/elements).",
|
|
871
|
+
'When building repeating content backed by a state array (e.g. posts, products, items), use the "repeat" field on a container element. Example: { "type": "<ContainerComponent>", "props": {}, "repeat": { "statePath": "/posts", "key": "id" }, "children": ["post-card"] }. Replace <ContainerComponent> with an appropriate component from the AVAILABLE COMPONENTS list. Inside repeated children, use { "$item": "field" } to read a field from the current item, and { "$index": true } for the current array index. For two-way binding to an item field use { "$bindItem": "completed" }. Do NOT hardcode individual elements for each array item.',
|
|
872
|
+
// Design quality
|
|
873
|
+
"Design with visual hierarchy: use container components to group content, heading components for section titles, proper spacing, and status indicators. ONLY use components from the AVAILABLE COMPONENTS list.",
|
|
874
|
+
"For data-rich UIs, use multi-column layout components if available. For forms and single-column content, use vertical layout components. ONLY use components from the AVAILABLE COMPONENTS list.",
|
|
875
|
+
"Always include realistic, professional-looking sample data. For blogs include 3-4 posts with varied titles, authors, dates, categories. For products include names, prices, images. Never leave data empty."
|
|
876
|
+
]
|
|
877
|
+
}
|
|
878
|
+
);
|
|
879
|
+
var elementTreeSchema = schema;
|
|
880
|
+
|
|
881
|
+
// src/index.ts
|
|
882
|
+
var import_core8 = require("@xmachines/json-render-core");
|
|
883
|
+
|
|
884
|
+
// src/renderer.tsx
|
|
885
|
+
var import_react6 = __toESM(require("react"));
|
|
886
|
+
var import_core6 = require("@xmachines/json-render-core");
|
|
887
|
+
var import_jsx_runtime6 = require("react/jsx-runtime");
|
|
888
|
+
function reportRenderError(registry, elementType, error, componentStack) {
|
|
889
|
+
const onRenderError = registry?.onRenderError;
|
|
890
|
+
if (typeof onRenderError === "function") {
|
|
891
|
+
onRenderError(error, elementType);
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
console.error(
|
|
895
|
+
`[json-render] Rendering error in <${elementType}>:`,
|
|
896
|
+
error,
|
|
897
|
+
componentStack
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
var ElementErrorBoundary = class extends import_react6.default.Component {
|
|
901
|
+
constructor(props) {
|
|
902
|
+
super(props);
|
|
903
|
+
this.state = { hasError: false };
|
|
904
|
+
}
|
|
905
|
+
static getDerivedStateFromError() {
|
|
906
|
+
return { hasError: true };
|
|
907
|
+
}
|
|
908
|
+
componentDidCatch(error, info) {
|
|
909
|
+
reportRenderError(
|
|
910
|
+
this.props.registry,
|
|
911
|
+
this.props.elementType,
|
|
912
|
+
error,
|
|
913
|
+
info.componentStack
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
render() {
|
|
917
|
+
if (this.state.hasError) {
|
|
918
|
+
return null;
|
|
919
|
+
}
|
|
920
|
+
return this.props.children;
|
|
921
|
+
}
|
|
922
|
+
};
|
|
923
|
+
var EMPTY_FUNCTIONS = {};
|
|
924
|
+
var FunctionsContext = import_react6.default.createContext(EMPTY_FUNCTIONS);
|
|
925
|
+
function useFunctions() {
|
|
926
|
+
return import_react6.default.useContext(FunctionsContext);
|
|
927
|
+
}
|
|
928
|
+
var DirectivesContext = import_react6.default.createContext(
|
|
929
|
+
void 0
|
|
930
|
+
);
|
|
931
|
+
function useDirectives() {
|
|
932
|
+
return import_react6.default.useContext(DirectivesContext);
|
|
933
|
+
}
|
|
934
|
+
function useDevtoolsActive() {
|
|
935
|
+
return import_react6.default.useSyncExternalStore(
|
|
936
|
+
import_core6.subscribeDevtoolsActive,
|
|
937
|
+
import_core6.isDevtoolsActive,
|
|
938
|
+
() => false
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
var ElementRenderer = import_react6.default.memo(function ElementRenderer2({
|
|
942
|
+
element,
|
|
943
|
+
elementKey,
|
|
944
|
+
spec,
|
|
945
|
+
registry,
|
|
946
|
+
loading,
|
|
947
|
+
fallback
|
|
948
|
+
}) {
|
|
949
|
+
const devtoolsActive = useDevtoolsActive();
|
|
950
|
+
const repeatScope = useRepeatScope();
|
|
951
|
+
const { ctx } = useVisibility();
|
|
952
|
+
const { execute } = useActions();
|
|
953
|
+
const { getSnapshot, state: watchState } = useStateStore();
|
|
954
|
+
const functions = useFunctions();
|
|
955
|
+
const directives = useDirectives();
|
|
956
|
+
const fullCtx = (0, import_react6.useMemo)(() => {
|
|
957
|
+
const base = repeatScope ? {
|
|
958
|
+
...ctx,
|
|
959
|
+
repeatItem: repeatScope.item,
|
|
960
|
+
repeatIndex: repeatScope.index,
|
|
961
|
+
repeatBasePath: repeatScope.basePath
|
|
962
|
+
} : { ...ctx };
|
|
963
|
+
base.functions = functions;
|
|
964
|
+
base.directives = directives;
|
|
965
|
+
return base;
|
|
966
|
+
}, [ctx, repeatScope, functions, directives]);
|
|
967
|
+
const isVisible = element.visible === void 0 ? true : (0, import_core6.evaluateVisibility)(element.visible, fullCtx);
|
|
968
|
+
const onBindings = element.on;
|
|
969
|
+
const emit = (0, import_react6.useCallback)(
|
|
970
|
+
async (eventName) => {
|
|
971
|
+
const binding = onBindings?.[eventName];
|
|
972
|
+
if (!binding) return;
|
|
973
|
+
const actionBindings = Array.isArray(binding) ? binding : [binding];
|
|
974
|
+
for (const b of actionBindings) {
|
|
975
|
+
if (!b.params) {
|
|
976
|
+
await execute(b);
|
|
977
|
+
continue;
|
|
978
|
+
}
|
|
979
|
+
const liveCtx = {
|
|
980
|
+
...fullCtx,
|
|
981
|
+
stateModel: getSnapshot()
|
|
982
|
+
};
|
|
983
|
+
const resolved = {};
|
|
984
|
+
for (const [key, val] of Object.entries(b.params)) {
|
|
985
|
+
resolved[key] = (0, import_core6.resolveActionParam)(val, liveCtx);
|
|
986
|
+
}
|
|
987
|
+
await execute({ ...b, params: resolved });
|
|
988
|
+
}
|
|
989
|
+
},
|
|
990
|
+
[onBindings, execute, fullCtx, getSnapshot]
|
|
991
|
+
);
|
|
992
|
+
const on = (0, import_react6.useCallback)(
|
|
993
|
+
(eventName) => {
|
|
994
|
+
const binding = onBindings?.[eventName];
|
|
995
|
+
if (!binding) {
|
|
996
|
+
return { emit: () => {
|
|
997
|
+
}, shouldPreventDefault: false, bound: false };
|
|
998
|
+
}
|
|
999
|
+
const actionBindings = Array.isArray(binding) ? binding : [binding];
|
|
1000
|
+
const shouldPreventDefault = actionBindings.some((b) => b.preventDefault);
|
|
1001
|
+
return {
|
|
1002
|
+
emit: () => emit(eventName),
|
|
1003
|
+
shouldPreventDefault,
|
|
1004
|
+
bound: true
|
|
1005
|
+
};
|
|
1006
|
+
},
|
|
1007
|
+
[onBindings, emit]
|
|
1008
|
+
);
|
|
1009
|
+
const watchConfig = element.watch;
|
|
1010
|
+
const prevWatchValues = (0, import_react6.useRef)(null);
|
|
1011
|
+
const stableWatchRef = (0, import_react6.useRef)(void 0);
|
|
1012
|
+
const watchedValues = (0, import_react6.useMemo)(() => {
|
|
1013
|
+
if (!watchConfig) return void 0;
|
|
1014
|
+
const values = {};
|
|
1015
|
+
for (const path of Object.keys(watchConfig)) {
|
|
1016
|
+
values[path] = (0, import_core6.getByPath)(watchState, path);
|
|
1017
|
+
}
|
|
1018
|
+
const prev = stableWatchRef.current;
|
|
1019
|
+
if (prev) {
|
|
1020
|
+
const keys = Object.keys(values);
|
|
1021
|
+
if (keys.length === Object.keys(prev).length && keys.every((k) => values[k] === prev[k])) {
|
|
1022
|
+
return prev;
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
stableWatchRef.current = values;
|
|
1026
|
+
return values;
|
|
1027
|
+
}, [watchConfig, watchState]);
|
|
1028
|
+
(0, import_react6.useEffect)(() => {
|
|
1029
|
+
if (!watchConfig || !watchedValues) return;
|
|
1030
|
+
const paths = Object.keys(watchConfig);
|
|
1031
|
+
if (paths.length === 0) return;
|
|
1032
|
+
const prev = prevWatchValues.current;
|
|
1033
|
+
prevWatchValues.current = watchedValues;
|
|
1034
|
+
if (prev === null) return;
|
|
1035
|
+
let cancelled = false;
|
|
1036
|
+
void (async () => {
|
|
1037
|
+
for (const path of paths) {
|
|
1038
|
+
if (cancelled) break;
|
|
1039
|
+
if (watchedValues[path] !== prev[path]) {
|
|
1040
|
+
const binding = watchConfig[path];
|
|
1041
|
+
if (!binding) continue;
|
|
1042
|
+
const bindings = Array.isArray(binding) ? binding : [binding];
|
|
1043
|
+
for (const b of bindings) {
|
|
1044
|
+
if (cancelled) break;
|
|
1045
|
+
if (!b.params) {
|
|
1046
|
+
await execute(b);
|
|
1047
|
+
if (cancelled) break;
|
|
1048
|
+
continue;
|
|
1049
|
+
}
|
|
1050
|
+
const liveCtx = {
|
|
1051
|
+
...fullCtx,
|
|
1052
|
+
stateModel: getSnapshot()
|
|
1053
|
+
};
|
|
1054
|
+
const resolved = {};
|
|
1055
|
+
for (const [key, val] of Object.entries(b.params)) {
|
|
1056
|
+
resolved[key] = (0, import_core6.resolveActionParam)(val, liveCtx);
|
|
1057
|
+
}
|
|
1058
|
+
await execute({ ...b, params: resolved });
|
|
1059
|
+
if (cancelled) break;
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
})().catch(console.error);
|
|
1064
|
+
return () => {
|
|
1065
|
+
cancelled = true;
|
|
1066
|
+
};
|
|
1067
|
+
}, [watchConfig, watchedValues, execute, fullCtx, getSnapshot]);
|
|
1068
|
+
if (!isVisible) {
|
|
1069
|
+
return null;
|
|
1070
|
+
}
|
|
1071
|
+
const rawProps = element.props;
|
|
1072
|
+
const elementBindings = (0, import_core6.resolveBindings)(rawProps, fullCtx);
|
|
1073
|
+
const resolvedProps = (0, import_core6.resolveElementProps)(rawProps, fullCtx);
|
|
1074
|
+
const resolvedElement = resolvedProps !== element.props ? { ...element, props: resolvedProps } : element;
|
|
1075
|
+
const Component = registry[resolvedElement.type] ?? fallback;
|
|
1076
|
+
if (!Component) {
|
|
1077
|
+
console.warn(`No renderer for component type: ${resolvedElement.type}`);
|
|
1078
|
+
return null;
|
|
1079
|
+
}
|
|
1080
|
+
const children = resolvedElement.repeat ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1081
|
+
RepeatChildren,
|
|
1082
|
+
{
|
|
1083
|
+
element: resolvedElement,
|
|
1084
|
+
spec,
|
|
1085
|
+
registry,
|
|
1086
|
+
loading,
|
|
1087
|
+
fallback
|
|
1088
|
+
}
|
|
1089
|
+
) : resolvedElement.children?.map((childKey) => {
|
|
1090
|
+
const childElement = spec.elements[childKey];
|
|
1091
|
+
if (!childElement) {
|
|
1092
|
+
if (!loading) {
|
|
1093
|
+
console.warn(
|
|
1094
|
+
`[json-render] Missing element "${childKey}" referenced as child of "${resolvedElement.type}". This element will not render.`
|
|
1095
|
+
);
|
|
1096
|
+
}
|
|
1097
|
+
return null;
|
|
1098
|
+
}
|
|
1099
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1100
|
+
ElementRenderer2,
|
|
1101
|
+
{
|
|
1102
|
+
element: childElement,
|
|
1103
|
+
elementKey: childKey,
|
|
1104
|
+
spec,
|
|
1105
|
+
registry,
|
|
1106
|
+
loading,
|
|
1107
|
+
fallback
|
|
1108
|
+
},
|
|
1109
|
+
childKey
|
|
1110
|
+
);
|
|
1111
|
+
});
|
|
1112
|
+
const rendered = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1113
|
+
Component,
|
|
1114
|
+
{
|
|
1115
|
+
element: resolvedElement,
|
|
1116
|
+
emit,
|
|
1117
|
+
on,
|
|
1118
|
+
bindings: elementBindings,
|
|
1119
|
+
loading,
|
|
1120
|
+
children
|
|
1121
|
+
}
|
|
1122
|
+
);
|
|
1123
|
+
const tagged = devtoolsActive && elementKey ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { "data-jr-key": elementKey, style: { display: "contents" }, children: rendered }) : rendered;
|
|
1124
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1125
|
+
ElementErrorBoundary,
|
|
1126
|
+
{
|
|
1127
|
+
elementType: resolvedElement.type,
|
|
1128
|
+
registry,
|
|
1129
|
+
children: tagged
|
|
1130
|
+
}
|
|
1131
|
+
);
|
|
1132
|
+
});
|
|
1133
|
+
function RepeatChildren({
|
|
1134
|
+
element,
|
|
1135
|
+
spec,
|
|
1136
|
+
registry,
|
|
1137
|
+
loading,
|
|
1138
|
+
fallback
|
|
1139
|
+
}) {
|
|
1140
|
+
const { state } = useStateStore();
|
|
1141
|
+
const repeat = element.repeat;
|
|
1142
|
+
const statePath = repeat.statePath;
|
|
1143
|
+
const items = (0, import_core6.getByPath)(state, statePath) ?? [];
|
|
1144
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: items.map((itemValue, index) => {
|
|
1145
|
+
const key = repeat.key && typeof itemValue === "object" && itemValue !== null ? String(
|
|
1146
|
+
itemValue[repeat.key] ?? index
|
|
1147
|
+
) : String(index);
|
|
1148
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1149
|
+
RepeatScopeProvider,
|
|
1150
|
+
{
|
|
1151
|
+
item: itemValue,
|
|
1152
|
+
index,
|
|
1153
|
+
basePath: `${statePath}/${index}`,
|
|
1154
|
+
children: element.children?.map((childKey) => {
|
|
1155
|
+
const childElement = spec.elements[childKey];
|
|
1156
|
+
if (!childElement) {
|
|
1157
|
+
if (!loading) {
|
|
1158
|
+
console.warn(
|
|
1159
|
+
`[json-render] Missing element "${childKey}" referenced as child of "${element.type}" (repeat). This element will not render.`
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
return null;
|
|
1163
|
+
}
|
|
1164
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1165
|
+
ElementRenderer,
|
|
1166
|
+
{
|
|
1167
|
+
element: childElement,
|
|
1168
|
+
elementKey: childKey,
|
|
1169
|
+
spec,
|
|
1170
|
+
registry,
|
|
1171
|
+
loading,
|
|
1172
|
+
fallback
|
|
1173
|
+
},
|
|
1174
|
+
childKey
|
|
1175
|
+
);
|
|
1176
|
+
})
|
|
1177
|
+
},
|
|
1178
|
+
key
|
|
1179
|
+
);
|
|
1180
|
+
}) });
|
|
1181
|
+
}
|
|
1182
|
+
function Renderer({
|
|
1183
|
+
spec,
|
|
1184
|
+
registry,
|
|
1185
|
+
loading,
|
|
1186
|
+
fallback,
|
|
1187
|
+
onRenderError
|
|
1188
|
+
}) {
|
|
1189
|
+
const rendererRegistry = (0, import_react6.useMemo)(() => {
|
|
1190
|
+
if (!onRenderError) return registry;
|
|
1191
|
+
const next = { ...registry };
|
|
1192
|
+
Object.defineProperty(next, "onRenderError", {
|
|
1193
|
+
value: onRenderError,
|
|
1194
|
+
enumerable: false,
|
|
1195
|
+
configurable: true
|
|
1196
|
+
});
|
|
1197
|
+
return next;
|
|
1198
|
+
}, [registry, onRenderError]);
|
|
1199
|
+
if (!spec || !spec.root) {
|
|
1200
|
+
return null;
|
|
1201
|
+
}
|
|
1202
|
+
const rootElement = spec.elements[spec.root];
|
|
1203
|
+
if (!rootElement) {
|
|
1204
|
+
return null;
|
|
1205
|
+
}
|
|
1206
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1207
|
+
ElementRenderer,
|
|
1208
|
+
{
|
|
1209
|
+
element: rootElement,
|
|
1210
|
+
elementKey: spec.root,
|
|
1211
|
+
spec,
|
|
1212
|
+
registry: rendererRegistry,
|
|
1213
|
+
loading,
|
|
1214
|
+
fallback
|
|
1215
|
+
}
|
|
1216
|
+
);
|
|
1217
|
+
}
|
|
1218
|
+
function JSONUIProvider({
|
|
1219
|
+
registry,
|
|
1220
|
+
store,
|
|
1221
|
+
initialState,
|
|
1222
|
+
handlers,
|
|
1223
|
+
navigate,
|
|
1224
|
+
validationFunctions,
|
|
1225
|
+
functions,
|
|
1226
|
+
directives,
|
|
1227
|
+
onStateChange,
|
|
1228
|
+
children
|
|
1229
|
+
}) {
|
|
1230
|
+
const directiveRegistry = (0, import_react6.useMemo)(
|
|
1231
|
+
() => directives ? (0, import_core6.createDirectiveRegistry)(directives) : void 0,
|
|
1232
|
+
[directives]
|
|
1233
|
+
);
|
|
1234
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1235
|
+
StateProvider,
|
|
1236
|
+
{
|
|
1237
|
+
store,
|
|
1238
|
+
initialState,
|
|
1239
|
+
onStateChange,
|
|
1240
|
+
children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(VisibilityProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ValidationProvider, { customFunctions: validationFunctions, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ActionProvider, { handlers, navigate, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FunctionsContext.Provider, { value: functions ?? EMPTY_FUNCTIONS, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(DirectivesContext.Provider, { value: directiveRegistry, children: [
|
|
1241
|
+
children,
|
|
1242
|
+
/* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ConfirmationDialogManager, {})
|
|
1243
|
+
] }) }) }) }) })
|
|
1244
|
+
}
|
|
1245
|
+
);
|
|
1246
|
+
}
|
|
1247
|
+
function ConfirmationDialogManager() {
|
|
1248
|
+
const { pendingConfirmation, confirm, cancel } = useActions();
|
|
1249
|
+
if (!pendingConfirmation?.action.confirm) {
|
|
1250
|
+
return null;
|
|
1251
|
+
}
|
|
1252
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1253
|
+
ConfirmDialog,
|
|
1254
|
+
{
|
|
1255
|
+
confirm: pendingConfirmation.action.confirm,
|
|
1256
|
+
onConfirm: confirm,
|
|
1257
|
+
onCancel: cancel
|
|
1258
|
+
}
|
|
1259
|
+
);
|
|
1260
|
+
}
|
|
1261
|
+
function defineRegistry(_catalog, options) {
|
|
1262
|
+
const registry = {};
|
|
1263
|
+
if (options.components) {
|
|
1264
|
+
for (const [name, componentFn] of Object.entries(options.components)) {
|
|
1265
|
+
registry[name] = ({
|
|
1266
|
+
element,
|
|
1267
|
+
children,
|
|
1268
|
+
emit,
|
|
1269
|
+
on,
|
|
1270
|
+
bindings,
|
|
1271
|
+
loading
|
|
1272
|
+
}) => {
|
|
1273
|
+
return componentFn({
|
|
1274
|
+
props: element.props,
|
|
1275
|
+
children,
|
|
1276
|
+
emit,
|
|
1277
|
+
on,
|
|
1278
|
+
bindings,
|
|
1279
|
+
loading
|
|
1280
|
+
});
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
const actionMap = options.actions ? Object.entries(options.actions) : [];
|
|
1285
|
+
const handlers = (getSetState, getState) => {
|
|
1286
|
+
const result = {};
|
|
1287
|
+
for (const [name, actionFn] of actionMap) {
|
|
1288
|
+
result[name] = async (params) => {
|
|
1289
|
+
const setState = getSetState();
|
|
1290
|
+
const state = getState();
|
|
1291
|
+
if (setState) {
|
|
1292
|
+
await actionFn(params, setState, state);
|
|
1293
|
+
}
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
return result;
|
|
1297
|
+
};
|
|
1298
|
+
const executeAction2 = async (actionName, params, setState, state = {}) => {
|
|
1299
|
+
const entry = actionMap.find(([name]) => name === actionName);
|
|
1300
|
+
if (entry) {
|
|
1301
|
+
await entry[1](params, setState, state);
|
|
1302
|
+
} else {
|
|
1303
|
+
console.warn(`Unknown action: ${actionName}`);
|
|
1304
|
+
}
|
|
1305
|
+
};
|
|
1306
|
+
if (options.onRenderError) {
|
|
1307
|
+
Object.defineProperty(registry, "onRenderError", {
|
|
1308
|
+
value: options.onRenderError,
|
|
1309
|
+
enumerable: false,
|
|
1310
|
+
configurable: true
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
return { registry, handlers, executeAction: executeAction2 };
|
|
1314
|
+
}
|
|
1315
|
+
function createRenderer(catalog, components) {
|
|
1316
|
+
const registry = components;
|
|
1317
|
+
return function CatalogRenderer({
|
|
1318
|
+
spec,
|
|
1319
|
+
store,
|
|
1320
|
+
state,
|
|
1321
|
+
onAction,
|
|
1322
|
+
onStateChange,
|
|
1323
|
+
functions,
|
|
1324
|
+
directives,
|
|
1325
|
+
loading,
|
|
1326
|
+
fallback,
|
|
1327
|
+
onRenderError
|
|
1328
|
+
}) {
|
|
1329
|
+
const directiveRegistry = (0, import_react6.useMemo)(
|
|
1330
|
+
() => directives ? (0, import_core6.createDirectiveRegistry)(directives) : void 0,
|
|
1331
|
+
[directives]
|
|
1332
|
+
);
|
|
1333
|
+
const rendererRegistry = (0, import_react6.useMemo)(() => {
|
|
1334
|
+
if (!onRenderError) return registry;
|
|
1335
|
+
const next = { ...registry };
|
|
1336
|
+
Object.defineProperty(next, "onRenderError", {
|
|
1337
|
+
value: onRenderError,
|
|
1338
|
+
enumerable: false,
|
|
1339
|
+
configurable: true
|
|
1340
|
+
});
|
|
1341
|
+
return next;
|
|
1342
|
+
}, [onRenderError]);
|
|
1343
|
+
const actionHandlers = onAction ? new Proxy(
|
|
1344
|
+
{},
|
|
1345
|
+
{
|
|
1346
|
+
get: (_target, prop) => {
|
|
1347
|
+
return (params) => onAction(prop, params);
|
|
1348
|
+
},
|
|
1349
|
+
has: () => true
|
|
1350
|
+
}
|
|
1351
|
+
) : void 0;
|
|
1352
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1353
|
+
StateProvider,
|
|
1354
|
+
{
|
|
1355
|
+
store,
|
|
1356
|
+
initialState: state,
|
|
1357
|
+
onStateChange,
|
|
1358
|
+
children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(VisibilityProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ValidationProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ActionProvider, { handlers: actionHandlers, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FunctionsContext.Provider, { value: functions ?? EMPTY_FUNCTIONS, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(DirectivesContext.Provider, { value: directiveRegistry, children: [
|
|
1359
|
+
/* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
|
|
1360
|
+
Renderer,
|
|
1361
|
+
{
|
|
1362
|
+
spec,
|
|
1363
|
+
registry: rendererRegistry,
|
|
1364
|
+
loading,
|
|
1365
|
+
fallback
|
|
1366
|
+
}
|
|
1367
|
+
),
|
|
1368
|
+
/* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ConfirmationDialogManager, {})
|
|
1369
|
+
] }) }) }) }) })
|
|
1370
|
+
}
|
|
1371
|
+
);
|
|
1372
|
+
};
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
// src/hooks.ts
|
|
1376
|
+
var import_react7 = require("react");
|
|
1377
|
+
var import_core7 = require("@xmachines/json-render-core");
|
|
1378
|
+
function parseLine(line) {
|
|
1379
|
+
try {
|
|
1380
|
+
const trimmed = line.trim();
|
|
1381
|
+
if (!trimmed || trimmed.startsWith("//")) {
|
|
1382
|
+
return null;
|
|
1383
|
+
}
|
|
1384
|
+
const parsed = JSON.parse(trimmed);
|
|
1385
|
+
if (parsed.__meta === "usage") {
|
|
1386
|
+
return {
|
|
1387
|
+
type: "usage",
|
|
1388
|
+
usage: {
|
|
1389
|
+
promptTokens: parsed.promptTokens ?? 0,
|
|
1390
|
+
completionTokens: parsed.completionTokens ?? 0,
|
|
1391
|
+
totalTokens: parsed.totalTokens ?? 0
|
|
1392
|
+
}
|
|
1393
|
+
};
|
|
1394
|
+
}
|
|
1395
|
+
return { type: "patch", patch: parsed };
|
|
1396
|
+
} catch {
|
|
1397
|
+
return null;
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
function setSpecValue(newSpec, path, value) {
|
|
1401
|
+
if (path === "/root") {
|
|
1402
|
+
newSpec.root = value;
|
|
1403
|
+
return;
|
|
1404
|
+
}
|
|
1405
|
+
if (path === "/state") {
|
|
1406
|
+
newSpec.state = value;
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
if (path.startsWith("/state/")) {
|
|
1410
|
+
if (!newSpec.state) newSpec.state = {};
|
|
1411
|
+
const statePath = path.slice("/state".length);
|
|
1412
|
+
(0, import_core7.setByPath)(newSpec.state, statePath, value);
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
if (path.startsWith("/elements/")) {
|
|
1416
|
+
const pathParts = path.slice("/elements/".length).split("/");
|
|
1417
|
+
const elementKey = pathParts[0];
|
|
1418
|
+
if (!elementKey) return;
|
|
1419
|
+
if (pathParts.length === 1) {
|
|
1420
|
+
newSpec.elements[elementKey] = value;
|
|
1421
|
+
} else {
|
|
1422
|
+
const element = newSpec.elements[elementKey];
|
|
1423
|
+
if (element) {
|
|
1424
|
+
const propPath = "/" + pathParts.slice(1).join("/");
|
|
1425
|
+
const newElement = { ...element };
|
|
1426
|
+
(0, import_core7.setByPath)(
|
|
1427
|
+
newElement,
|
|
1428
|
+
propPath,
|
|
1429
|
+
value
|
|
1430
|
+
);
|
|
1431
|
+
newSpec.elements[elementKey] = newElement;
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
function removeSpecValue(newSpec, path) {
|
|
1437
|
+
if (path === "/state") {
|
|
1438
|
+
delete newSpec.state;
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
if (path.startsWith("/state/") && newSpec.state) {
|
|
1442
|
+
const statePath = path.slice("/state".length);
|
|
1443
|
+
(0, import_core7.removeByPath)(newSpec.state, statePath);
|
|
1444
|
+
return;
|
|
1445
|
+
}
|
|
1446
|
+
if (path.startsWith("/elements/")) {
|
|
1447
|
+
const pathParts = path.slice("/elements/".length).split("/");
|
|
1448
|
+
const elementKey = pathParts[0];
|
|
1449
|
+
if (!elementKey) return;
|
|
1450
|
+
if (pathParts.length === 1) {
|
|
1451
|
+
const { [elementKey]: _, ...rest } = newSpec.elements;
|
|
1452
|
+
newSpec.elements = rest;
|
|
1453
|
+
} else {
|
|
1454
|
+
const element = newSpec.elements[elementKey];
|
|
1455
|
+
if (element) {
|
|
1456
|
+
const propPath = "/" + pathParts.slice(1).join("/");
|
|
1457
|
+
const newElement = { ...element };
|
|
1458
|
+
(0, import_core7.removeByPath)(
|
|
1459
|
+
newElement,
|
|
1460
|
+
propPath
|
|
1461
|
+
);
|
|
1462
|
+
newSpec.elements[elementKey] = newElement;
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
function getSpecValue(spec, path) {
|
|
1468
|
+
if (path === "/root") return spec.root;
|
|
1469
|
+
if (path === "/state") return spec.state;
|
|
1470
|
+
if (path.startsWith("/state/") && spec.state) {
|
|
1471
|
+
const statePath = path.slice("/state".length);
|
|
1472
|
+
return (0, import_core7.getByPath)(spec.state, statePath);
|
|
1473
|
+
}
|
|
1474
|
+
return (0, import_core7.getByPath)(spec, path);
|
|
1475
|
+
}
|
|
1476
|
+
function applyPatch(spec, patch) {
|
|
1477
|
+
const newSpec = {
|
|
1478
|
+
...spec,
|
|
1479
|
+
elements: { ...spec.elements },
|
|
1480
|
+
...spec.state ? { state: { ...spec.state } } : {}
|
|
1481
|
+
};
|
|
1482
|
+
switch (patch.op) {
|
|
1483
|
+
case "add":
|
|
1484
|
+
case "replace": {
|
|
1485
|
+
setSpecValue(newSpec, patch.path, patch.value);
|
|
1486
|
+
break;
|
|
1487
|
+
}
|
|
1488
|
+
case "remove": {
|
|
1489
|
+
removeSpecValue(newSpec, patch.path);
|
|
1490
|
+
break;
|
|
1491
|
+
}
|
|
1492
|
+
case "move": {
|
|
1493
|
+
if (!patch.from) break;
|
|
1494
|
+
const moveValue = getSpecValue(newSpec, patch.from);
|
|
1495
|
+
removeSpecValue(newSpec, patch.from);
|
|
1496
|
+
setSpecValue(newSpec, patch.path, moveValue);
|
|
1497
|
+
break;
|
|
1498
|
+
}
|
|
1499
|
+
case "copy": {
|
|
1500
|
+
if (!patch.from) break;
|
|
1501
|
+
const copyValue = getSpecValue(newSpec, patch.from);
|
|
1502
|
+
setSpecValue(newSpec, patch.path, copyValue);
|
|
1503
|
+
break;
|
|
1504
|
+
}
|
|
1505
|
+
case "test": {
|
|
1506
|
+
break;
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
return newSpec;
|
|
1510
|
+
}
|
|
1511
|
+
function useUIStream({
|
|
1512
|
+
api,
|
|
1513
|
+
onComplete,
|
|
1514
|
+
onError
|
|
1515
|
+
}) {
|
|
1516
|
+
const [spec, setSpec] = (0, import_react7.useState)(null);
|
|
1517
|
+
const [isStreaming, setIsStreaming] = (0, import_react7.useState)(false);
|
|
1518
|
+
const [error, setError] = (0, import_react7.useState)(null);
|
|
1519
|
+
const [usage, setUsage] = (0, import_react7.useState)(null);
|
|
1520
|
+
const [rawLines, setRawLines] = (0, import_react7.useState)([]);
|
|
1521
|
+
const abortControllerRef = (0, import_react7.useRef)(null);
|
|
1522
|
+
const onCompleteRef = (0, import_react7.useRef)(onComplete);
|
|
1523
|
+
onCompleteRef.current = onComplete;
|
|
1524
|
+
const onErrorRef = (0, import_react7.useRef)(onError);
|
|
1525
|
+
onErrorRef.current = onError;
|
|
1526
|
+
const clear = (0, import_react7.useCallback)(() => {
|
|
1527
|
+
setSpec(null);
|
|
1528
|
+
setError(null);
|
|
1529
|
+
}, []);
|
|
1530
|
+
const send = (0, import_react7.useCallback)(
|
|
1531
|
+
async (prompt, context) => {
|
|
1532
|
+
abortControllerRef.current?.abort();
|
|
1533
|
+
abortControllerRef.current = new AbortController();
|
|
1534
|
+
setIsStreaming(true);
|
|
1535
|
+
setError(null);
|
|
1536
|
+
setUsage(null);
|
|
1537
|
+
setRawLines([]);
|
|
1538
|
+
const previousSpec = context?.previousSpec;
|
|
1539
|
+
let currentSpec = previousSpec && previousSpec.root ? { ...previousSpec, elements: { ...previousSpec.elements } } : { root: "", elements: {} };
|
|
1540
|
+
setSpec(currentSpec);
|
|
1541
|
+
try {
|
|
1542
|
+
const response = await fetch(api, {
|
|
1543
|
+
method: "POST",
|
|
1544
|
+
headers: { "Content-Type": "application/json" },
|
|
1545
|
+
body: JSON.stringify({
|
|
1546
|
+
prompt,
|
|
1547
|
+
context,
|
|
1548
|
+
currentSpec
|
|
1549
|
+
}),
|
|
1550
|
+
signal: abortControllerRef.current.signal
|
|
1551
|
+
});
|
|
1552
|
+
if (!response.ok) {
|
|
1553
|
+
let errorMessage = `HTTP error: ${response.status}`;
|
|
1554
|
+
try {
|
|
1555
|
+
const errorData = await response.json();
|
|
1556
|
+
if (errorData.message) {
|
|
1557
|
+
errorMessage = errorData.message;
|
|
1558
|
+
} else if (errorData.error) {
|
|
1559
|
+
errorMessage = errorData.error;
|
|
1560
|
+
}
|
|
1561
|
+
} catch {
|
|
1562
|
+
}
|
|
1563
|
+
throw new Error(errorMessage);
|
|
1564
|
+
}
|
|
1565
|
+
const reader = response.body?.getReader();
|
|
1566
|
+
if (!reader) {
|
|
1567
|
+
throw new Error("No response body");
|
|
1568
|
+
}
|
|
1569
|
+
const decoder = new TextDecoder();
|
|
1570
|
+
let buffer = "";
|
|
1571
|
+
while (true) {
|
|
1572
|
+
const { done, value } = await reader.read();
|
|
1573
|
+
if (done) break;
|
|
1574
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1575
|
+
const lines = buffer.split("\n");
|
|
1576
|
+
buffer = lines.pop() ?? "";
|
|
1577
|
+
for (const line of lines) {
|
|
1578
|
+
const trimmed = line.trim();
|
|
1579
|
+
if (!trimmed) continue;
|
|
1580
|
+
const result = parseLine(trimmed);
|
|
1581
|
+
if (!result) continue;
|
|
1582
|
+
if (result.type === "usage") {
|
|
1583
|
+
setUsage(result.usage);
|
|
1584
|
+
} else {
|
|
1585
|
+
setRawLines((prev) => [...prev, trimmed]);
|
|
1586
|
+
currentSpec = applyPatch(currentSpec, result.patch);
|
|
1587
|
+
setSpec({ ...currentSpec });
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
if (buffer.trim()) {
|
|
1592
|
+
const trimmed = buffer.trim();
|
|
1593
|
+
const result = parseLine(trimmed);
|
|
1594
|
+
if (result) {
|
|
1595
|
+
if (result.type === "usage") {
|
|
1596
|
+
setUsage(result.usage);
|
|
1597
|
+
} else {
|
|
1598
|
+
setRawLines((prev) => [...prev, trimmed]);
|
|
1599
|
+
currentSpec = applyPatch(currentSpec, result.patch);
|
|
1600
|
+
setSpec({ ...currentSpec });
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
onCompleteRef.current?.(currentSpec);
|
|
1605
|
+
} catch (err) {
|
|
1606
|
+
if (err.name === "AbortError") {
|
|
1607
|
+
return;
|
|
1608
|
+
}
|
|
1609
|
+
const error2 = err instanceof Error ? err : new Error(String(err));
|
|
1610
|
+
setError(error2);
|
|
1611
|
+
onErrorRef.current?.(error2);
|
|
1612
|
+
} finally {
|
|
1613
|
+
setIsStreaming(false);
|
|
1614
|
+
}
|
|
1615
|
+
},
|
|
1616
|
+
[api]
|
|
1617
|
+
);
|
|
1618
|
+
(0, import_react7.useEffect)(() => {
|
|
1619
|
+
return () => {
|
|
1620
|
+
abortControllerRef.current?.abort();
|
|
1621
|
+
};
|
|
1622
|
+
}, []);
|
|
1623
|
+
return {
|
|
1624
|
+
spec,
|
|
1625
|
+
isStreaming,
|
|
1626
|
+
error,
|
|
1627
|
+
usage,
|
|
1628
|
+
rawLines,
|
|
1629
|
+
send,
|
|
1630
|
+
clear
|
|
1631
|
+
};
|
|
1632
|
+
}
|
|
1633
|
+
function flatToTree(elements) {
|
|
1634
|
+
const elementMap = {};
|
|
1635
|
+
let root = "";
|
|
1636
|
+
for (const element of elements) {
|
|
1637
|
+
elementMap[element.key] = {
|
|
1638
|
+
type: element.type,
|
|
1639
|
+
props: element.props,
|
|
1640
|
+
children: [],
|
|
1641
|
+
visible: element.visible
|
|
1642
|
+
};
|
|
1643
|
+
}
|
|
1644
|
+
for (const element of elements) {
|
|
1645
|
+
if (element.parentKey) {
|
|
1646
|
+
const parent = elementMap[element.parentKey];
|
|
1647
|
+
if (parent) {
|
|
1648
|
+
if (!parent.children) {
|
|
1649
|
+
parent.children = [];
|
|
1650
|
+
}
|
|
1651
|
+
parent.children.push(element.key);
|
|
1652
|
+
}
|
|
1653
|
+
} else {
|
|
1654
|
+
root = element.key;
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
return { root, elements: elementMap };
|
|
1658
|
+
}
|
|
1659
|
+
function useBoundProp(propValue, bindingPath) {
|
|
1660
|
+
const { set } = useStateStore();
|
|
1661
|
+
const setValue = (0, import_react7.useCallback)(
|
|
1662
|
+
(value) => {
|
|
1663
|
+
if (bindingPath) set(bindingPath, value);
|
|
1664
|
+
},
|
|
1665
|
+
[bindingPath, set]
|
|
1666
|
+
);
|
|
1667
|
+
return [propValue, setValue];
|
|
1668
|
+
}
|
|
1669
|
+
function isSpecDataPart(data) {
|
|
1670
|
+
if (typeof data !== "object" || data === null) return false;
|
|
1671
|
+
const obj = data;
|
|
1672
|
+
switch (obj.type) {
|
|
1673
|
+
case "patch":
|
|
1674
|
+
return typeof obj.patch === "object" && obj.patch !== null;
|
|
1675
|
+
case "flat":
|
|
1676
|
+
case "nested":
|
|
1677
|
+
return typeof obj.spec === "object" && obj.spec !== null;
|
|
1678
|
+
default:
|
|
1679
|
+
return false;
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
function buildSpecFromParts(parts) {
|
|
1683
|
+
const spec = { root: "", elements: {} };
|
|
1684
|
+
let hasSpec = false;
|
|
1685
|
+
for (const part of parts) {
|
|
1686
|
+
if (part.type === import_core7.SPEC_DATA_PART_TYPE) {
|
|
1687
|
+
if (!isSpecDataPart(part.data)) continue;
|
|
1688
|
+
const payload = part.data;
|
|
1689
|
+
if (payload.type === "patch") {
|
|
1690
|
+
hasSpec = true;
|
|
1691
|
+
(0, import_core7.applySpecPatch)(spec, payload.patch);
|
|
1692
|
+
} else if (payload.type === "flat") {
|
|
1693
|
+
hasSpec = true;
|
|
1694
|
+
Object.assign(spec, payload.spec);
|
|
1695
|
+
} else if (payload.type === "nested") {
|
|
1696
|
+
hasSpec = true;
|
|
1697
|
+
const flat = (0, import_core7.nestedToFlat)(payload.spec);
|
|
1698
|
+
Object.assign(spec, flat);
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
return hasSpec ? spec : null;
|
|
1703
|
+
}
|
|
1704
|
+
function getTextFromParts(parts) {
|
|
1705
|
+
return parts.filter(
|
|
1706
|
+
(p) => p.type === "text" && typeof p.text === "string"
|
|
1707
|
+
).map((p) => p.text.trim()).filter(Boolean).join("\n\n");
|
|
1708
|
+
}
|
|
1709
|
+
function useJsonRenderMessage(parts) {
|
|
1710
|
+
const prevPartsRef = (0, import_react7.useRef)([]);
|
|
1711
|
+
const prevResultRef = (0, import_react7.useRef)({
|
|
1712
|
+
spec: null,
|
|
1713
|
+
text: ""
|
|
1714
|
+
});
|
|
1715
|
+
const partsChanged = parts !== prevPartsRef.current && (parts.length !== prevPartsRef.current.length || parts[parts.length - 1] !== prevPartsRef.current[prevPartsRef.current.length - 1]);
|
|
1716
|
+
if (partsChanged || prevPartsRef.current.length === 0) {
|
|
1717
|
+
prevPartsRef.current = parts;
|
|
1718
|
+
prevResultRef.current = {
|
|
1719
|
+
spec: buildSpecFromParts(parts),
|
|
1720
|
+
text: getTextFromParts(parts)
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
const { spec, text } = prevResultRef.current;
|
|
1724
|
+
const hasSpec = spec !== null && Object.keys(spec.elements || {}).length > 0;
|
|
1725
|
+
return { spec, text, hasSpec };
|
|
1726
|
+
}
|
|
1727
|
+
var chatMessageIdCounter = 0;
|
|
1728
|
+
function generateChatId() {
|
|
1729
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
1730
|
+
return crypto.randomUUID();
|
|
1731
|
+
}
|
|
1732
|
+
chatMessageIdCounter += 1;
|
|
1733
|
+
return `msg-${Date.now()}-${chatMessageIdCounter}`;
|
|
1734
|
+
}
|
|
1735
|
+
function useChatUI({
|
|
1736
|
+
api,
|
|
1737
|
+
onComplete,
|
|
1738
|
+
onError
|
|
1739
|
+
}) {
|
|
1740
|
+
const [messages, setMessages] = (0, import_react7.useState)([]);
|
|
1741
|
+
const [isStreaming, setIsStreaming] = (0, import_react7.useState)(false);
|
|
1742
|
+
const [error, setError] = (0, import_react7.useState)(null);
|
|
1743
|
+
const abortControllerRef = (0, import_react7.useRef)(null);
|
|
1744
|
+
const messagesRef = (0, import_react7.useRef)(messages);
|
|
1745
|
+
messagesRef.current = messages;
|
|
1746
|
+
const onCompleteRef = (0, import_react7.useRef)(onComplete);
|
|
1747
|
+
onCompleteRef.current = onComplete;
|
|
1748
|
+
const onErrorRef = (0, import_react7.useRef)(onError);
|
|
1749
|
+
onErrorRef.current = onError;
|
|
1750
|
+
const clear = (0, import_react7.useCallback)(() => {
|
|
1751
|
+
setMessages([]);
|
|
1752
|
+
setError(null);
|
|
1753
|
+
}, []);
|
|
1754
|
+
const send = (0, import_react7.useCallback)(
|
|
1755
|
+
async (text) => {
|
|
1756
|
+
if (!text.trim()) return;
|
|
1757
|
+
abortControllerRef.current?.abort();
|
|
1758
|
+
abortControllerRef.current = new AbortController();
|
|
1759
|
+
const userMessage = {
|
|
1760
|
+
id: generateChatId(),
|
|
1761
|
+
role: "user",
|
|
1762
|
+
text: text.trim(),
|
|
1763
|
+
spec: null
|
|
1764
|
+
};
|
|
1765
|
+
const assistantId = generateChatId();
|
|
1766
|
+
const assistantMessage = {
|
|
1767
|
+
id: assistantId,
|
|
1768
|
+
role: "assistant",
|
|
1769
|
+
text: "",
|
|
1770
|
+
spec: null
|
|
1771
|
+
};
|
|
1772
|
+
setMessages((prev) => [...prev, userMessage, assistantMessage]);
|
|
1773
|
+
setIsStreaming(true);
|
|
1774
|
+
setError(null);
|
|
1775
|
+
const historyForApi = [
|
|
1776
|
+
...messagesRef.current.map((m) => ({
|
|
1777
|
+
role: m.role,
|
|
1778
|
+
content: m.text
|
|
1779
|
+
})),
|
|
1780
|
+
{ role: "user", content: text.trim() }
|
|
1781
|
+
];
|
|
1782
|
+
let accumulatedText = "";
|
|
1783
|
+
let currentSpec = { root: "", elements: {} };
|
|
1784
|
+
let hasSpec = false;
|
|
1785
|
+
try {
|
|
1786
|
+
const response = await fetch(api, {
|
|
1787
|
+
method: "POST",
|
|
1788
|
+
headers: { "Content-Type": "application/json" },
|
|
1789
|
+
body: JSON.stringify({ messages: historyForApi }),
|
|
1790
|
+
signal: abortControllerRef.current.signal
|
|
1791
|
+
});
|
|
1792
|
+
if (!response.ok) {
|
|
1793
|
+
let errorMessage = `HTTP error: ${response.status}`;
|
|
1794
|
+
try {
|
|
1795
|
+
const errorData = await response.json();
|
|
1796
|
+
if (errorData.message) {
|
|
1797
|
+
errorMessage = errorData.message;
|
|
1798
|
+
} else if (errorData.error) {
|
|
1799
|
+
errorMessage = errorData.error;
|
|
1800
|
+
}
|
|
1801
|
+
} catch {
|
|
1802
|
+
}
|
|
1803
|
+
throw new Error(errorMessage);
|
|
1804
|
+
}
|
|
1805
|
+
const reader = response.body?.getReader();
|
|
1806
|
+
if (!reader) {
|
|
1807
|
+
throw new Error("No response body");
|
|
1808
|
+
}
|
|
1809
|
+
const decoder = new TextDecoder();
|
|
1810
|
+
const parser = (0, import_core7.createMixedStreamParser)({
|
|
1811
|
+
onPatch(patch) {
|
|
1812
|
+
hasSpec = true;
|
|
1813
|
+
(0, import_core7.applySpecPatch)(currentSpec, patch);
|
|
1814
|
+
setMessages(
|
|
1815
|
+
(prev) => prev.map(
|
|
1816
|
+
(m) => m.id === assistantId ? {
|
|
1817
|
+
...m,
|
|
1818
|
+
spec: {
|
|
1819
|
+
root: currentSpec.root,
|
|
1820
|
+
elements: { ...currentSpec.elements },
|
|
1821
|
+
...currentSpec.state ? { state: { ...currentSpec.state } } : {}
|
|
1822
|
+
}
|
|
1823
|
+
} : m
|
|
1824
|
+
)
|
|
1825
|
+
);
|
|
1826
|
+
},
|
|
1827
|
+
onText(line) {
|
|
1828
|
+
accumulatedText += (accumulatedText ? "\n" : "") + line;
|
|
1829
|
+
setMessages(
|
|
1830
|
+
(prev) => prev.map(
|
|
1831
|
+
(m) => m.id === assistantId ? { ...m, text: accumulatedText } : m
|
|
1832
|
+
)
|
|
1833
|
+
);
|
|
1834
|
+
}
|
|
1835
|
+
});
|
|
1836
|
+
while (true) {
|
|
1837
|
+
const { done, value } = await reader.read();
|
|
1838
|
+
if (done) break;
|
|
1839
|
+
parser.push(decoder.decode(value, { stream: true }));
|
|
1840
|
+
}
|
|
1841
|
+
parser.flush();
|
|
1842
|
+
const finalMessage = {
|
|
1843
|
+
id: assistantId,
|
|
1844
|
+
role: "assistant",
|
|
1845
|
+
text: accumulatedText,
|
|
1846
|
+
spec: hasSpec ? {
|
|
1847
|
+
root: currentSpec.root,
|
|
1848
|
+
elements: { ...currentSpec.elements },
|
|
1849
|
+
...currentSpec.state ? { state: { ...currentSpec.state } } : {}
|
|
1850
|
+
} : null
|
|
1851
|
+
};
|
|
1852
|
+
onCompleteRef.current?.(finalMessage);
|
|
1853
|
+
} catch (err) {
|
|
1854
|
+
if (err.name === "AbortError") {
|
|
1855
|
+
return;
|
|
1856
|
+
}
|
|
1857
|
+
const resolvedError = err instanceof Error ? err : new Error(String(err));
|
|
1858
|
+
setError(resolvedError);
|
|
1859
|
+
setMessages(
|
|
1860
|
+
(prev) => prev.filter((m) => m.id !== assistantId || m.text.length > 0)
|
|
1861
|
+
);
|
|
1862
|
+
onErrorRef.current?.(resolvedError);
|
|
1863
|
+
} finally {
|
|
1864
|
+
setIsStreaming(false);
|
|
1865
|
+
}
|
|
1866
|
+
},
|
|
1867
|
+
[api]
|
|
1868
|
+
);
|
|
1869
|
+
(0, import_react7.useEffect)(() => {
|
|
1870
|
+
return () => {
|
|
1871
|
+
abortControllerRef.current?.abort();
|
|
1872
|
+
};
|
|
1873
|
+
}, []);
|
|
1874
|
+
return {
|
|
1875
|
+
messages,
|
|
1876
|
+
isStreaming,
|
|
1877
|
+
error,
|
|
1878
|
+
send,
|
|
1879
|
+
clear
|
|
1880
|
+
};
|
|
1881
|
+
}
|
|
1882
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1883
|
+
0 && (module.exports = {
|
|
1884
|
+
ActionProvider,
|
|
1885
|
+
ConfirmDialog,
|
|
1886
|
+
JSONUIProvider,
|
|
1887
|
+
Renderer,
|
|
1888
|
+
RepeatScopeProvider,
|
|
1889
|
+
StateProvider,
|
|
1890
|
+
ValidationProvider,
|
|
1891
|
+
VisibilityProvider,
|
|
1892
|
+
buildSpecFromParts,
|
|
1893
|
+
createRenderer,
|
|
1894
|
+
createStateStore,
|
|
1895
|
+
defineRegistry,
|
|
1896
|
+
elementTreeSchema,
|
|
1897
|
+
flatToTree,
|
|
1898
|
+
getTextFromParts,
|
|
1899
|
+
schema,
|
|
1900
|
+
useAction,
|
|
1901
|
+
useActions,
|
|
1902
|
+
useBoundProp,
|
|
1903
|
+
useChatUI,
|
|
1904
|
+
useFieldValidation,
|
|
1905
|
+
useIsVisible,
|
|
1906
|
+
useJsonRenderMessage,
|
|
1907
|
+
useOptionalValidation,
|
|
1908
|
+
useRepeatScope,
|
|
1909
|
+
useStateBinding,
|
|
1910
|
+
useStateStore,
|
|
1911
|
+
useStateValue,
|
|
1912
|
+
useUIStream,
|
|
1913
|
+
useValidation,
|
|
1914
|
+
useVisibility
|
|
1915
|
+
});
|
|
1916
|
+
//# sourceMappingURL=index.js.map
|