cogsbox-state 0.5.216 → 0.5.218
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/CogsState.jsx +89 -99
- package/dist/CogsState.jsx.map +1 -1
- package/package.json +1 -1
- package/src/CogsState.tsx +27 -44
package/dist/CogsState.jsx
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx as ye } from "react/jsx-runtime";
|
|
3
3
|
import { useState as de, useRef as te, useEffect as ue, useLayoutEffect as $e, useMemo as Te, createElement as ae, useSyncExternalStore as Ve, startTransition as Ne } from "react";
|
|
4
|
-
import { transformStateFunc as Ae, isDeepEqual as
|
|
4
|
+
import { transformStateFunc as Ae, isDeepEqual as W, isFunction as J, getNestedValue as G, getDifferences as ge, debounce as be } from "./utility.js";
|
|
5
5
|
import { pushFunc as ce, updateFn as Q, cutFunc as ee, ValidationWrapper as Pe, FormControlComponent as _e } from "./Functions.jsx";
|
|
6
6
|
import xe from "superjson";
|
|
7
7
|
import { v4 as fe } from "uuid";
|
|
8
8
|
import "zod";
|
|
9
9
|
import { getGlobalStore as r, formRefStore as ve } from "./store.js";
|
|
10
|
-
import { useCogsConfig as
|
|
10
|
+
import { useCogsConfig as pe } from "./CogsStateClient.jsx";
|
|
11
11
|
import { applyPatch as Ce } from "fast-json-patch";
|
|
12
12
|
function he(e, i) {
|
|
13
13
|
const v = r.getState().getInitialOptions, u = r.getState().setInitialStateOptions, S = v(e) || {};
|
|
@@ -21,13 +21,13 @@ function Ie({
|
|
|
21
21
|
options: i,
|
|
22
22
|
initialOptionsPart: v
|
|
23
23
|
}) {
|
|
24
|
-
const u = Y(e) || {}, S = v[e] || {}, E = r.getState().setInitialStateOptions,
|
|
24
|
+
const u = Y(e) || {}, S = v[e] || {}, E = r.getState().setInitialStateOptions, w = { ...S, ...u };
|
|
25
25
|
let h = !1;
|
|
26
26
|
if (i)
|
|
27
27
|
for (const s in i)
|
|
28
|
-
|
|
29
|
-
!
|
|
30
|
-
h && E(e,
|
|
28
|
+
w.hasOwnProperty(s) ? (s == "localStorage" && i[s] && w[s].key !== i[s]?.key && (h = !0, w[s] = i[s]), s == "initialState" && i[s] && w[s] !== i[s] && // Different references
|
|
29
|
+
!W(w[s], i[s]) && (h = !0, w[s] = i[s])) : (h = !0, w[s] = i[s]);
|
|
30
|
+
h && E(e, w);
|
|
31
31
|
}
|
|
32
32
|
function Ke(e, { formElements: i, validation: v }) {
|
|
33
33
|
return { initialState: e, formElements: i, validation: v };
|
|
@@ -69,10 +69,10 @@ const et = (e, i) => {
|
|
|
69
69
|
);
|
|
70
70
|
return _;
|
|
71
71
|
};
|
|
72
|
-
function
|
|
72
|
+
function w(h, s) {
|
|
73
73
|
Ie({ stateKey: h, options: s, initialOptionsPart: S }), s.localStorage && Ue(h, s), ie(h);
|
|
74
74
|
}
|
|
75
|
-
return { useCogsState: E, setCogsOptions:
|
|
75
|
+
return { useCogsState: E, setCogsOptions: w };
|
|
76
76
|
}, {
|
|
77
77
|
setUpdaterState: ne,
|
|
78
78
|
setState: H,
|
|
@@ -84,7 +84,7 @@ const et = (e, i) => {
|
|
|
84
84
|
addValidationError: Re,
|
|
85
85
|
removeValidationError: B,
|
|
86
86
|
setServerSyncActions: je
|
|
87
|
-
} = r.getState(),
|
|
87
|
+
} = r.getState(), we = (e, i, v, u, S) => {
|
|
88
88
|
v?.log && console.log(
|
|
89
89
|
"saving to localstorage",
|
|
90
90
|
i,
|
|
@@ -93,10 +93,10 @@ const et = (e, i) => {
|
|
|
93
93
|
);
|
|
94
94
|
const E = J(v?.localStorage?.key) ? v.localStorage?.key(e) : v?.localStorage?.key;
|
|
95
95
|
if (E && u) {
|
|
96
|
-
const
|
|
96
|
+
const w = `${u}-${i}-${E}`;
|
|
97
97
|
let h;
|
|
98
98
|
try {
|
|
99
|
-
h = oe(
|
|
99
|
+
h = oe(w)?.lastSyncedWithServer;
|
|
100
100
|
} catch {
|
|
101
101
|
}
|
|
102
102
|
const s = {
|
|
@@ -105,7 +105,7 @@ const et = (e, i) => {
|
|
|
105
105
|
lastSyncedWithServer: S ?? h
|
|
106
106
|
}, m = xe.serialize(s);
|
|
107
107
|
window.localStorage.setItem(
|
|
108
|
-
|
|
108
|
+
w,
|
|
109
109
|
JSON.stringify(m.json)
|
|
110
110
|
);
|
|
111
111
|
}
|
|
@@ -118,7 +118,7 @@ const et = (e, i) => {
|
|
|
118
118
|
return console.error("Error loading from localStorage:", i), null;
|
|
119
119
|
}
|
|
120
120
|
}, Ue = (e, i) => {
|
|
121
|
-
const v = r.getState().cogsStateStore[e], { sessionId: u } =
|
|
121
|
+
const v = r.getState().cogsStateStore[e], { sessionId: u } = pe(), S = J(i?.localStorage?.key) ? i.localStorage.key(v) : i?.localStorage?.key;
|
|
122
122
|
if (S && u) {
|
|
123
123
|
const E = oe(
|
|
124
124
|
`${u}-${e}-${S}`
|
|
@@ -128,7 +128,7 @@ const et = (e, i) => {
|
|
|
128
128
|
}
|
|
129
129
|
return !1;
|
|
130
130
|
}, ke = (e, i, v, u, S, E) => {
|
|
131
|
-
const
|
|
131
|
+
const w = {
|
|
132
132
|
initialState: i,
|
|
133
133
|
updaterState: re(
|
|
134
134
|
e,
|
|
@@ -138,7 +138,7 @@ const et = (e, i) => {
|
|
|
138
138
|
),
|
|
139
139
|
state: v
|
|
140
140
|
};
|
|
141
|
-
Se(e,
|
|
141
|
+
Se(e, w.initialState), ne(e, w.updaterState), H(e, w.state);
|
|
142
142
|
}, ie = (e) => {
|
|
143
143
|
const i = r.getState().stateComponents.get(e);
|
|
144
144
|
if (!i) return;
|
|
@@ -160,18 +160,18 @@ const et = (e, i) => {
|
|
|
160
160
|
switch (e) {
|
|
161
161
|
case "update":
|
|
162
162
|
return {
|
|
163
|
-
oldValue:
|
|
164
|
-
newValue:
|
|
163
|
+
oldValue: G(i, u),
|
|
164
|
+
newValue: G(v, u)
|
|
165
165
|
};
|
|
166
166
|
case "insert":
|
|
167
167
|
return {
|
|
168
168
|
oldValue: null,
|
|
169
169
|
// or undefined
|
|
170
|
-
newValue:
|
|
170
|
+
newValue: G(v, u)
|
|
171
171
|
};
|
|
172
172
|
case "cut":
|
|
173
173
|
return {
|
|
174
|
-
oldValue:
|
|
174
|
+
oldValue: G(i, u),
|
|
175
175
|
newValue: null
|
|
176
176
|
// or undefined
|
|
177
177
|
};
|
|
@@ -185,14 +185,14 @@ function De(e, {
|
|
|
185
185
|
localStorage: u,
|
|
186
186
|
formElements: S,
|
|
187
187
|
reactiveDeps: E,
|
|
188
|
-
reactiveType:
|
|
188
|
+
reactiveType: w,
|
|
189
189
|
componentId: h,
|
|
190
190
|
initialState: s,
|
|
191
191
|
syncUpdate: m,
|
|
192
192
|
dependencies: n,
|
|
193
193
|
serverState: y
|
|
194
194
|
} = {}) {
|
|
195
|
-
const [j, _] = de({}), { sessionId: x } =
|
|
195
|
+
const [j, _] = de({}), { sessionId: x } = pe();
|
|
196
196
|
let U = !i;
|
|
197
197
|
const [f] = de(i ?? fe()), c = r.getState().stateLog[f], K = te(/* @__PURE__ */ new Set()), L = te(h ?? fe()), A = te(
|
|
198
198
|
null
|
|
@@ -215,21 +215,21 @@ function De(e, {
|
|
|
215
215
|
initialState: s
|
|
216
216
|
});
|
|
217
217
|
const t = A.current, o = t?.serverState?.id !== void 0 && t?.serverState?.status === "success" && t?.serverState?.data, d = r.getState().initialStateGlobal[f];
|
|
218
|
-
if (!(d && !
|
|
218
|
+
if (!(d && !W(d, s) || !d) && !o)
|
|
219
219
|
return;
|
|
220
220
|
let g = null;
|
|
221
221
|
const N = J(t?.localStorage?.key) ? t?.localStorage?.key(s) : t?.localStorage?.key;
|
|
222
222
|
N && x && (g = oe(`${x}-${f}-${N}`));
|
|
223
|
-
let
|
|
223
|
+
let p = s, $ = !1;
|
|
224
224
|
const F = o ? Date.now() : 0, b = g?.lastUpdated || 0, M = g?.lastSyncedWithServer || 0;
|
|
225
|
-
o && F > b ? (
|
|
225
|
+
o && F > b ? (p = t.serverState.data, $ = !0) : g && b > M && (p = g.state, t?.localStorage?.onChange && t?.localStorage?.onChange(p)), ke(
|
|
226
226
|
f,
|
|
227
227
|
s,
|
|
228
|
-
|
|
228
|
+
p,
|
|
229
229
|
X,
|
|
230
230
|
L.current,
|
|
231
231
|
x
|
|
232
|
-
), $ && N && x &&
|
|
232
|
+
), $ && N && x && we(p, f, t, x, Date.now()), ie(f), (Array.isArray(w) ? w : [w || "component"]).includes("none") || _({});
|
|
233
233
|
}
|
|
234
234
|
}, [
|
|
235
235
|
s,
|
|
@@ -252,7 +252,7 @@ function De(e, {
|
|
|
252
252
|
paths: /* @__PURE__ */ new Set(),
|
|
253
253
|
deps: [],
|
|
254
254
|
depsFunction: E || void 0,
|
|
255
|
-
reactiveType:
|
|
255
|
+
reactiveType: w ?? ["component", "deps"]
|
|
256
256
|
}), r.getState().stateComponents.set(f, a), _({}), () => {
|
|
257
257
|
const o = `${f}////${L.current}`;
|
|
258
258
|
a && (a.components.delete(o), a.components.size === 0 && r.getState().stateComponents.delete(f));
|
|
@@ -268,7 +268,7 @@ function De(e, {
|
|
|
268
268
|
if (N) {
|
|
269
269
|
let R = !1, k = r.getState().signalDomElements.get(N);
|
|
270
270
|
if ((!k || k.size === 0) && (o.updateType === "insert" || o.updateType === "cut")) {
|
|
271
|
-
const O = a.slice(0, -1), C =
|
|
271
|
+
const O = a.slice(0, -1), C = G(g, O);
|
|
272
272
|
if (Array.isArray(C)) {
|
|
273
273
|
R = !0;
|
|
274
274
|
const P = `${f}-${O.join(".")}`;
|
|
@@ -276,7 +276,7 @@ function De(e, {
|
|
|
276
276
|
}
|
|
277
277
|
}
|
|
278
278
|
if (k) {
|
|
279
|
-
const O = R ?
|
|
279
|
+
const O = R ? G(g, a.slice(0, -1)) : G(g, a);
|
|
280
280
|
k.forEach(({ parentId: C, position: P, effect: T }) => {
|
|
281
281
|
const V = document.querySelector(
|
|
282
282
|
`[data-parent-id="${C}"]`
|
|
@@ -294,15 +294,15 @@ function De(e, {
|
|
|
294
294
|
o.updateType === "update" && (d || A.current?.validation?.key) && a && B(
|
|
295
295
|
(d || A.current?.validation?.key) + "." + a.join(".")
|
|
296
296
|
);
|
|
297
|
-
const
|
|
297
|
+
const p = a.slice(0, a.length - 1);
|
|
298
298
|
o.updateType === "cut" && A.current?.validation?.key && B(
|
|
299
|
-
A.current?.validation?.key + "." +
|
|
299
|
+
A.current?.validation?.key + "." + p.join(".")
|
|
300
300
|
), o.updateType === "insert" && A.current?.validation?.key && Oe(
|
|
301
|
-
A.current?.validation?.key + "." +
|
|
301
|
+
A.current?.validation?.key + "." + p.join(".")
|
|
302
302
|
).filter(([k, O]) => {
|
|
303
303
|
let C = k?.split(".").length;
|
|
304
|
-
if (k ==
|
|
305
|
-
let P = k + "." +
|
|
304
|
+
if (k == p.join(".") && C == p.length - 1) {
|
|
305
|
+
let P = k + "." + p;
|
|
306
306
|
B(k), Re(P, O);
|
|
307
307
|
}
|
|
308
308
|
});
|
|
@@ -351,7 +351,7 @@ function De(e, {
|
|
|
351
351
|
if (!V && Z.includes("deps") && T.depsFunction) {
|
|
352
352
|
const z = T.depsFunction(g);
|
|
353
353
|
let D = !1;
|
|
354
|
-
typeof z == "boolean" ? z && (D = !0) :
|
|
354
|
+
typeof z == "boolean" ? z && (D = !0) : W(T.deps, z) || (T.deps = z, D = !0), D && (V = !0);
|
|
355
355
|
}
|
|
356
356
|
V && C.push(T.forceUpdate);
|
|
357
357
|
}
|
|
@@ -362,7 +362,7 @@ function De(e, {
|
|
|
362
362
|
}
|
|
363
363
|
const F = Date.now();
|
|
364
364
|
a = a.map((R, k) => {
|
|
365
|
-
const O = a.slice(0, -1), C =
|
|
365
|
+
const O = a.slice(0, -1), C = G(g, O);
|
|
366
366
|
return k === a.length - 1 && ["insert", "cut"].includes(o.updateType) ? (C.length - 1).toString() : R;
|
|
367
367
|
});
|
|
368
368
|
const { oldValue: b, newValue: M } = Me(
|
|
@@ -385,7 +385,7 @@ function De(e, {
|
|
|
385
385
|
return V ? (V.timeStamp = Math.max(V.timeStamp, P.timeStamp), V.newValue = P.newValue, V.oldValue = V.oldValue ?? P.oldValue, V.updateType = P.updateType) : C.set(T, { ...P }), C;
|
|
386
386
|
}, /* @__PURE__ */ new Map());
|
|
387
387
|
return Array.from(O.values());
|
|
388
|
-
}),
|
|
388
|
+
}), we(
|
|
389
389
|
g,
|
|
390
390
|
f,
|
|
391
391
|
A.current,
|
|
@@ -425,7 +425,7 @@ function De(e, {
|
|
|
425
425
|
function re(e, i, v, u) {
|
|
426
426
|
const S = /* @__PURE__ */ new Map();
|
|
427
427
|
let E = 0;
|
|
428
|
-
const
|
|
428
|
+
const w = (m) => {
|
|
429
429
|
const n = m.join(".");
|
|
430
430
|
for (const [y] of S)
|
|
431
431
|
(y === n || y.startsWith(n + ".")) && S.delete(y);
|
|
@@ -469,7 +469,7 @@ function re(e, i, v, u) {
|
|
|
469
469
|
_isLoading: r.getState().isLoadingGlobal[e],
|
|
470
470
|
_isServerSynced: () => {
|
|
471
471
|
const m = r.getState().serverState[e];
|
|
472
|
-
return !!(m &&
|
|
472
|
+
return !!(m && W(m, Ee(e)));
|
|
473
473
|
}
|
|
474
474
|
};
|
|
475
475
|
function s(m, n = [], y) {
|
|
@@ -509,32 +509,22 @@ function re(e, i, v, u) {
|
|
|
509
509
|
"removeStorage",
|
|
510
510
|
"middleware"
|
|
511
511
|
]);
|
|
512
|
-
if (
|
|
512
|
+
if (c !== "then" && !c.startsWith("$") && c !== "stateMapNoRender" && !K.has(c)) {
|
|
513
|
+
console.log("adding path start", n, c);
|
|
513
514
|
const l = `${e}////${v}`, t = r.getState().stateComponents.get(e);
|
|
514
515
|
if (t) {
|
|
515
516
|
const a = t.components.get(l);
|
|
516
|
-
if (a
|
|
517
|
-
if (
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
for (const I of a.paths) {
|
|
526
|
-
if (I === o) {
|
|
527
|
-
d = !1;
|
|
528
|
-
break;
|
|
529
|
-
}
|
|
530
|
-
if (I.length < o.length && o[I.length] === "." && o.substring(0, I.length) === I) {
|
|
531
|
-
d = !1;
|
|
532
|
-
break;
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
d && (console.log("adding path to component", o, c), a.paths.add(o));
|
|
517
|
+
if (a) {
|
|
518
|
+
if (a.paths.has(""))
|
|
519
|
+
return;
|
|
520
|
+
const o = [...n, c].join(".");
|
|
521
|
+
let d = !0;
|
|
522
|
+
for (const I of a.paths)
|
|
523
|
+
if (o.startsWith(I) && (o === I || o[I.length] === ".")) {
|
|
524
|
+
d = !1;
|
|
525
|
+
break;
|
|
536
526
|
}
|
|
537
|
-
|
|
527
|
+
d && (console.log("adding path addimg", o, c), a.paths.add(o));
|
|
538
528
|
}
|
|
539
529
|
}
|
|
540
530
|
}
|
|
@@ -567,16 +557,16 @@ function re(e, i, v, u) {
|
|
|
567
557
|
}
|
|
568
558
|
};
|
|
569
559
|
if (c === "_status") {
|
|
570
|
-
const l = r.getState().getNestedState(e, n), t = r.getState().initialStateGlobal[e], a =
|
|
571
|
-
return
|
|
560
|
+
const l = r.getState().getNestedState(e, n), t = r.getState().initialStateGlobal[e], a = G(t, n);
|
|
561
|
+
return W(l, a) ? "fresh" : "stale";
|
|
572
562
|
}
|
|
573
563
|
if (c === "getStatus")
|
|
574
564
|
return function() {
|
|
575
565
|
const l = r().getNestedState(
|
|
576
566
|
e,
|
|
577
567
|
n
|
|
578
|
-
), t = r.getState().initialStateGlobal[e], a =
|
|
579
|
-
return
|
|
568
|
+
), t = r.getState().initialStateGlobal[e], a = G(t, n);
|
|
569
|
+
return W(l, a) ? "fresh" : "stale";
|
|
580
570
|
};
|
|
581
571
|
if (c === "removeStorage")
|
|
582
572
|
return () => {
|
|
@@ -652,7 +642,7 @@ function re(e, i, v, u) {
|
|
|
652
642
|
);
|
|
653
643
|
});
|
|
654
644
|
if (c === "$stateMap")
|
|
655
|
-
return (t) => ae(
|
|
645
|
+
return (t) => ae(We, {
|
|
656
646
|
proxy: {
|
|
657
647
|
_stateKey: e,
|
|
658
648
|
_path: n,
|
|
@@ -687,7 +677,7 @@ function re(e, i, v, u) {
|
|
|
687
677
|
return s(o, d);
|
|
688
678
|
};
|
|
689
679
|
if (c === "insert")
|
|
690
|
-
return (t) => (
|
|
680
|
+
return (t) => (w(n), ce(i, t, n, e), s(
|
|
691
681
|
r.getState().getNestedState(e, n),
|
|
692
682
|
n
|
|
693
683
|
));
|
|
@@ -695,28 +685,28 @@ function re(e, i, v, u) {
|
|
|
695
685
|
return (t, a, o) => {
|
|
696
686
|
const d = r.getState().getNestedState(e, n), I = J(t) ? t(d) : t;
|
|
697
687
|
let g = null;
|
|
698
|
-
if (!d.some((
|
|
688
|
+
if (!d.some((p) => {
|
|
699
689
|
if (a) {
|
|
700
690
|
const F = a.every(
|
|
701
|
-
(b) =>
|
|
691
|
+
(b) => W(p[b], I[b])
|
|
702
692
|
);
|
|
703
|
-
return F && (g =
|
|
693
|
+
return F && (g = p), F;
|
|
704
694
|
}
|
|
705
|
-
const $ =
|
|
706
|
-
return $ && (g =
|
|
695
|
+
const $ = W(p, I);
|
|
696
|
+
return $ && (g = p), $;
|
|
707
697
|
}))
|
|
708
|
-
|
|
698
|
+
w(n), ce(i, I, n, e);
|
|
709
699
|
else if (o && g) {
|
|
710
|
-
const
|
|
711
|
-
(F) =>
|
|
700
|
+
const p = o(g), $ = d.map(
|
|
701
|
+
(F) => W(F, g) ? p : F
|
|
712
702
|
);
|
|
713
|
-
|
|
703
|
+
w(n), Q(i, $, n);
|
|
714
704
|
}
|
|
715
705
|
};
|
|
716
706
|
if (c === "cut")
|
|
717
707
|
return (t, a) => {
|
|
718
708
|
if (!a?.waitForSync)
|
|
719
|
-
return
|
|
709
|
+
return w(n), ee(i, n, e, t), s(
|
|
720
710
|
r.getState().getNestedState(e, n),
|
|
721
711
|
n
|
|
722
712
|
);
|
|
@@ -795,7 +785,7 @@ function re(e, i, v, u) {
|
|
|
795
785
|
const t = n.slice(0, -1), a = Number(n[n.length - 1]), o = t.join(".");
|
|
796
786
|
l ? r.getState().setSelectedIndex(e, o, a) : r.getState().setSelectedIndex(e, o, void 0);
|
|
797
787
|
const d = r.getState().getNestedState(e, [...t]);
|
|
798
|
-
Q(i, d, t),
|
|
788
|
+
Q(i, d, t), w(t);
|
|
799
789
|
};
|
|
800
790
|
if (c === "toggleSelected")
|
|
801
791
|
return () => {
|
|
@@ -806,7 +796,7 @@ function re(e, i, v, u) {
|
|
|
806
796
|
o === t ? void 0 : t
|
|
807
797
|
);
|
|
808
798
|
const d = r.getState().getNestedState(e, [...l]);
|
|
809
|
-
Q(i, d, l),
|
|
799
|
+
Q(i, d, l), w(l);
|
|
810
800
|
};
|
|
811
801
|
if (n.length == 0) {
|
|
812
802
|
if (c === "applyJsonPatch")
|
|
@@ -825,25 +815,25 @@ function re(e, i, v, u) {
|
|
|
825
815
|
const I = ge(t, o), g = new Set(I);
|
|
826
816
|
for (const [
|
|
827
817
|
N,
|
|
828
|
-
|
|
818
|
+
p
|
|
829
819
|
] of d.components.entries()) {
|
|
830
820
|
let $ = !1;
|
|
831
|
-
const F = Array.isArray(
|
|
821
|
+
const F = Array.isArray(p.reactiveType) ? p.reactiveType : [p.reactiveType || "component"];
|
|
832
822
|
if (!F.includes("none")) {
|
|
833
823
|
if (F.includes("all")) {
|
|
834
|
-
|
|
824
|
+
p.forceUpdate();
|
|
835
825
|
continue;
|
|
836
826
|
}
|
|
837
|
-
if (F.includes("component") && (
|
|
827
|
+
if (F.includes("component") && (p.paths.has("") && ($ = !0), !$))
|
|
838
828
|
for (const b of g) {
|
|
839
|
-
if (
|
|
829
|
+
if (p.paths.has(b)) {
|
|
840
830
|
$ = !0;
|
|
841
831
|
break;
|
|
842
832
|
}
|
|
843
833
|
let M = b.lastIndexOf(".");
|
|
844
834
|
for (; M !== -1; ) {
|
|
845
835
|
const q = b.substring(0, M);
|
|
846
|
-
if (
|
|
836
|
+
if (p.paths.has(q)) {
|
|
847
837
|
$ = !0;
|
|
848
838
|
break;
|
|
849
839
|
}
|
|
@@ -857,7 +847,7 @@ function re(e, i, v, u) {
|
|
|
857
847
|
0,
|
|
858
848
|
k
|
|
859
849
|
);
|
|
860
|
-
if (
|
|
850
|
+
if (p.paths.has(O)) {
|
|
861
851
|
$ = !0;
|
|
862
852
|
break;
|
|
863
853
|
}
|
|
@@ -867,12 +857,12 @@ function re(e, i, v, u) {
|
|
|
867
857
|
}
|
|
868
858
|
if ($) break;
|
|
869
859
|
}
|
|
870
|
-
if (!$ && F.includes("deps") &&
|
|
871
|
-
const b =
|
|
860
|
+
if (!$ && F.includes("deps") && p.depsFunction) {
|
|
861
|
+
const b = p.depsFunction(o);
|
|
872
862
|
let M = !1;
|
|
873
|
-
typeof b == "boolean" ? b && (M = !0) :
|
|
863
|
+
typeof b == "boolean" ? b && (M = !0) : W(p.deps, b) || (p.deps = b, M = !0), M && ($ = !0);
|
|
874
864
|
}
|
|
875
|
-
$ &&
|
|
865
|
+
$ && p.forceUpdate();
|
|
876
866
|
}
|
|
877
867
|
}
|
|
878
868
|
}
|
|
@@ -893,8 +883,8 @@ function re(e, i, v, u) {
|
|
|
893
883
|
});
|
|
894
884
|
const d = l.zodSchema.safeParse(a);
|
|
895
885
|
return d.success ? !0 : (d.error.errors.forEach((g) => {
|
|
896
|
-
const N = g.path,
|
|
897
|
-
t($,
|
|
886
|
+
const N = g.path, p = g.message, $ = [l.key, ...N].join(".");
|
|
887
|
+
t($, p);
|
|
898
888
|
}), ie(e), !1);
|
|
899
889
|
} catch (o) {
|
|
900
890
|
return console.error("Zod schema validation failed", o), !1;
|
|
@@ -949,7 +939,7 @@ function re(e, i, v, u) {
|
|
|
949
939
|
const a = r.getState().getNestedState(e, n);
|
|
950
940
|
t?.afterUpdate && t.afterUpdate(a);
|
|
951
941
|
}
|
|
952
|
-
|
|
942
|
+
w(n);
|
|
953
943
|
};
|
|
954
944
|
if (c === "formElement")
|
|
955
945
|
return (l, t) => /* @__PURE__ */ ye(
|
|
@@ -976,9 +966,9 @@ function re(e, i, v, u) {
|
|
|
976
966
|
);
|
|
977
967
|
}
|
|
978
968
|
function le(e) {
|
|
979
|
-
return ae(
|
|
969
|
+
return ae(Ge, { proxy: e });
|
|
980
970
|
}
|
|
981
|
-
function
|
|
971
|
+
function We({
|
|
982
972
|
proxy: e,
|
|
983
973
|
rebuildStateShape: i
|
|
984
974
|
}) {
|
|
@@ -987,23 +977,23 @@ function Ge({
|
|
|
987
977
|
v,
|
|
988
978
|
e._path
|
|
989
979
|
).stateMapNoRender(
|
|
990
|
-
(S, E,
|
|
980
|
+
(S, E, w, h, s) => e._mapFn(S, E, w, h, s)
|
|
991
981
|
) : null;
|
|
992
982
|
}
|
|
993
|
-
function
|
|
983
|
+
function Ge({
|
|
994
984
|
proxy: e
|
|
995
985
|
}) {
|
|
996
986
|
const i = te(null), v = `${e._stateKey}-${e._path.join(".")}`;
|
|
997
987
|
return ue(() => {
|
|
998
988
|
const u = i.current;
|
|
999
989
|
if (!u || !u.parentElement) return;
|
|
1000
|
-
const S = u.parentElement,
|
|
990
|
+
const S = u.parentElement, w = Array.from(S.childNodes).indexOf(u);
|
|
1001
991
|
let h = S.getAttribute("data-parent-id");
|
|
1002
992
|
h || (h = `parent-${crypto.randomUUID()}`, S.setAttribute("data-parent-id", h));
|
|
1003
993
|
const m = {
|
|
1004
994
|
instanceId: `instance-${crypto.randomUUID()}`,
|
|
1005
995
|
parentId: h,
|
|
1006
|
-
position:
|
|
996
|
+
position: w,
|
|
1007
997
|
effect: e._effect
|
|
1008
998
|
};
|
|
1009
999
|
r.getState().addSignalElement(v, m);
|
package/dist/CogsState.jsx.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\n\r\nimport {\r\n createElement,\r\n startTransition,\r\n useEffect,\r\n useLayoutEffect,\r\n useMemo,\r\n useRef,\r\n useState,\r\n useSyncExternalStore,\r\n type ReactNode,\r\n} from \"react\";\r\n\r\nimport {\r\n debounce,\r\n getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport superjson from \"superjson\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { z } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\nimport { applyPatch } from \"fast-json-patch\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U, T> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => StateObject<T>;\r\n\r\ntype CutFunctionType<T> = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => StateObject<T>;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\ntype ArraySpecificPrototypeKeys =\r\n | \"concat\"\r\n | \"copyWithin\"\r\n | \"fill\"\r\n | \"find\"\r\n | \"findIndex\"\r\n | \"flat\"\r\n | \"flatMap\"\r\n | \"includes\"\r\n | \"indexOf\"\r\n | \"join\"\r\n | \"keys\"\r\n | \"lastIndexOf\"\r\n | \"map\"\r\n | \"pop\"\r\n | \"push\"\r\n | \"reduce\"\r\n | \"reduceRight\"\r\n | \"reverse\"\r\n | \"shift\"\r\n | \"slice\"\r\n | \"some\"\r\n | \"sort\"\r\n | \"splice\"\r\n | \"unshift\"\r\n | \"values\"\r\n | \"entries\"\r\n | \"every\"\r\n | \"filter\"\r\n | \"forEach\"\r\n | \"with\";\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFind: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => boolean\r\n ) => StateObject<InferArrayElement<TShape>> | undefined;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n clearSelected: () => void;\r\n getSelectedIndex: () => number;\r\n last: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n} & EndType<TShape>;\r\n\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<T>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\n\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n applyJsonPatch: (patches: any[]) => void;\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n toggleSelected: () => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n sync: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {});\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n getDifferences: () => string[];\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction: UpdateArg<TStateObject>,\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: z.ZodTypeAny;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n serverState?: {\r\n id?: string | number;\r\n data?: T;\r\n status?: \"pending\" | \"error\" | \"success\";\r\n };\r\n sync?: {\r\n action: (state: T) => Promise<{\r\n success: boolean;\r\n data?: any;\r\n error?: any;\r\n errors?: Array<{\r\n path: (string | number)[];\r\n message: string;\r\n }>;\r\n }>;\r\n onSuccess?: (data: any) => void;\r\n onError?: (error: any) => void;\r\n };\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: {\r\n key: string | ((state: T) => string);\r\n onChange?: (state: T) => void;\r\n };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\n// Fix for the setOptions function\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n const mergedOptions = { ...initialOptionsPartState, ...initialOptions };\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n if (\r\n key == \"initialState\" &&\r\n options[key] &&\r\n mergedOptions[key] !== options[key] && // Different references\r\n !isDeepEqual(mergedOptions[key], options[key]) // And different values\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (\r\n Object.keys(initialOptionsPart).length > 0 ||\r\n (opt && Object.keys(opt).length > 0)\r\n ) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt?.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n const existingOptions = getInitialOptions(key);\r\n\r\n if (!existingOptions) {\r\n getGlobalStore\r\n .getState()\r\n .setInitialStateOptions(key, initialOptionsPart[key]);\r\n }\r\n });\r\n }\r\n\r\n getGlobalStore.getState().setInitialStates(statePart);\r\n getGlobalStore.getState().setCreatedState(statePart);\r\n type StateKeys = keyof typeof statePart;\r\n\r\n const useCogsState = <StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options?: OptionsType<(typeof statePart)[StateKey]>\r\n ) => {\r\n const [componentId] = useState(options?.componentId ?? uuidv4());\r\n\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState as any,\r\n dependencies: options?.dependencies,\r\n serverState: options?.serverState,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n\r\n if (options.localStorage) {\r\n loadAndApplyLocalStorage(stateKey as string, options);\r\n }\r\n\r\n notifyComponents(stateKey as string);\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string,\r\n lastSyncedWithServer?: number\r\n) => {\r\n if (currentInitialOptions?.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n\r\n if (key && sessionId) {\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n // Get existing data to preserve lastSyncedWithServer if not explicitly updating it\r\n let existingLastSynced: number | undefined;\r\n try {\r\n const existing = loadFromLocalStorage(storageKey);\r\n existingLastSynced = existing?.lastSyncedWithServer;\r\n } catch {\r\n // Ignore errors, will use undefined\r\n }\r\n\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer: lastSyncedWithServer ?? existingLastSynced,\r\n };\r\n\r\n // Use SuperJSON serialize to get the json part only\r\n const superJsonResult = superjson.serialize(data);\r\n window.localStorage.setItem(\r\n storageKey,\r\n JSON.stringify(superJsonResult.json)\r\n );\r\n }\r\n};\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n // Parse the json part back normally\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\nconst loadAndApplyLocalStorage = (stateKey: string, options: any) => {\r\n const currentState = getGlobalStore.getState().cogsStateStore[stateKey];\r\n const { sessionId } = useCogsConfig();\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options.localStorage.key(currentState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n const localData = loadFromLocalStorage(\r\n `${sessionId}-${stateKey}-${localkey}`\r\n );\r\n\r\n if (\r\n localData &&\r\n localData.lastUpdated > (localData.lastSyncedWithServer || 0)\r\n ) {\r\n setState(stateKey, localData.state);\r\n\r\n notifyComponents(stateKey);\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n if (!reactiveTypes?.includes(\"none\")) {\r\n updates.add(() => component.forceUpdate());\r\n }\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n updates.forEach((update) => update());\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes?.includes(\"none\")) {\r\n return;\r\n }\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\nconst getUpdateValues = (\r\n updateType: string,\r\n prevValue: any,\r\n payload: any,\r\n path: string[]\r\n) => {\r\n switch (updateType) {\r\n case \"update\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"insert\":\r\n return {\r\n oldValue: null, // or undefined\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"cut\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: null, // or undefined\r\n };\r\n default:\r\n return { oldValue: null, newValue: null };\r\n }\r\n};\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n serverState,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n initialState?: TStateObject;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<OptionsType<TStateObject> | null>(\r\n null\r\n );\r\n latestInitialOptionsRef.current = (getInitialOptions(thisKey as string) ??\r\n null) as OptionsType<TStateObject> | null;\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n useEffect(() => {\r\n // Only proceed if initialState is provided\r\n if (initialState) {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n\r\n const options = latestInitialOptionsRef.current;\r\n const hasServerId = options?.serverState?.id !== undefined;\r\n const hasServerData =\r\n hasServerId &&\r\n options?.serverState?.status === \"success\" &&\r\n options?.serverState?.data;\r\n\r\n const currentGloballyStoredInitialState =\r\n getGlobalStore.getState().initialStateGlobal[thisKey];\r\n\r\n const initialStateChanged =\r\n (currentGloballyStoredInitialState &&\r\n !isDeepEqual(currentGloballyStoredInitialState, initialState)) ||\r\n !currentGloballyStoredInitialState;\r\n\r\n if (!initialStateChanged && !hasServerData) {\r\n return;\r\n }\r\n\r\n let localData = null;\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(`${sessionId}-${thisKey}-${localkey}`);\r\n }\r\n\r\n let newState = initialState;\r\n let isFromServer = false;\r\n\r\n const serverTimestamp = hasServerData ? Date.now() : 0;\r\n const localTimestamp = localData?.lastUpdated || 0;\r\n const lastSyncTimestamp = localData?.lastSyncedWithServer || 0;\r\n\r\n if (hasServerData && serverTimestamp > localTimestamp) {\r\n newState = options.serverState!.data!;\r\n isFromServer = true;\r\n } else if (localData && localTimestamp > lastSyncTimestamp) {\r\n newState = localData.state;\r\n if (options?.localStorage?.onChange) {\r\n options?.localStorage?.onChange(newState);\r\n }\r\n }\r\n\r\n // Update the global state\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n // Save to localStorage if we used server data\r\n if (isFromServer && localkey && sessionId) {\r\n saveToLocalStorage(newState, thisKey, options, sessionId, Date.now());\r\n }\r\n\r\n // Notify components of the change\r\n notifyComponents(thisKey);\r\n\r\n const reactiveTypes = Array.isArray(reactiveType)\r\n ? reactiveType\r\n : [reactiveType || \"component\"];\r\n\r\n if (!reactiveTypes.includes(\"none\")) {\r\n forceUpdate({});\r\n }\r\n }\r\n }, [\r\n initialState,\r\n serverState?.status,\r\n serverState?.data,\r\n ...(dependencies || []),\r\n ]);\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware: latestInitialOptionsRef.current?.middleware,\r\n });\r\n }\r\n\r\n const componentKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(componentKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n const componentKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(componentKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction: UpdateArg<TStateObject>,\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n\r\n if (stateEntry) {\r\n const changedPaths = getDifferences(prevValue, payload);\r\n const changedPathsSet = new Set(changedPaths);\r\n const primaryPathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : path.slice(0, -1).join(\".\") || \"\";\r\n\r\n const componentsToUpdate: Array<() => void> = [];\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n componentsToUpdate.push(component.forceUpdate); // COLLECT instead of calling\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths.has(primaryPathToCheck) ||\r\n component.paths.has(\"\")\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n let currentPathToCheck = changedPath;\r\n while (true) {\r\n if (component.paths.has(currentPathToCheck)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n const lastDotIndex = currentPathToCheck.lastIndexOf(\".\");\r\n if (lastDotIndex !== -1) {\r\n const parentPath = currentPathToCheck.substring(\r\n 0,\r\n lastDotIndex\r\n );\r\n if (\r\n !isNaN(\r\n Number(currentPathToCheck.substring(lastDotIndex + 1))\r\n )\r\n ) {\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n currentPathToCheck = parentPath;\r\n } else {\r\n currentPathToCheck = \"\";\r\n }\r\n if (currentPathToCheck === \"\") {\r\n break;\r\n }\r\n }\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n componentsToUpdate.push(component.forceUpdate); // COLLECT instead of calling\r\n }\r\n }\r\n\r\n // BATCH all updates at once\r\n if (componentsToUpdate.length > 0) {\r\n queueMicrotask(() => {\r\n componentsToUpdate.forEach((update) => update());\r\n });\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n path = path.map((p, i) => {\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n\r\n return i === path.length - 1 &&\r\n [\"insert\", \"cut\"].includes(updateObj.updateType)\r\n ? (arrayValue.length - 1).toString()\r\n : p;\r\n });\r\n\r\n const { oldValue, newValue } = getUpdateValues(\r\n updateObj.updateType,\r\n prevValue,\r\n payload,\r\n path\r\n );\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (latestInitialOptionsRef.current?.middleware) {\r\n latestInitialOptionsRef.current!.middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = getGlobalStore.getState().serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey, sessionId]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n getGlobalStore.getState().clearSelectedIndexesForState(stateKey);\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (localStorage.getItem(storageKey)) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (meta?.validIndices && !Array.isArray(currentState)) {\r\n meta = { ...meta, validIndices: undefined };\r\n }\r\n const mutationMethods = new Set([\r\n \"insert\",\r\n \"cut\",\r\n \"cutByValue\",\r\n \"toggleByValue\",\r\n \"uniqueInsert\",\r\n \"update\",\r\n \"applyJsonPatch\",\r\n \"setSelected\",\r\n \"toggleSelected\",\r\n \"clearSelected\",\r\n \"sync\",\r\n \"validateZodSchema\",\r\n \"revertToInitialState\",\r\n \"updateInitialState\",\r\n \"removeValidation\",\r\n \"setValidation\",\r\n \"removeStorage\",\r\n \"middleware\",\r\n ]);\r\n\r\n if (\r\n prop === \"then\" ||\r\n prop[0] === \"$\" ||\r\n prop === \"stateMapNoRender\" ||\r\n mutationMethods.has(prop)\r\n ) {\r\n // Skip path tracking entirely\r\n } else {\r\n // Only compute these if needed\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // OPTIMIZED: Most important optimization - check for root first\r\n if (component.paths.has(\"\")) {\r\n // Do nothing - root already tracks everything\r\n } else if (path.length === 0 && prop === \"get\") {\r\n // Special case for root get()\r\n component.paths.add(\"\");\r\n } else if (path.length > 0) {\r\n // OPTIMIZED: Build path only when needed\r\n const currentPath = path.join(\".\");\r\n\r\n // OPTIMIZED: Use size check first (O(1))\r\n if (component.paths.size === 0) {\r\n component.paths.add(currentPath);\r\n } else {\r\n // OPTIMIZED: For small sets, iteration is faster than complex algorithms\r\n let needsAdd = true;\r\n\r\n // Check if any existing path is a parent\r\n for (const existingPath of component.paths) {\r\n if (existingPath === currentPath) {\r\n needsAdd = false;\r\n break;\r\n }\r\n // OPTIMIZED: Length check before string operation\r\n if (\r\n existingPath.length < currentPath.length &&\r\n currentPath[existingPath.length] === \".\" &&\r\n currentPath.substring(0, existingPath.length) ===\r\n existingPath\r\n ) {\r\n needsAdd = false;\r\n break;\r\n }\r\n }\r\n\r\n if (needsAdd) {\r\n console.log(\"adding path to component\", currentPath, prop);\r\n component.paths.add(currentPath);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (prop === \"getDifferences\") {\r\n return () => {\r\n const differences = getDifferences(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n getGlobalStore.getState().initialStateGlobal[stateKey]\r\n );\r\n return differences;\r\n };\r\n }\r\n if (prop === \"sync\" && path.length === 0) {\r\n return async function () {\r\n // Get the options for this state key\r\n const options = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey);\r\n const sync = options?.sync;\r\n\r\n if (!sync) {\r\n console.error(`No mutation defined for state key \"${stateKey}\"`);\r\n return { success: false, error: `No mutation defined` };\r\n }\r\n\r\n // Get the root state\r\n const state = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, []);\r\n\r\n // Get validation key\r\n const validationKey = options?.validation?.key;\r\n\r\n try {\r\n // Execute the mutation action\r\n const response = await sync.action(state);\r\n\r\n // Handle validation errors\r\n if (\r\n response &&\r\n !response.success &&\r\n response.errors &&\r\n validationKey\r\n ) {\r\n // Clear existing errors\r\n getGlobalStore.getState().removeValidationError(validationKey);\r\n\r\n // Add new validation errors\r\n response.errors.forEach((error) => {\r\n const errorPath = [validationKey, ...error.path].join(\".\");\r\n\r\n getGlobalStore\r\n .getState()\r\n .addValidationError(errorPath, error.message);\r\n });\r\n\r\n // Notify components to update\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n }\r\n\r\n // Call success/error callbacks\r\n if (response?.success && sync.onSuccess) {\r\n sync.onSuccess(response.data);\r\n } else if (!response?.success && sync.onError) {\r\n sync.onError(response.error);\r\n }\r\n\r\n return response;\r\n } catch (error) {\r\n if (sync.onError) {\r\n sync.onError(error);\r\n }\r\n return { success: false, error };\r\n }\r\n };\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n const getSourceArrayAndIndices = (): {\r\n item: any;\r\n originalIndex: number;\r\n }[] => {\r\n // If meta exists, we're in a chain. Use the currentState and map it to its original index.\r\n if (meta?.validIndices) {\r\n return (currentState as any[]).map((item, index) => ({\r\n item,\r\n originalIndex: meta!.validIndices![index]!,\r\n }));\r\n }\r\n // Otherwise, this is the first operation. Use the full array from the global store.\r\n const sourceArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n return sourceArray.map((item, index) => ({\r\n item,\r\n originalIndex: index,\r\n }));\r\n };\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"clearSelected\") {\r\n return () => {\r\n getGlobalStore.getState().clearSelectedIndex({ stateKey, path });\r\n };\r\n }\r\n if (prop === \"getSelectedIndex\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n\r\n return selectedIndex ?? -1;\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const sortedResult = [...sourceWithIndices].sort((a, b) =>\r\n compareFn(a.item, b.item)\r\n );\r\n const newCurrentState = sortedResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: sortedResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const filteredResult = sourceWithIndices.filter(\r\n ({ item }, index) => callbackfn(item, index)\r\n );\r\n const newCurrentState = filteredResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: filteredResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n\r\n if (prop === \"stateMap\" || prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => any\r\n ) => {\r\n const arrayToMap = currentState as any[];\r\n return arrayToMap.map((item, index) => {\r\n let originalIndex: number;\r\n // We READ from the meta object using the CORRECT property name: `validIndices`.\r\n if (\r\n meta?.validIndices &&\r\n meta.validIndices[index] !== undefined\r\n ) {\r\n originalIndex = meta.validIndices[index]!;\r\n } else {\r\n originalIndex = index;\r\n }\r\n const finalPath = [...path, originalIndex.toString()];\r\n\r\n const setter = rebuildStateShape(item, finalPath, meta); // Pass meta through\r\n return callbackfn(\r\n item,\r\n setter,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const arrayToMap = currentState as any[];\r\n shapeCache.clear();\r\n stateVersion++;\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any) => val[fieldName] ?? []\r\n );\r\n return rebuildStateShape(\r\n flattenedResults as any,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n if (prop === \"last\") {\r\n // Added handler for 'last'\r\n return () => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n if (currentArray.length === 0) return undefined;\r\n const lastIndex = currentArray.length - 1;\r\n const lastValue = currentArray[lastIndex];\r\n const newPath = [...path, lastIndex.toString()];\r\n // shapeCache.clear(); // Decide if you need cache invalidation for 'last' access\r\n // stateVersion++;\r\n return rebuildStateShape(lastValue, newPath);\r\n };\r\n }\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n if (prop === \"stateFind\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(({ item }, index) =>\r\n callbackfn(item, index)\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (thisKey: keyof InferArrayElement<T>, thisValue: any) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(\r\n ({ item }) => item[thisKey] === thisValue\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => getGlobalStore.getState().getNestedState(stateKey, path);\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (prop === \"toggleSelected\") {\r\n return () => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, parentKey);\r\n\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(\r\n stateKey,\r\n parentKey,\r\n selectedIndex === thisIndex ? undefined : thisIndex\r\n );\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"applyJsonPatch\") {\r\n return (patches: any[]) => {\r\n // This part is correct.\r\n const currentState =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n const patchResult = applyPatch(currentState, patches);\r\n const newState = patchResult.newDocument;\r\n\r\n // This is also correct.\r\n updateGlobalState(\r\n stateKey,\r\n getGlobalStore.getState().initialStateGlobal[stateKey],\r\n newState,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n\r\n // ===================================================================\r\n // REPLACE THE OLD LOGIC WITH THIS DIRECT COPY\r\n // ===================================================================\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey); // Use stateKey here\r\n\r\n if (stateEntry) {\r\n // Use `getDifferences` between the state before and after the patch.\r\n const changedPaths = getDifferences(currentState, newState);\r\n const changedPathsSet = new Set(changedPaths);\r\n\r\n // There is no single `primaryPathToCheck` for a patch, so we just check against the full set.\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n // This is the core logic that needs to be copied.\r\n // Check if any of the component's watched paths are in the set of changed paths.\r\n if (component.paths.has(\"\")) {\r\n // Always update for root listeners\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n // Direct match first (fastest)\r\n if (component.paths.has(changedPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n\r\n // Check parent paths more efficiently\r\n let dotIndex = changedPath.lastIndexOf(\".\");\r\n while (dotIndex !== -1) {\r\n const parentPath = changedPath.substring(0, dotIndex);\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n // Skip numeric segments more efficiently\r\n const lastSegment = changedPath.substring(\r\n dotIndex + 1\r\n );\r\n if (!isNaN(Number(lastSegment))) {\r\n // For array indices, check the parent collection path\r\n const parentDotIndex = parentPath.lastIndexOf(\".\");\r\n if (parentDotIndex !== -1) {\r\n const grandParentPath = parentPath.substring(\r\n 0,\r\n parentDotIndex\r\n );\r\n if (component.paths.has(grandParentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n }\r\n dotIndex = parentPath.lastIndexOf(\".\");\r\n }\r\n\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n // Use `newState` (the result of the patch) for dependency checks.\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(newState);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","isDeepEqual","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","loadAndApplyLocalStorage","notifyComponents","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","lastSyncedWithServer","isFunction","storageKey","existingLastSynced","loadFromLocalStorage","data","superJsonResult","superjson","localStorageKey","storedData","error","currentState","useCogsConfig","localkey","localData","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","stateEntry","component","update","notifyComponent","fullComponentId","getUpdateValues","updateType","prevValue","payload","path","getNestedValue","stateObject","serverSync","localStorage","reactiveDeps","reactiveType","syncUpdate","dependencies","serverState","reactiveForce","forceUpdate","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","hasServerData","currentGloballyStoredInitialState","isFromServer","serverTimestamp","localTimestamp","lastSyncTimestamp","useLayoutEffect","componentKey","newStateOrFunction","updateObj","validationKey","pathKey","signalId","isArrayOperation","elements","arrayPath","arrayValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","v","length","newKey","changedPaths","getDifferences","changedPathsSet","primaryPathToCheck","componentsToUpdate","shouldUpdate","reactiveTypes","changedPath","currentPathToCheck","lastDotIndex","parentPath","depsResult","depsChanged","timeStamp","p","i","oldValue","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","startTransition","field","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","mutationMethods","currentPath","needsAdd","existingPath","sync","response","errorPath","thisReactiveState","initialStateAtPath","getSourceArrayAndIndices","item","index","selectedIndex","compareFn","sortedResult","a","b","newCurrentState","newMeta","originalIndex","callbackfn","filteredResult","finalPath","setter","createElement","SignalMapRenderer","fieldName","arrayToMap","flattenedResults","val","indexValue","currentArray","lastIndex","lastValue","newPath","pushFunc","fields","onMatch","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","found","thisValue","lastPathElement","parentValue","fn","$cogsSignal","parentKey","thisIndex","nested","patches","applyPatch","dotIndex","lastSegment","parentDotIndex","grandParentPath","thisObject","existingErrors","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify"],"mappings":";;;;;;;;;;;AAocA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC;AAEjE,EAAAI,EAAuBJ,GAAoB;AAAA,IACzC,GAAGK;AAAA,IACH,GAAGJ;AAAA,EAAA,CACJ;AACH;AAGA,SAASK,GAA0B;AAAA,EACjC,UAAAN;AAAA,EACA,SAAAO;AAAA,EACA,oBAAAC;AACF,GAIG;AACD,QAAMH,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC,GAC3DS,IAA0BD,EAAmBR,CAAkB,KAAK,CAAC,GACrEI,IACJD,EAAe,SAAA,EAAW,wBACtBO,IAAgB,EAAE,GAAGD,GAAyB,GAAGJ,EAAe;AAEtE,MAAIM,IAAY;AAChB,M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GAEnDtD,GAAc,QAAQ;AAAA,IAC3B,KAAKyD;AAAA,IACL,OAAO,EAAE,SAAS,OAAO;AAAA,IACzB,kBAAkBlJ;AAAA,EAAA,CACnB;AACH;AACO,SAASwJ,GAAiBT,GAG9B;AACD,QAAMlC,IAAQ4C;AAAA,IACZ,CAACC,MAAW;AACJ,YAAApM,IAAajE,EAChB,SAAS,EACT,gBAAgB,IAAI0P,EAAM,SAAS,KAAK;AAAA,QACzC,gCAAgB,IAAI;AAAA,MACtB;AACW,aAAAzL,EAAA,WAAW,IAAIyL,EAAM,WAAW;AAAA,QACzC,aAAaW;AAAA,QACb,2BAAW,IAAI,CAACX,EAAM,MAAM,KAAK,GAAG,CAAC,CAAC;AAAA,MAAA,CACvC,GACM,MAAMzL,EAAW,WAAW,OAAOyL,EAAM,SAAS;AAAA,IAC3D;AAAA,IACA,MAAM1P,EAAe,WAAW,eAAe0P,EAAM,WAAWA,EAAM,KAAK;AAAA,EAC7E;AACA,SAAOtD,GAAc,QAAQ,CAAI,GAAA,OAAOoB,CAAK,CAAC;AAChD;"}
|
|
1
|
+
{"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\n\r\nimport {\r\n createElement,\r\n startTransition,\r\n useEffect,\r\n useLayoutEffect,\r\n useMemo,\r\n useRef,\r\n useState,\r\n useSyncExternalStore,\r\n type ReactNode,\r\n} from \"react\";\r\n\r\nimport {\r\n debounce,\r\n getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport superjson from \"superjson\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { z } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\nimport { applyPatch } from \"fast-json-patch\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U, T> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => StateObject<T>;\r\n\r\ntype CutFunctionType<T> = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => StateObject<T>;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\ntype ArraySpecificPrototypeKeys =\r\n | \"concat\"\r\n | \"copyWithin\"\r\n | \"fill\"\r\n | \"find\"\r\n | \"findIndex\"\r\n | \"flat\"\r\n | \"flatMap\"\r\n | \"includes\"\r\n | \"indexOf\"\r\n | \"join\"\r\n | \"keys\"\r\n | \"lastIndexOf\"\r\n | \"map\"\r\n | \"pop\"\r\n | \"push\"\r\n | \"reduce\"\r\n | \"reduceRight\"\r\n | \"reverse\"\r\n | \"shift\"\r\n | \"slice\"\r\n | \"some\"\r\n | \"sort\"\r\n | \"splice\"\r\n | \"unshift\"\r\n | \"values\"\r\n | \"entries\"\r\n | \"every\"\r\n | \"filter\"\r\n | \"forEach\"\r\n | \"with\";\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFind: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => boolean\r\n ) => StateObject<InferArrayElement<TShape>> | undefined;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n clearSelected: () => void;\r\n getSelectedIndex: () => number;\r\n last: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n} & EndType<TShape>;\r\n\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<T>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\n\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n applyJsonPatch: (patches: any[]) => void;\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n toggleSelected: () => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n sync: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {});\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n getDifferences: () => string[];\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction: UpdateArg<TStateObject>,\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: z.ZodTypeAny;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n serverState?: {\r\n id?: string | number;\r\n data?: T;\r\n status?: \"pending\" | \"error\" | \"success\";\r\n };\r\n sync?: {\r\n action: (state: T) => Promise<{\r\n success: boolean;\r\n data?: any;\r\n error?: any;\r\n errors?: Array<{\r\n path: (string | number)[];\r\n message: string;\r\n }>;\r\n }>;\r\n onSuccess?: (data: any) => void;\r\n onError?: (error: any) => void;\r\n };\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: {\r\n key: string | ((state: T) => string);\r\n onChange?: (state: T) => void;\r\n };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[]; // Just like useEffect dependencies\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\n// Fix for the setOptions function\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n const mergedOptions = { ...initialOptionsPartState, ...initialOptions };\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n if (\r\n key == \"initialState\" &&\r\n options[key] &&\r\n mergedOptions[key] !== options[key] && // Different references\r\n !isDeepEqual(mergedOptions[key], options[key]) // And different values\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (\r\n Object.keys(initialOptionsPart).length > 0 ||\r\n (opt && Object.keys(opt).length > 0)\r\n ) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt?.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n const existingOptions = getInitialOptions(key);\r\n\r\n if (!existingOptions) {\r\n getGlobalStore\r\n .getState()\r\n .setInitialStateOptions(key, initialOptionsPart[key]);\r\n }\r\n });\r\n }\r\n\r\n getGlobalStore.getState().setInitialStates(statePart);\r\n getGlobalStore.getState().setCreatedState(statePart);\r\n type StateKeys = keyof typeof statePart;\r\n\r\n const useCogsState = <StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options?: OptionsType<(typeof statePart)[StateKey]>\r\n ) => {\r\n const [componentId] = useState(options?.componentId ?? uuidv4());\r\n\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState as any,\r\n dependencies: options?.dependencies,\r\n serverState: options?.serverState,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n\r\n if (options.localStorage) {\r\n loadAndApplyLocalStorage(stateKey as string, options);\r\n }\r\n\r\n notifyComponents(stateKey as string);\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string,\r\n lastSyncedWithServer?: number\r\n) => {\r\n if (currentInitialOptions?.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n\r\n if (key && sessionId) {\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n // Get existing data to preserve lastSyncedWithServer if not explicitly updating it\r\n let existingLastSynced: number | undefined;\r\n try {\r\n const existing = loadFromLocalStorage(storageKey);\r\n existingLastSynced = existing?.lastSyncedWithServer;\r\n } catch {\r\n // Ignore errors, will use undefined\r\n }\r\n\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer: lastSyncedWithServer ?? existingLastSynced,\r\n };\r\n\r\n // Use SuperJSON serialize to get the json part only\r\n const superJsonResult = superjson.serialize(data);\r\n window.localStorage.setItem(\r\n storageKey,\r\n JSON.stringify(superJsonResult.json)\r\n );\r\n }\r\n};\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n // Parse the json part back normally\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\nconst loadAndApplyLocalStorage = (stateKey: string, options: any) => {\r\n const currentState = getGlobalStore.getState().cogsStateStore[stateKey];\r\n const { sessionId } = useCogsConfig();\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options.localStorage.key(currentState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n const localData = loadFromLocalStorage(\r\n `${sessionId}-${stateKey}-${localkey}`\r\n );\r\n\r\n if (\r\n localData &&\r\n localData.lastUpdated > (localData.lastSyncedWithServer || 0)\r\n ) {\r\n setState(stateKey, localData.state);\r\n\r\n notifyComponents(stateKey);\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n if (!reactiveTypes?.includes(\"none\")) {\r\n updates.add(() => component.forceUpdate());\r\n }\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n updates.forEach((update) => update());\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes?.includes(\"none\")) {\r\n return;\r\n }\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\nconst getUpdateValues = (\r\n updateType: string,\r\n prevValue: any,\r\n payload: any,\r\n path: string[]\r\n) => {\r\n switch (updateType) {\r\n case \"update\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"insert\":\r\n return {\r\n oldValue: null, // or undefined\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"cut\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: null, // or undefined\r\n };\r\n default:\r\n return { oldValue: null, newValue: null };\r\n }\r\n};\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n serverState,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n initialState?: TStateObject;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<OptionsType<TStateObject> | null>(\r\n null\r\n );\r\n latestInitialOptionsRef.current = (getInitialOptions(thisKey as string) ??\r\n null) as OptionsType<TStateObject> | null;\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n useEffect(() => {\r\n // Only proceed if initialState is provided\r\n if (initialState) {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n\r\n const options = latestInitialOptionsRef.current;\r\n const hasServerId = options?.serverState?.id !== undefined;\r\n const hasServerData =\r\n hasServerId &&\r\n options?.serverState?.status === \"success\" &&\r\n options?.serverState?.data;\r\n\r\n const currentGloballyStoredInitialState =\r\n getGlobalStore.getState().initialStateGlobal[thisKey];\r\n\r\n const initialStateChanged =\r\n (currentGloballyStoredInitialState &&\r\n !isDeepEqual(currentGloballyStoredInitialState, initialState)) ||\r\n !currentGloballyStoredInitialState;\r\n\r\n if (!initialStateChanged && !hasServerData) {\r\n return;\r\n }\r\n\r\n let localData = null;\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(`${sessionId}-${thisKey}-${localkey}`);\r\n }\r\n\r\n let newState = initialState;\r\n let isFromServer = false;\r\n\r\n const serverTimestamp = hasServerData ? Date.now() : 0;\r\n const localTimestamp = localData?.lastUpdated || 0;\r\n const lastSyncTimestamp = localData?.lastSyncedWithServer || 0;\r\n\r\n if (hasServerData && serverTimestamp > localTimestamp) {\r\n newState = options.serverState!.data!;\r\n isFromServer = true;\r\n } else if (localData && localTimestamp > lastSyncTimestamp) {\r\n newState = localData.state;\r\n if (options?.localStorage?.onChange) {\r\n options?.localStorage?.onChange(newState);\r\n }\r\n }\r\n\r\n // Update the global state\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n // Save to localStorage if we used server data\r\n if (isFromServer && localkey && sessionId) {\r\n saveToLocalStorage(newState, thisKey, options, sessionId, Date.now());\r\n }\r\n\r\n // Notify components of the change\r\n notifyComponents(thisKey);\r\n\r\n const reactiveTypes = Array.isArray(reactiveType)\r\n ? reactiveType\r\n : [reactiveType || \"component\"];\r\n\r\n if (!reactiveTypes.includes(\"none\")) {\r\n forceUpdate({});\r\n }\r\n }\r\n }, [\r\n initialState,\r\n serverState?.status,\r\n serverState?.data,\r\n ...(dependencies || []),\r\n ]);\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware: latestInitialOptionsRef.current?.middleware,\r\n });\r\n }\r\n\r\n const componentKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(componentKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n const componentKey = `${thisKey}////${componentIdRef.current}`;\r\n\r\n if (stateEntry) {\r\n stateEntry.components.delete(componentKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction: UpdateArg<TStateObject>,\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = getGlobalStore\r\n .getState()\r\n .signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n\r\n if (stateEntry) {\r\n const changedPaths = getDifferences(prevValue, payload);\r\n const changedPathsSet = new Set(changedPaths);\r\n const primaryPathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : path.slice(0, -1).join(\".\") || \"\";\r\n\r\n const componentsToUpdate: Array<() => void> = [];\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n componentsToUpdate.push(component.forceUpdate); // COLLECT instead of calling\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths.has(primaryPathToCheck) ||\r\n component.paths.has(\"\")\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n let currentPathToCheck = changedPath;\r\n while (true) {\r\n if (component.paths.has(currentPathToCheck)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n const lastDotIndex = currentPathToCheck.lastIndexOf(\".\");\r\n if (lastDotIndex !== -1) {\r\n const parentPath = currentPathToCheck.substring(\r\n 0,\r\n lastDotIndex\r\n );\r\n if (\r\n !isNaN(\r\n Number(currentPathToCheck.substring(lastDotIndex + 1))\r\n )\r\n ) {\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n currentPathToCheck = parentPath;\r\n } else {\r\n currentPathToCheck = \"\";\r\n }\r\n if (currentPathToCheck === \"\") {\r\n break;\r\n }\r\n }\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n componentsToUpdate.push(component.forceUpdate); // COLLECT instead of calling\r\n }\r\n }\r\n\r\n // BATCH all updates at once\r\n if (componentsToUpdate.length > 0) {\r\n queueMicrotask(() => {\r\n componentsToUpdate.forEach((update) => update());\r\n });\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n path = path.map((p, i) => {\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n\r\n return i === path.length - 1 &&\r\n [\"insert\", \"cut\"].includes(updateObj.updateType)\r\n ? (arrayValue.length - 1).toString()\r\n : p;\r\n });\r\n\r\n const { oldValue, newValue } = getUpdateValues(\r\n updateObj.updateType,\r\n prevValue,\r\n payload,\r\n path\r\n );\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (latestInitialOptionsRef.current?.middleware) {\r\n latestInitialOptionsRef.current!.middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = getGlobalStore.getState().serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey, sessionId]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n getGlobalStore.getState().clearSelectedIndexesForState(stateKey);\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (localStorage.getItem(storageKey)) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (meta?.validIndices && !Array.isArray(currentState)) {\r\n meta = { ...meta, validIndices: undefined };\r\n }\r\n const mutationMethods = new Set([\r\n \"insert\",\r\n \"cut\",\r\n \"cutByValue\",\r\n \"toggleByValue\",\r\n \"uniqueInsert\",\r\n \"update\",\r\n \"applyJsonPatch\",\r\n \"setSelected\",\r\n \"toggleSelected\",\r\n \"clearSelected\",\r\n \"sync\",\r\n \"validateZodSchema\",\r\n \"revertToInitialState\",\r\n \"updateInitialState\",\r\n \"removeValidation\",\r\n \"setValidation\",\r\n \"removeStorage\",\r\n \"middleware\",\r\n ]);\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\" &&\r\n !mutationMethods.has(prop) // ADD THIS CHECK\r\n ) {\r\n console.log(\"adding path start\", path, prop);\r\n // Only compute these if needed\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // If we already track root, no need to track anything else\r\n if (component.paths.has(\"\")) {\r\n return;\r\n }\r\n\r\n // Build the current path including the property being accessed\r\n const currentPath = [...path, prop].join(\".\");\r\n\r\n // Check if we need to add this path\r\n let needsAdd = true;\r\n for (const existingPath of component.paths) {\r\n // If we already track this exact path or a parent of it\r\n if (\r\n currentPath.startsWith(existingPath) &&\r\n (currentPath === existingPath ||\r\n currentPath[existingPath.length] === \".\")\r\n ) {\r\n needsAdd = false;\r\n break;\r\n }\r\n }\r\n\r\n if (needsAdd) {\r\n console.log(\"adding path addimg\", currentPath, prop);\r\n component.paths.add(currentPath);\r\n }\r\n }\r\n }\r\n }\r\n if (prop === \"getDifferences\") {\r\n return () => {\r\n const differences = getDifferences(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n getGlobalStore.getState().initialStateGlobal[stateKey]\r\n );\r\n return differences;\r\n };\r\n }\r\n if (prop === \"sync\" && path.length === 0) {\r\n return async function () {\r\n // Get the options for this state key\r\n const options = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey);\r\n const sync = options?.sync;\r\n\r\n if (!sync) {\r\n console.error(`No mutation defined for state key \"${stateKey}\"`);\r\n return { success: false, error: `No mutation defined` };\r\n }\r\n\r\n // Get the root state\r\n const state = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, []);\r\n\r\n // Get validation key\r\n const validationKey = options?.validation?.key;\r\n\r\n try {\r\n // Execute the mutation action\r\n const response = await sync.action(state);\r\n\r\n // Handle validation errors\r\n if (\r\n response &&\r\n !response.success &&\r\n response.errors &&\r\n validationKey\r\n ) {\r\n // Clear existing errors\r\n getGlobalStore.getState().removeValidationError(validationKey);\r\n\r\n // Add new validation errors\r\n response.errors.forEach((error) => {\r\n const errorPath = [validationKey, ...error.path].join(\".\");\r\n\r\n getGlobalStore\r\n .getState()\r\n .addValidationError(errorPath, error.message);\r\n });\r\n\r\n // Notify components to update\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n }\r\n\r\n // Call success/error callbacks\r\n if (response?.success && sync.onSuccess) {\r\n sync.onSuccess(response.data);\r\n } else if (!response?.success && sync.onError) {\r\n sync.onError(response.error);\r\n }\r\n\r\n return response;\r\n } catch (error) {\r\n if (sync.onError) {\r\n sync.onError(error);\r\n }\r\n return { success: false, error };\r\n }\r\n };\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n const getSourceArrayAndIndices = (): {\r\n item: any;\r\n originalIndex: number;\r\n }[] => {\r\n // If meta exists, we're in a chain. Use the currentState and map it to its original index.\r\n if (meta?.validIndices) {\r\n return (currentState as any[]).map((item, index) => ({\r\n item,\r\n originalIndex: meta!.validIndices![index]!,\r\n }));\r\n }\r\n // Otherwise, this is the first operation. Use the full array from the global store.\r\n const sourceArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n return sourceArray.map((item, index) => ({\r\n item,\r\n originalIndex: index,\r\n }));\r\n };\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"clearSelected\") {\r\n return () => {\r\n getGlobalStore.getState().clearSelectedIndex({ stateKey, path });\r\n };\r\n }\r\n if (prop === \"getSelectedIndex\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n\r\n return selectedIndex ?? -1;\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const sortedResult = [...sourceWithIndices].sort((a, b) =>\r\n compareFn(a.item, b.item)\r\n );\r\n const newCurrentState = sortedResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: sortedResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const filteredResult = sourceWithIndices.filter(\r\n ({ item }, index) => callbackfn(item, index)\r\n );\r\n const newCurrentState = filteredResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: filteredResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n\r\n if (prop === \"stateMap\" || prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => any\r\n ) => {\r\n const arrayToMap = currentState as any[];\r\n return arrayToMap.map((item, index) => {\r\n let originalIndex: number;\r\n // We READ from the meta object using the CORRECT property name: `validIndices`.\r\n if (\r\n meta?.validIndices &&\r\n meta.validIndices[index] !== undefined\r\n ) {\r\n originalIndex = meta.validIndices[index]!;\r\n } else {\r\n originalIndex = index;\r\n }\r\n const finalPath = [...path, originalIndex.toString()];\r\n\r\n const setter = rebuildStateShape(item, finalPath, meta); // Pass meta through\r\n return callbackfn(\r\n item,\r\n setter,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const arrayToMap = currentState as any[];\r\n shapeCache.clear();\r\n stateVersion++;\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any) => val[fieldName] ?? []\r\n );\r\n return rebuildStateShape(\r\n flattenedResults as any,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n if (prop === \"last\") {\r\n // Added handler for 'last'\r\n return () => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n if (currentArray.length === 0) return undefined;\r\n const lastIndex = currentArray.length - 1;\r\n const lastValue = currentArray[lastIndex];\r\n const newPath = [...path, lastIndex.toString()];\r\n // shapeCache.clear(); // Decide if you need cache invalidation for 'last' access\r\n // stateVersion++;\r\n return rebuildStateShape(lastValue, newPath);\r\n };\r\n }\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n if (prop === \"stateFind\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(({ item }, index) =>\r\n callbackfn(item, index)\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (thisKey: keyof InferArrayElement<T>, thisValue: any) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(\r\n ({ item }) => item[thisKey] === thisValue\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => getGlobalStore.getState().getNestedState(stateKey, path);\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (prop === \"toggleSelected\") {\r\n return () => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, parentKey);\r\n\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(\r\n stateKey,\r\n parentKey,\r\n selectedIndex === thisIndex ? undefined : thisIndex\r\n );\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"applyJsonPatch\") {\r\n return (patches: any[]) => {\r\n // This part is correct.\r\n const currentState =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n const patchResult = applyPatch(currentState, patches);\r\n const newState = patchResult.newDocument;\r\n\r\n // This is also correct.\r\n updateGlobalState(\r\n stateKey,\r\n getGlobalStore.getState().initialStateGlobal[stateKey],\r\n newState,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n\r\n // ===================================================================\r\n // REPLACE THE OLD LOGIC WITH THIS DIRECT COPY\r\n // ===================================================================\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey); // Use stateKey here\r\n\r\n if (stateEntry) {\r\n // Use `getDifferences` between the state before and after the patch.\r\n const changedPaths = getDifferences(currentState, newState);\r\n const changedPathsSet = new Set(changedPaths);\r\n\r\n // There is no single `primaryPathToCheck` for a patch, so we just check against the full set.\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n // This is the core logic that needs to be copied.\r\n // Check if any of the component's watched paths are in the set of changed paths.\r\n if (component.paths.has(\"\")) {\r\n // Always update for root listeners\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n // Direct match first (fastest)\r\n if (component.paths.has(changedPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n\r\n // Check parent paths more efficiently\r\n let dotIndex = changedPath.lastIndexOf(\".\");\r\n while (dotIndex !== -1) {\r\n const parentPath = changedPath.substring(0, dotIndex);\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n // Skip numeric segments more efficiently\r\n const lastSegment = changedPath.substring(\r\n dotIndex + 1\r\n );\r\n if (!isNaN(Number(lastSegment))) {\r\n // For array indices, check the parent collection path\r\n const parentDotIndex = parentPath.lastIndexOf(\".\");\r\n if (parentDotIndex !== -1) {\r\n const grandParentPath = parentPath.substring(\r\n 0,\r\n parentDotIndex\r\n );\r\n if (component.paths.has(grandParentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n }\r\n dotIndex = parentPath.lastIndexOf(\".\");\r\n }\r\n\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n // Use `newState` (the result of the patch) for dependency checks.\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(newState);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","isDeepEqual","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","loadAndApplyLocalStorage","notifyComponents","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","lastSyncedWithServer","isFunction","storageKey","existingLastSynced","loadFromLocalStorage","data","superJsonResult","superjson","localStorageKey","storedData","error","currentState","useCogsConfig","localkey","localData","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","stateEntry","component","update","notifyComponent","fullComponentId","getUpdateValues","updateType","prevValue","payload","path","getNestedValue","stateObject","serverSync","localStorage","reactiveDeps","reactiveType","syncUpdate","dependencies","serverState","reactiveForce","forceUpdate","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","hasServerData","currentGloballyStoredInitialState","isFromServer","serverTimestamp","localTimestamp","lastSyncTimestamp","useLayoutEffect","componentKey","newStateOrFunction","updateObj","validationKey","pathKey","signalId","isArrayOperation","elements","arrayPath","arrayValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","v","length","newKey","changedPaths","getDifferences","changedPathsSet","primaryPathToCheck","componentsToUpdate","shouldUpdate","reactiveTypes","changedPath","currentPathToCheck","lastDotIndex","parentPath","depsResult","depsChanged","timeStamp","p","i","oldValue","newUpdate","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","startTransition","field","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","mutationMethods","currentPath","needsAdd","existingPath","sync","response","errorPath","thisReactiveState","initialStateAtPath","getSourceArrayAndIndices","item","index","selectedIndex","compareFn","sortedResult","a","b","newCurrentState","newMeta","originalIndex","callbackfn","filteredResult","finalPath","setter","createElement","SignalMapRenderer","fieldName","arrayToMap","flattenedResults","val","indexValue","currentArray","lastIndex","lastValue","newPath","pushFunc","fields","onMatch","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","found","thisValue","lastPathElement","parentValue","fn","$cogsSignal","parentKey","thisIndex","nested","patches","applyPatch","dotIndex","lastSegment","parentDotIndex","grandParentPath","thisObject","existingErrors","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify"],"mappings":";;;;;;;;;;;AAocA,SAASA,GAAmBC,GA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G;AAGjB,IAAIjG,MAAiB,QAAQ,OAAOA,KAAiB,aACpCA,IAAA,KAAK,UAAUA,CAAY;AAG5C,UAAM2I,IAAW,SAAS,eAAe,OAAO3I,CAAY,CAAC;AAC7D,IAAAuI,EAAQ,YAAYI,CAAQ;AAAA,EAAA,GAC3B,CAACR,EAAM,WAAWA,EAAM,MAAM,KAAK,GAAG,GAAGA,EAAM,OAAO,CAAC,GAEnDtD,GAAc,QAAQ;AAAA,IAC3B,KAAKyD;AAAA,IACL,OAAO,EAAE,SAAS,OAAO;AAAA,IACzB,kBAAkBlJ;AAAA,EAAA,CACnB;AACH;AACO,SAASwJ,GAAiBT,GAG9B;AACD,QAAMlC,IAAQ4C;AAAA,IACZ,CAACC,MAAW;AACJ,YAAApM,IAAajE,EAChB,SAAS,EACT,gBAAgB,IAAI0P,EAAM,SAAS,KAAK;AAAA,QACzC,gCAAgB,IAAI;AAAA,MACtB;AACW,aAAAzL,EAAA,WAAW,IAAIyL,EAAM,WAAW;AAAA,QACzC,aAAaW;AAAA,QACb,2BAAW,IAAI,CAACX,EAAM,MAAM,KAAK,GAAG,CAAC,CAAC;AAAA,MAAA,CACvC,GACM,MAAMzL,EAAW,WAAW,OAAOyL,EAAM,SAAS;AAAA,IAC3D;AAAA,IACA,MAAM1P,EAAe,WAAW,eAAe0P,EAAM,WAAWA,EAAM,KAAK;AAAA,EAC7E;AACA,SAAOtD,GAAc,QAAQ,CAAI,GAAA,OAAOoB,CAAK,CAAC;AAChD;"}
|
package/package.json
CHANGED
package/src/CogsState.tsx
CHANGED
|
@@ -1504,15 +1504,13 @@ function createProxyHandler<T>(
|
|
|
1504
1504
|
"removeStorage",
|
|
1505
1505
|
"middleware",
|
|
1506
1506
|
]);
|
|
1507
|
-
|
|
1508
1507
|
if (
|
|
1509
|
-
prop
|
|
1510
|
-
prop
|
|
1511
|
-
prop
|
|
1512
|
-
mutationMethods.has(prop)
|
|
1508
|
+
prop !== "then" &&
|
|
1509
|
+
!prop.startsWith("$") &&
|
|
1510
|
+
prop !== "stateMapNoRender" &&
|
|
1511
|
+
!mutationMethods.has(prop) // ADD THIS CHECK
|
|
1513
1512
|
) {
|
|
1514
|
-
|
|
1515
|
-
} else {
|
|
1513
|
+
console.log("adding path start", path, prop);
|
|
1516
1514
|
// Only compute these if needed
|
|
1517
1515
|
const fullComponentId = `${stateKey}////${componentId}`;
|
|
1518
1516
|
const stateEntry = getGlobalStore
|
|
@@ -1523,47 +1521,32 @@ function createProxyHandler<T>(
|
|
|
1523
1521
|
const component = stateEntry.components.get(fullComponentId);
|
|
1524
1522
|
|
|
1525
1523
|
if (component) {
|
|
1526
|
-
//
|
|
1524
|
+
// If we already track root, no need to track anything else
|
|
1527
1525
|
if (component.paths.has("")) {
|
|
1528
|
-
|
|
1529
|
-
}
|
|
1530
|
-
// Special case for root get()
|
|
1531
|
-
component.paths.add("");
|
|
1532
|
-
} else if (path.length > 0) {
|
|
1533
|
-
// OPTIMIZED: Build path only when needed
|
|
1534
|
-
const currentPath = path.join(".");
|
|
1535
|
-
|
|
1536
|
-
// OPTIMIZED: Use size check first (O(1))
|
|
1537
|
-
if (component.paths.size === 0) {
|
|
1538
|
-
component.paths.add(currentPath);
|
|
1539
|
-
} else {
|
|
1540
|
-
// OPTIMIZED: For small sets, iteration is faster than complex algorithms
|
|
1541
|
-
let needsAdd = true;
|
|
1542
|
-
|
|
1543
|
-
// Check if any existing path is a parent
|
|
1544
|
-
for (const existingPath of component.paths) {
|
|
1545
|
-
if (existingPath === currentPath) {
|
|
1546
|
-
needsAdd = false;
|
|
1547
|
-
break;
|
|
1548
|
-
}
|
|
1549
|
-
// OPTIMIZED: Length check before string operation
|
|
1550
|
-
if (
|
|
1551
|
-
existingPath.length < currentPath.length &&
|
|
1552
|
-
currentPath[existingPath.length] === "." &&
|
|
1553
|
-
currentPath.substring(0, existingPath.length) ===
|
|
1554
|
-
existingPath
|
|
1555
|
-
) {
|
|
1556
|
-
needsAdd = false;
|
|
1557
|
-
break;
|
|
1558
|
-
}
|
|
1559
|
-
}
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1560
1528
|
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1529
|
+
// Build the current path including the property being accessed
|
|
1530
|
+
const currentPath = [...path, prop].join(".");
|
|
1531
|
+
|
|
1532
|
+
// Check if we need to add this path
|
|
1533
|
+
let needsAdd = true;
|
|
1534
|
+
for (const existingPath of component.paths) {
|
|
1535
|
+
// If we already track this exact path or a parent of it
|
|
1536
|
+
if (
|
|
1537
|
+
currentPath.startsWith(existingPath) &&
|
|
1538
|
+
(currentPath === existingPath ||
|
|
1539
|
+
currentPath[existingPath.length] === ".")
|
|
1540
|
+
) {
|
|
1541
|
+
needsAdd = false;
|
|
1542
|
+
break;
|
|
1565
1543
|
}
|
|
1566
1544
|
}
|
|
1545
|
+
|
|
1546
|
+
if (needsAdd) {
|
|
1547
|
+
console.log("adding path addimg", currentPath, prop);
|
|
1548
|
+
component.paths.add(currentPath);
|
|
1549
|
+
}
|
|
1567
1550
|
}
|
|
1568
1551
|
}
|
|
1569
1552
|
}
|