cogsbox-state 0.5.431 → 0.5.434

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1195 +1,1702 @@
1
1
  "use client";
2
- import { jsx as $t } from "react/jsx-runtime";
3
- import { useState as lt, useRef as B, useEffect as rt, useLayoutEffect as _t, useMemo as At, createElement as gt, useSyncExternalStore as Ft, startTransition as Ut, useCallback as Et } from "react";
4
- import { transformStateFunc as Dt, isDeepEqual as Q, isFunction as tt, getNestedValue as U, getDifferences as Pt, debounce as Gt } from "./utility.js";
5
- import { pushFunc as wt, updateFn as ut, cutFunc as ft, ValidationWrapper as Lt, FormControlComponent as Wt } from "./Functions.jsx";
6
- import Bt from "superjson";
7
- import { v4 as kt } from "uuid";
2
+ import { jsx as ae, Fragment as ke } from "react/jsx-runtime";
3
+ import { memo as Re, useState as Z, useRef as q, useCallback as ce, useEffect as Y, useLayoutEffect as ue, useMemo as de, createElement as le, startTransition as je } from "react";
4
+ import { createRoot as Ce } from "react-dom/client";
5
+ import { transformStateFunc as Fe, isFunction as K, isArray as Te, getDifferences as Ae, isDeepEqual as ie } from "./utility.js";
6
+ import { ValidationWrapper as Me } from "./Functions.jsx";
7
+ import De from "superjson";
8
+ import { v4 as ee } from "uuid";
8
9
  import "zod";
9
- import { getGlobalStore as o, formRefStore as Vt } from "./store.js";
10
- import { useCogsConfig as Mt } from "./CogsStateClient.jsx";
11
- import { applyPatch as zt } from "fast-json-patch";
12
- import Ht from "react-use-measure";
13
- import "ulid";
14
- function bt(t, i) {
15
- const S = o.getState().getInitialOptions, g = o.getState().setInitialStateOptions, I = S(t) || {};
16
- g(t, {
17
- ...I,
18
- ...i
10
+ import { getGlobalStore as t, formRefStore as ye } from "./store.js";
11
+ import { useCogsConfig as $e } from "./CogsStateClient.jsx";
12
+ import { applyPatch as Le } from "fast-json-patch";
13
+ import { useInView as Oe } from "react-intersection-observer";
14
+ function me(e, s) {
15
+ const p = t.getState().getInitialOptions, g = t.getState().setInitialStateOptions, v = p(e) || {};
16
+ g(e, {
17
+ ...v,
18
+ ...s
19
19
  });
20
20
  }
21
- function Nt({
22
- stateKey: t,
23
- options: i,
24
- initialOptionsPart: S
21
+ function Ve({
22
+ stateKey: e,
23
+ options: s,
24
+ initialOptionsPart: p
25
25
  }) {
26
- const g = ct(t) || {}, I = S[t] || {}, k = o.getState().setInitialStateOptions, w = { ...I, ...g };
27
- let v = !1;
28
- if (i)
29
- for (const s in i)
30
- w.hasOwnProperty(s) ? (s == "localStorage" && i[s] && w[s].key !== i[s]?.key && (v = !0, w[s] = i[s]), s == "initialState" && i[s] && w[s] !== i[s] && // Different references
31
- !Q(w[s], i[s]) && (v = !0, w[s] = i[s])) : (v = !0, w[s] = i[s]);
32
- v && k(t, w);
26
+ const g = te(e) || {}, v = p[e] || {}, h = t.getState().setInitialStateOptions, V = { ...v, ...g };
27
+ let u = !1;
28
+ if (s)
29
+ for (const l in s)
30
+ V.hasOwnProperty(l) ? (l == "localStorage" && s[l] && V[l].key !== s[l]?.key && (u = !0, V[l] = s[l]), l == "defaultState" && s[l] && V[l] !== s[l] && !ie(V[l], s[l]) && (u = !0, V[l] = s[l])) : (u = !0, V[l] = s[l]);
31
+ u && h(e, V);
33
32
  }
34
- function Se(t, { formElements: i, validation: S }) {
35
- return { initialState: t, formElements: i, validation: S };
33
+ function lt(e, { formElements: s, validation: p }) {
34
+ return { initialState: e, formElements: s, validation: p };
36
35
  }
37
- const me = (t, i) => {
38
- let S = t;
39
- const [g, I] = Dt(S);
40
- (Object.keys(I).length > 0 || i && Object.keys(i).length > 0) && Object.keys(I).forEach((v) => {
41
- I[v] = I[v] || {}, I[v].formElements = {
42
- ...i?.formElements,
43
- // Global defaults first
44
- ...i?.validation,
45
- ...I[v].formElements || {}
46
- // State-specific overrides
47
- }, ct(v) || o.getState().setInitialStateOptions(v, I[v]);
48
- }), o.getState().setInitialStates(g), o.getState().setCreatedState(g);
49
- const k = (v, s) => {
50
- const [$] = lt(s?.componentId ?? kt());
51
- Nt({
52
- stateKey: v,
53
- options: s,
54
- initialOptionsPart: I
36
+ const ut = (e, s) => {
37
+ let p = e;
38
+ const [g, v] = Fe(p);
39
+ Object.keys(g).forEach((u) => {
40
+ let l = v[u] || {};
41
+ const E = {
42
+ ...l
43
+ };
44
+ if (s?.formElements && (E.formElements = {
45
+ ...s.formElements,
46
+ ...l.formElements || {}
47
+ }), s?.validation && (E.validation = {
48
+ ...s.validation,
49
+ ...l.validation || {}
50
+ }, s.validation.key && !l.validation?.key && (E.validation.key = `${s.validation.key}.${u}`)), Object.keys(E).length > 0) {
51
+ const T = te(u);
52
+ T ? t.getState().setInitialStateOptions(u, {
53
+ ...T,
54
+ ...E
55
+ }) : t.getState().setInitialStateOptions(u, E);
56
+ }
57
+ }), Object.keys(g).forEach((u) => {
58
+ t.getState().initializeShadowState(u, g[u]);
59
+ });
60
+ const h = (u, l) => {
61
+ const [E] = Z(l?.componentId ?? ee());
62
+ Ve({
63
+ stateKey: u,
64
+ options: l,
65
+ initialOptionsPart: v
66
+ });
67
+ const T = t.getState().getShadowValue(u) || g[u], o = l?.modifyState ? l.modifyState(T) : T;
68
+ return Be(o, {
69
+ stateKey: u,
70
+ syncUpdate: l?.syncUpdate,
71
+ componentId: E,
72
+ localStorage: l?.localStorage,
73
+ middleware: l?.middleware,
74
+ reactiveType: l?.reactiveType,
75
+ reactiveDeps: l?.reactiveDeps,
76
+ defaultState: l?.defaultState,
77
+ dependencies: l?.dependencies,
78
+ serverState: l?.serverState
55
79
  });
56
- const y = o.getState().cogsStateStore[v] || g[v], r = s?.modifyState ? s.modifyState(y) : y, [h, M] = Xt(
57
- r,
58
- {
59
- stateKey: v,
60
- syncUpdate: s?.syncUpdate,
61
- componentId: $,
62
- localStorage: s?.localStorage,
63
- middleware: s?.middleware,
64
- enabledSync: s?.enabledSync,
65
- reactiveType: s?.reactiveType,
66
- reactiveDeps: s?.reactiveDeps,
67
- initialState: s?.initialState,
68
- dependencies: s?.dependencies,
69
- serverState: s?.serverState
70
- }
71
- );
72
- return M;
73
80
  };
74
- function w(v, s) {
75
- Nt({ stateKey: v, options: s, initialOptionsPart: I }), s.localStorage && Yt(v, s), nt(v);
81
+ function V(u, l) {
82
+ Ve({ stateKey: u, options: l, initialOptionsPart: v }), l.localStorage && xe(u, l), re(u);
76
83
  }
77
- return { useCogsState: k, setCogsOptions: w };
84
+ return { useCogsState: h, setCogsOptions: V };
78
85
  }, {
79
- setUpdaterState: St,
80
- setState: ot,
81
- getInitialOptions: ct,
82
- getKeyState: Ot,
83
- getValidationErrors: qt,
84
- setStateLog: Jt,
85
- updateInitialStateGlobal: Tt,
86
- addValidationError: xt,
87
- removeValidationError: K,
88
- setServerSyncActions: Zt
89
- } = o.getState(), pt = (t, i, S, g, I) => {
90
- S?.log && console.log(
86
+ getInitialOptions: te,
87
+ getValidationErrors: Ne,
88
+ setStateLog: We,
89
+ updateInitialStateGlobal: _e,
90
+ addValidationError: pe,
91
+ removeValidationError: ne
92
+ } = t.getState(), He = (e, s, p, g, v) => {
93
+ p?.log && console.log(
91
94
  "saving to localstorage",
92
- i,
93
- S.localStorage?.key,
95
+ s,
96
+ p.localStorage?.key,
94
97
  g
95
98
  );
96
- const k = tt(S?.localStorage?.key) ? S.localStorage?.key(t) : S?.localStorage?.key;
97
- if (k && g) {
98
- const w = `${g}-${i}-${k}`;
99
- let v;
99
+ const h = K(p?.localStorage?.key) ? p.localStorage?.key(e) : p?.localStorage?.key;
100
+ if (h && g) {
101
+ const V = `${g}-${s}-${h}`;
102
+ let u;
100
103
  try {
101
- v = It(w)?.lastSyncedWithServer;
104
+ u = fe(V)?.lastSyncedWithServer;
102
105
  } catch {
103
106
  }
104
- const s = {
105
- state: t,
107
+ const l = t.getState().getShadowMetadata(s, []), E = {
108
+ state: e,
106
109
  lastUpdated: Date.now(),
107
- lastSyncedWithServer: I ?? v
108
- }, $ = Bt.serialize(s);
110
+ lastSyncedWithServer: u,
111
+ stateSource: l?.stateSource,
112
+ baseServerState: l?.baseServerState
113
+ }, T = De.serialize(E);
109
114
  window.localStorage.setItem(
110
- w,
111
- JSON.stringify($.json)
115
+ V,
116
+ JSON.stringify(T.json)
112
117
  );
113
118
  }
114
- }, It = (t) => {
115
- if (!t) return null;
119
+ }, fe = (e) => {
120
+ if (!e) return null;
116
121
  try {
117
- const i = window.localStorage.getItem(t);
118
- return i ? JSON.parse(i) : null;
119
- } catch (i) {
120
- return console.error("Error loading from localStorage:", i), null;
122
+ const s = window.localStorage.getItem(e);
123
+ return s ? JSON.parse(s) : null;
124
+ } catch (s) {
125
+ return console.error("Error loading from localStorage:", s), null;
121
126
  }
122
- }, Yt = (t, i) => {
123
- const S = o.getState().cogsStateStore[t], { sessionId: g } = Mt(), I = tt(i?.localStorage?.key) ? i.localStorage.key(S) : i?.localStorage?.key;
124
- if (I && g) {
125
- const k = It(
126
- `${g}-${t}-${I}`
127
+ }, xe = (e, s) => {
128
+ const p = t.getState().getShadowValue(e), { sessionId: g } = $e(), v = K(s?.localStorage?.key) ? s.localStorage.key(p) : s?.localStorage?.key;
129
+ if (v && g) {
130
+ const h = fe(
131
+ `${g}-${e}-${v}`
127
132
  );
128
- if (k && k.lastUpdated > (k.lastSyncedWithServer || 0))
129
- return ot(t, k.state), nt(t), !0;
133
+ if (h && h.lastUpdated > (h.lastSyncedWithServer || 0))
134
+ return re(e), !0;
130
135
  }
131
136
  return !1;
132
- }, Rt = (t, i, S, g, I, k) => {
133
- const w = {
134
- initialState: i,
135
- updaterState: mt(
136
- t,
137
- g,
138
- I,
139
- k
140
- ),
141
- state: S
142
- };
143
- Tt(t, w.initialState), St(t, w.updaterState), ot(t, w.state);
144
- }, nt = (t) => {
145
- const i = o.getState().stateComponents.get(t);
146
- if (!i) return;
147
- const S = /* @__PURE__ */ new Set();
148
- i.components.forEach((g) => {
149
- (g ? Array.isArray(g.reactiveType) ? g.reactiveType : [g.reactiveType || "component"] : null)?.includes("none") || S.add(() => g.forceUpdate());
137
+ }, re = (e) => {
138
+ const s = t.getState().getShadowMetadata(e, []);
139
+ if (!s) return;
140
+ const p = /* @__PURE__ */ new Set();
141
+ s?.components?.forEach((g) => {
142
+ (g ? Array.isArray(g.reactiveType) ? g.reactiveType : [g.reactiveType || "component"] : null)?.includes("none") || p.add(() => g.forceUpdate());
150
143
  }), queueMicrotask(() => {
151
- S.forEach((g) => g());
144
+ p.forEach((g) => g());
152
145
  });
153
- }, Ie = (t, i) => {
154
- const S = o.getState().stateComponents.get(t);
155
- if (S) {
156
- const g = `${t}////${i}`, I = S.components.get(g);
157
- if ((I ? Array.isArray(I.reactiveType) ? I.reactiveType : [I.reactiveType || "component"] : null)?.includes("none"))
146
+ }, dt = (e, s) => {
147
+ const p = t.getState().getShadowMetadata(e, []);
148
+ if (p) {
149
+ const g = `${e}////${s}`, v = p?.components?.get(g);
150
+ if ((v ? Array.isArray(v.reactiveType) ? v.reactiveType : [v.reactiveType || "component"] : null)?.includes("none"))
158
151
  return;
159
- I && I.forceUpdate();
160
- }
161
- }, Qt = (t, i, S, g) => {
162
- switch (t) {
163
- case "update":
164
- return {
165
- oldValue: U(i, g),
166
- newValue: U(S, g)
167
- };
168
- case "insert":
169
- return {
170
- oldValue: null,
171
- // or undefined
172
- newValue: U(S, g)
173
- };
174
- case "cut":
175
- return {
176
- oldValue: U(i, g),
177
- newValue: null
178
- // or undefined
179
- };
180
- default:
181
- return { oldValue: null, newValue: null };
152
+ v && v.forceUpdate();
182
153
  }
183
154
  };
184
- function Xt(t, {
185
- stateKey: i,
186
- serverSync: S,
155
+ function Be(e, {
156
+ stateKey: s,
157
+ serverSync: p,
187
158
  localStorage: g,
188
- formElements: I,
189
- reactiveDeps: k,
190
- reactiveType: w,
191
- componentId: v,
192
- initialState: s,
193
- syncUpdate: $,
194
- dependencies: y,
195
- serverState: r
159
+ formElements: v,
160
+ reactiveDeps: h,
161
+ reactiveType: V,
162
+ componentId: u,
163
+ defaultState: l,
164
+ syncUpdate: E,
165
+ dependencies: T,
166
+ serverState: o
196
167
  } = {}) {
197
- const [h, M] = lt({}), { sessionId: C } = Mt();
198
- let X = !i;
199
- const [f] = lt(i ?? kt()), W = o.getState().stateLog[f], c = B(/* @__PURE__ */ new Set()), et = B(v ?? kt()), P = B(
168
+ const [S, M] = Z({}), { sessionId: L } = $e();
169
+ let N = !s;
170
+ const [c] = Z(s ?? ee()), J = t.getState().stateLog[c], G = q(/* @__PURE__ */ new Set()), H = q(u ?? ee()), f = q(
200
171
  null
201
172
  );
202
- P.current = ct(f) ?? null, rt(() => {
203
- if ($ && $.stateKey === f && $.path?.[0]) {
204
- ot(f, (e) => ({
205
- ...e,
206
- [$.path[0]]: $.newValue
207
- }));
208
- const n = `${$.stateKey}:${$.path.join(".")}`;
209
- o.getState().setSyncInfo(n, {
210
- timeStamp: $.timeStamp,
211
- userId: $.userId
173
+ f.current = te(c) ?? null, Y(() => {
174
+ if (E && E.stateKey === c && E.path?.[0]) {
175
+ const a = `${E.stateKey}:${E.path.join(".")}`;
176
+ t.getState().setSyncInfo(a, {
177
+ timeStamp: E.timeStamp,
178
+ userId: E.userId
212
179
  });
213
180
  }
214
- }, [$]), rt(() => {
215
- if (s) {
216
- bt(f, {
217
- initialState: s
181
+ }, [E]);
182
+ const oe = ce(
183
+ (a) => {
184
+ const r = a ? { ...te(c), ...a } : te(c), i = r?.defaultState || l || e;
185
+ if (r?.serverState?.status === "success" && r?.serverState?.data !== void 0)
186
+ return {
187
+ value: r.serverState.data,
188
+ source: "server",
189
+ timestamp: r.serverState.timestamp || Date.now()
190
+ };
191
+ if (r?.localStorage?.key && L) {
192
+ const d = K(r.localStorage.key) ? r.localStorage.key(i) : r.localStorage.key, I = fe(
193
+ `${L}-${c}-${d}`
194
+ );
195
+ if (I && I.lastUpdated > (r?.serverState?.timestamp || 0))
196
+ return {
197
+ value: I.state,
198
+ source: "localStorage",
199
+ timestamp: I.lastUpdated
200
+ };
201
+ }
202
+ return {
203
+ value: i || e,
204
+ source: "default",
205
+ timestamp: Date.now()
206
+ };
207
+ },
208
+ [c, l, e, L]
209
+ );
210
+ Y(() => {
211
+ t.getState().setServerStateUpdate(c, o);
212
+ }, [o, c]), Y(() => t.getState().subscribeToPath(c, (n) => {
213
+ if (n?.type === "SERVER_STATE_UPDATE") {
214
+ const r = n.serverState;
215
+ if (r?.status === "success" && r.data !== void 0) {
216
+ me(c, { serverState: r });
217
+ const m = typeof r.merge == "object" ? r.merge : r.merge === !0 ? {} : null, d = t.getState().getShadowValue(c), I = r.data;
218
+ if (m && Array.isArray(d) && Array.isArray(I)) {
219
+ const U = m.key || "id", x = new Set(
220
+ d.map((R) => R[U])
221
+ ), _ = I.filter((R) => !x.has(R[U]));
222
+ if (console.log("newUniqueItems", _), _.length > 0)
223
+ _.forEach((R) => {
224
+ t.getState().insertShadowArrayElement(c, [], R);
225
+ });
226
+ else
227
+ return;
228
+ } else
229
+ t.getState().initializeShadowState(c, I);
230
+ const P = t.getState().getShadowMetadata(c, []);
231
+ t.getState().setShadowMetadata(c, [], {
232
+ ...P,
233
+ stateSource: "server",
234
+ lastServerSync: r.timestamp || Date.now(),
235
+ isDirty: !1
236
+ });
237
+ }
238
+ }
239
+ }), [c, oe]), Y(() => {
240
+ const a = t.getState().getShadowMetadata(c, []);
241
+ if (a && a.stateSource)
242
+ return;
243
+ const n = te(c);
244
+ if (n?.defaultState !== void 0 || l !== void 0) {
245
+ const r = n?.defaultState || l;
246
+ n?.defaultState || me(c, {
247
+ defaultState: r
218
248
  });
219
- const n = P.current, a = n?.serverState?.id !== void 0 && n?.serverState?.status === "success" && n?.serverState?.data, u = o.getState().initialStateGlobal[f];
220
- if (!(u && !Q(u, s) || !u) && !a)
221
- return;
222
- let l = null;
223
- const m = tt(n?.localStorage?.key) ? n?.localStorage?.key(s) : n?.localStorage?.key;
224
- m && C && (l = It(`${C}-${f}-${m}`));
225
- let x = s, T = !1;
226
- const R = a ? Date.now() : 0, z = l?.lastUpdated || 0, D = l?.lastSyncedWithServer || 0;
227
- a && R > z ? (x = n.serverState.data, T = !0) : l && z > D && (x = l.state, n?.localStorage?.onChange && n?.localStorage?.onChange(x)), o.getState().initializeShadowState(f, s), Rt(
228
- f,
229
- s,
230
- x,
231
- at,
232
- et.current,
233
- C
234
- ), T && m && C && pt(x, f, n, C, Date.now()), nt(f), (Array.isArray(w) ? w : [w || "component"]).includes("none") || M({});
249
+ const { value: i, source: m, timestamp: d } = oe();
250
+ t.getState().initializeShadowState(c, i), t.getState().setShadowMetadata(c, [], {
251
+ stateSource: m,
252
+ lastServerSync: m === "server" ? d : void 0,
253
+ isDirty: !1,
254
+ baseServerState: m === "server" ? i : void 0
255
+ }), re(c);
235
256
  }
236
- }, [
237
- s,
238
- r?.status,
239
- r?.data,
240
- ...y || []
241
- ]), _t(() => {
242
- X && bt(f, {
243
- serverSync: S,
244
- formElements: I,
245
- initialState: s,
257
+ }, [c, ...T || []]), ue(() => {
258
+ N && me(c, {
259
+ serverSync: p,
260
+ formElements: v,
261
+ defaultState: l,
246
262
  localStorage: g,
247
- middleware: P.current?.middleware
263
+ middleware: f.current?.middleware
248
264
  });
249
- const n = `${f}////${et.current}`, e = o.getState().stateComponents.get(f) || {
250
- components: /* @__PURE__ */ new Map()
251
- };
252
- return e.components.set(n, {
265
+ const a = `${c}////${H.current}`, n = t.getState().getShadowMetadata(c, []), r = n?.components || /* @__PURE__ */ new Map();
266
+ return r.set(a, {
253
267
  forceUpdate: () => M({}),
268
+ reactiveType: V ?? ["component", "deps"],
254
269
  paths: /* @__PURE__ */ new Set(),
255
- deps: [],
256
- depsFunction: k || void 0,
257
- reactiveType: w ?? ["component", "deps"]
258
- }), o.getState().stateComponents.set(f, e), M({}), () => {
259
- e && (e.components.delete(n), e.components.size === 0 && o.getState().stateComponents.delete(f));
270
+ depsFunction: h || void 0,
271
+ deps: h ? h(t.getState().getShadowValue(c)) : [],
272
+ prevDeps: h ? h(t.getState().getShadowValue(c)) : []
273
+ }), t.getState().setShadowMetadata(c, [], {
274
+ ...n,
275
+ components: r
276
+ }), M({}), () => {
277
+ const i = t.getState().getShadowMetadata(c, []), m = i?.components?.get(a);
278
+ m?.paths && m.paths.forEach((d) => {
279
+ const P = d.split(".").slice(1), U = t.getState().getShadowMetadata(c, P);
280
+ U?.pathComponents && U.pathComponents.size === 0 && (delete U.pathComponents, t.getState().setShadowMetadata(c, P, U));
281
+ }), i?.components && t.getState().setShadowMetadata(c, [], i);
260
282
  };
261
283
  }, []);
262
- const at = (n, e, a, u) => {
263
- if (Array.isArray(e)) {
264
- const l = `${f}-${e.join(".")}`;
265
- c.current.add(l);
284
+ const se = (a, n, r, i) => {
285
+ const m = [c, ...n].join(".");
286
+ if (Array.isArray(n)) {
287
+ const b = `${c}-${n.join(".")}`;
288
+ G.current.add(b);
266
289
  }
267
- const d = o.getState();
268
- ot(f, (l) => {
269
- const m = tt(n) ? n(l) : n, x = `${f}-${e.join(".")}`;
270
- if (x) {
271
- let _ = !1, E = d.signalDomElements.get(x);
272
- if ((!E || E.size === 0) && (a.updateType === "insert" || a.updateType === "cut")) {
273
- const V = e.slice(0, -1), N = U(m, V);
274
- if (Array.isArray(N)) {
275
- _ = !0;
276
- const A = `${f}-${V.join(".")}`;
277
- E = d.signalDomElements.get(A);
290
+ const d = t.getState(), I = d.getShadowMetadata(c, n), P = d.getShadowValue(m), U = r.updateType === "insert" && K(a) ? a({ state: P, uuid: ee() }) : K(a) ? a(P) : a, _ = {
291
+ timeStamp: Date.now(),
292
+ stateKey: c,
293
+ path: n,
294
+ updateType: r.updateType,
295
+ status: "new",
296
+ oldValue: P,
297
+ newValue: U
298
+ };
299
+ switch (r.updateType) {
300
+ case "insert": {
301
+ d.insertShadowArrayElement(c, n, _.newValue), d.markAsDirty(c, n, { bubble: !0 });
302
+ break;
303
+ }
304
+ case "cut": {
305
+ const b = n.slice(0, -1);
306
+ d.removeShadowArrayElement(c, n), d.markAsDirty(c, b, { bubble: !0 });
307
+ break;
308
+ }
309
+ case "update": {
310
+ d.updateShadowAtPath(c, n, _.newValue), d.markAsDirty(c, n, { bubble: !0 });
311
+ break;
312
+ }
313
+ }
314
+ if (I?.signals && I.signals.length > 0) {
315
+ const b = r.updateType === "cut" ? null : U;
316
+ I.signals.forEach(({ parentId: k, position: A, effect: F }) => {
317
+ const y = document.querySelector(`[data-parent-id="${k}"]`);
318
+ if (y) {
319
+ const w = Array.from(y.childNodes);
320
+ if (w[A]) {
321
+ let C = b;
322
+ if (F && b !== null)
323
+ try {
324
+ C = new Function(
325
+ "state",
326
+ `return (${F})(state)`
327
+ )(b);
328
+ } catch ($) {
329
+ console.error("Error evaluating effect function:", $);
330
+ }
331
+ C != null && typeof C == "object" && (C = JSON.stringify(C)), w[A].textContent = String(C ?? "");
278
332
  }
279
333
  }
280
- if (E) {
281
- const V = _ ? U(m, e.slice(0, -1)) : U(m, e);
282
- E.forEach(({ parentId: N, position: A, effect: b }) => {
283
- const J = document.querySelector(
284
- `[data-parent-id="${N}"]`
285
- );
286
- if (J) {
287
- const G = Array.from(J.childNodes);
288
- if (G[A]) {
289
- const j = b ? new Function("state", `return (${b})(state)`)(V) : V;
290
- G[A].textContent = String(j);
291
- }
334
+ });
335
+ }
336
+ if (r.updateType === "insert" && I?.mapWrappers && I.mapWrappers.length > 0) {
337
+ const b = d.getShadowMetadata(c, n)?.arrayKeys || [], k = b[b.length - 1], A = d.getShadowValue(k), F = d.getShadowValue(
338
+ [c, ...n].join(".")
339
+ );
340
+ if (!k || A === void 0) return;
341
+ I.mapWrappers.forEach((y) => {
342
+ let w = !0, C = -1;
343
+ if (y.meta?.transforms && y.meta.transforms.length > 0) {
344
+ for (const $ of y.meta.transforms)
345
+ if ($.type === "filter" && !$.fn(A, -1)) {
346
+ w = !1;
347
+ break;
292
348
  }
349
+ if (w) {
350
+ const $ = ve(
351
+ c,
352
+ n,
353
+ y.meta.transforms
354
+ ), j = y.meta.transforms.find(
355
+ (D) => D.type === "sort"
356
+ );
357
+ if (j) {
358
+ const D = $.map((z) => ({
359
+ key: z,
360
+ value: d.getShadowValue(z)
361
+ }));
362
+ D.push({ key: k, value: A }), D.sort((z, Q) => j.fn(z.value, Q.value)), C = D.findIndex(
363
+ (z) => z.key === k
364
+ );
365
+ } else
366
+ C = $.length;
367
+ }
368
+ } else
369
+ w = !0, C = b.length - 1;
370
+ if (w && y.containerRef && y.containerRef.isConnected) {
371
+ const $ = document.createElement("div");
372
+ $.setAttribute("data-item-path", k);
373
+ const j = Array.from(y.containerRef.children);
374
+ C >= 0 && C < j.length ? y.containerRef.insertBefore(
375
+ $,
376
+ j[C]
377
+ ) : y.containerRef.appendChild($);
378
+ const D = Ce($), z = ee(), Q = k.split(".").slice(1), X = y.rebuildStateShape({
379
+ path: y.path,
380
+ currentState: F,
381
+ componentId: y.componentId,
382
+ meta: y.meta
293
383
  });
384
+ D.render(
385
+ le(we, {
386
+ stateKey: c,
387
+ itemComponentId: z,
388
+ itemPath: Q,
389
+ localIndex: C,
390
+ arraySetter: X,
391
+ rebuildStateShape: y.rebuildStateShape,
392
+ renderFn: y.mapFn
393
+ })
394
+ );
294
395
  }
295
- }
296
- a.updateType === "update" && (u || P.current?.validation?.key) && e && K(
297
- (u || P.current?.validation?.key) + "." + e.join(".")
298
- );
299
- const T = e.slice(0, e.length - 1);
300
- a.updateType === "cut" && P.current?.validation?.key && K(
301
- P.current?.validation?.key + "." + T.join(".")
302
- ), a.updateType === "insert" && P.current?.validation?.key && qt(
303
- P.current?.validation?.key + "." + T.join(".")
304
- ).filter((E) => {
305
- let V = E?.split(".").length;
306
- const N = "";
307
- if (E == T.join(".") && V == T.length - 1) {
308
- let A = E + "." + T;
309
- K(E), xt(A, N);
396
+ });
397
+ }
398
+ if (r.updateType === "cut") {
399
+ const b = n.slice(0, -1), k = d.getShadowMetadata(c, b);
400
+ k?.mapWrappers && k.mapWrappers.length > 0 && k.mapWrappers.forEach((A) => {
401
+ if (A.containerRef && A.containerRef.isConnected) {
402
+ const F = A.containerRef.querySelector(
403
+ `[data-item-path="${m}"]`
404
+ );
405
+ F && F.remove();
310
406
  }
311
407
  });
312
- const R = d.stateComponents.get(f);
313
- if (R) {
314
- const _ = Pt(l, m), E = new Set(_), V = a.updateType === "update" ? e.join(".") : e.slice(0, -1).join(".") || "";
315
- for (const [
316
- N,
317
- A
318
- ] of R.components.entries()) {
319
- let b = !1;
320
- const J = Array.isArray(A.reactiveType) ? A.reactiveType : [A.reactiveType || "component"];
321
- if (!J.includes("none")) {
322
- if (J.includes("all")) {
323
- A.forceUpdate();
324
- continue;
325
- }
326
- if (J.includes("component") && ((A.paths.has(V) || A.paths.has("")) && (b = !0), !b))
327
- for (const G of E) {
328
- let j = G;
329
- for (; ; ) {
330
- if (A.paths.has(j)) {
331
- b = !0;
332
- break;
333
- }
334
- const p = j.lastIndexOf(".");
335
- if (p !== -1) {
336
- const O = j.substring(
337
- 0,
338
- p
339
- );
340
- if (!isNaN(
341
- Number(j.substring(p + 1))
342
- ) && A.paths.has(O)) {
343
- b = !0;
344
- break;
345
- }
346
- j = O;
347
- } else
348
- j = "";
349
- if (j === "")
350
- break;
408
+ }
409
+ r.updateType === "update" && (i || f.current?.validation?.key) && n && ne(
410
+ (i || f.current?.validation?.key) + "." + n.join(".")
411
+ );
412
+ const R = n.slice(0, n.length - 1);
413
+ r.updateType === "cut" && f.current?.validation?.key && ne(
414
+ f.current?.validation?.key + "." + R.join(".")
415
+ ), r.updateType === "insert" && f.current?.validation?.key && Ne(
416
+ f.current?.validation?.key + "." + R.join(".")
417
+ ).filter((k) => {
418
+ let A = k?.split(".").length;
419
+ const F = "";
420
+ if (k == R.join(".") && A == R.length - 1) {
421
+ let y = k + "." + R;
422
+ ne(k), pe(y, F);
423
+ }
424
+ });
425
+ const B = d.getShadowValue(c), O = d.getShadowMetadata(c, []), W = /* @__PURE__ */ new Set();
426
+ if (!O?.components)
427
+ return B;
428
+ if (r.updateType === "update")
429
+ I?.pathComponents && I.pathComponents.forEach((b) => {
430
+ if (W.has(b))
431
+ return;
432
+ const k = O.components?.get(b);
433
+ k && ((Array.isArray(k.reactiveType) ? k.reactiveType : [k.reactiveType || "component"]).includes("none") || (k.forceUpdate(), W.add(b)));
434
+ }), U && typeof U == "object" && !Te(U) && P && typeof P == "object" && !Te(P) && Ae(U, P).forEach((k) => {
435
+ const A = k.split("."), F = [...n, ...A], y = d.getShadowMetadata(c, F);
436
+ y?.pathComponents && y.pathComponents.forEach((w) => {
437
+ if (W.has(w))
438
+ return;
439
+ const C = O.components?.get(w);
440
+ C && ((Array.isArray(C.reactiveType) ? C.reactiveType : [C.reactiveType || "component"]).includes("none") || (C.forceUpdate(), W.add(w)));
441
+ });
442
+ });
443
+ else if (r.updateType === "insert" || r.updateType === "cut") {
444
+ const b = r.updateType === "insert" ? n : n.slice(0, -1), k = d.getShadowMetadata(c, b);
445
+ if (k?.signals && k.signals.length > 0) {
446
+ const A = [c, ...b].join("."), F = d.getShadowValue(A);
447
+ k.signals.forEach(({ parentId: y, position: w, effect: C }) => {
448
+ const $ = document.querySelector(
449
+ `[data-parent-id="${y}"]`
450
+ );
451
+ if ($) {
452
+ const j = Array.from($.childNodes);
453
+ if (j[w]) {
454
+ let D = F;
455
+ if (C)
456
+ try {
457
+ D = new Function(
458
+ "state",
459
+ `return (${C})(state)`
460
+ )(F);
461
+ } catch (z) {
462
+ console.error("Error evaluating effect function:", z), D = F;
351
463
  }
352
- if (b) break;
353
- }
354
- if (!b && J.includes("deps") && A.depsFunction) {
355
- const G = A.depsFunction(m);
356
- let j = !1;
357
- typeof G == "boolean" ? G && (j = !0) : Q(A.deps, G) || (A.deps = G, j = !0), j && (b = !0);
464
+ D != null && typeof D == "object" && (D = JSON.stringify(D)), j[w].textContent = String(D ?? "");
358
465
  }
359
- b && A.forceUpdate();
360
466
  }
361
- }
467
+ });
362
468
  }
363
- const z = Date.now();
364
- let { oldValue: D, newValue: H } = Qt(
365
- a.updateType,
366
- l,
367
- m,
368
- e
369
- );
370
- const it = {
371
- timeStamp: z,
372
- stateKey: f,
373
- path: e,
374
- updateType: a.updateType,
375
- status: "new",
376
- oldValue: D,
377
- newValue: H
378
- };
379
- switch (a.updateType) {
380
- case "insert": {
381
- const _ = e.slice(0, -1), V = e[e.length - 1].split(":")[1];
382
- H = U(m, _).find((A) => A.id == V), D = null, d.insertShadowArrayElement(f, _, H);
383
- break;
384
- }
385
- case "cut": {
386
- D = U(l, e), H = null, d.removeShadowArrayElement(f, e);
387
- break;
388
- }
389
- case "update": {
390
- D = U(l, e), H = U(m, e);
391
- const _ = e.map((E, V) => {
392
- const N = e.slice(0, V + 1), A = U(m, N);
393
- return A?.id ? `id:${A.id}` : E;
394
- });
395
- d.updateShadowAtPath(f, _, H);
396
- break;
469
+ k?.pathComponents && k.pathComponents.forEach((A) => {
470
+ if (!W.has(A)) {
471
+ const F = O.components?.get(A);
472
+ F && (F.forceUpdate(), W.add(A));
397
473
  }
474
+ });
475
+ }
476
+ return O.components.forEach((b, k) => {
477
+ if (W.has(k))
478
+ return;
479
+ const A = Array.isArray(b.reactiveType) ? b.reactiveType : [b.reactiveType || "component"];
480
+ if (A.includes("all")) {
481
+ b.forceUpdate(), W.add(k);
482
+ return;
398
483
  }
399
- if (Jt(f, (_) => {
400
- const E = [..._ ?? [], it], V = /* @__PURE__ */ new Map();
401
- return E.forEach((N) => {
402
- const A = `${N.stateKey}:${JSON.stringify(N.path)}`, b = V.get(A);
403
- b ? (b.timeStamp = Math.max(b.timeStamp, N.timeStamp), b.newValue = N.newValue, b.oldValue = b.oldValue ?? N.oldValue, b.updateType = N.updateType) : V.set(A, { ...N });
404
- }), Array.from(V.values());
405
- }), pt(
406
- m,
407
- f,
408
- P.current,
409
- C
410
- ), P.current?.middleware && P.current.middleware({
411
- updateLog: W,
412
- update: it
413
- }), P.current?.serverSync) {
414
- const _ = d.serverState[f], E = P.current?.serverSync;
415
- Zt(f, {
416
- syncKey: typeof E.syncKey == "string" ? E.syncKey : E.syncKey({ state: m }),
417
- rollBackState: _,
418
- actionTimeStamp: Date.now() + (E.debounce ?? 3e3),
419
- status: "waiting"
420
- });
484
+ if (A.includes("deps") && b.depsFunction) {
485
+ const F = d.getShadowValue(c), y = b.depsFunction(F);
486
+ let w = !1;
487
+ y === !0 ? w = !0 : Array.isArray(y) && (ie(b.prevDeps, y) || (b.prevDeps = y, w = !0)), w && (b.forceUpdate(), W.add(k));
421
488
  }
422
- return m;
423
- });
489
+ }), W.clear(), We(c, (b) => {
490
+ const k = [...b ?? [], _], A = /* @__PURE__ */ new Map();
491
+ return k.forEach((F) => {
492
+ const y = `${F.stateKey}:${JSON.stringify(F.path)}`, w = A.get(y);
493
+ w ? (w.timeStamp = Math.max(w.timeStamp, F.timeStamp), w.newValue = F.newValue, w.oldValue = w.oldValue ?? F.oldValue, w.updateType = F.updateType) : A.set(y, { ...F });
494
+ }), Array.from(A.values());
495
+ }), He(
496
+ U,
497
+ c,
498
+ f.current,
499
+ L
500
+ ), f.current?.middleware && f.current.middleware({
501
+ updateLog: J,
502
+ update: _
503
+ }), B;
424
504
  };
425
- o.getState().updaterState[f] || (St(
426
- f,
427
- mt(
428
- f,
429
- at,
430
- et.current,
431
- C
505
+ return t.getState().initialStateGlobal[c] || _e(c, e), de(() => Pe(
506
+ c,
507
+ se,
508
+ H.current,
509
+ L
510
+ ), [c, L]);
511
+ }
512
+ function qe(e) {
513
+ return !e || e.length === 0 ? "" : e.map(
514
+ (s) => (
515
+ // Safely stringify dependencies. An empty array becomes '[]'.
516
+ `${s.type}${JSON.stringify(s.dependencies || [])}`
432
517
  )
433
- ), o.getState().cogsStateStore[f] || ot(f, t), o.getState().initialStateGlobal[f] || Tt(f, t));
434
- const yt = At(() => mt(
435
- f,
436
- at,
437
- et.current,
438
- C
439
- ), [f, C]);
440
- return [Ot(f), yt];
518
+ ).join("");
441
519
  }
442
- function mt(t, i, S, g) {
443
- const I = /* @__PURE__ */ new Map();
444
- let k = 0;
445
- const w = (y) => {
446
- const r = y.join(".");
447
- for (const [h] of I)
448
- (h === r || h.startsWith(r + ".")) && I.delete(h);
449
- k++;
450
- }, v = {
451
- removeValidation: (y) => {
452
- y?.validationKey && K(y.validationKey);
453
- },
454
- revertToInitialState: (y) => {
455
- const r = o.getState().getInitialOptions(t)?.validation;
456
- r?.key && K(r?.key), y?.validationKey && K(y.validationKey);
457
- const h = o.getState().initialStateGlobal[t];
458
- o.getState().initializeShadowState(t, h), o.getState().clearSelectedIndexesForState(t), I.clear(), k++;
459
- const M = $(h, []), C = ct(t), X = tt(C?.localStorage?.key) ? C?.localStorage?.key(h) : C?.localStorage?.key, f = `${g}-${t}-${X}`;
460
- f && localStorage.removeItem(f), St(t, M), ot(t, h);
461
- const W = o.getState().stateComponents.get(t);
462
- return W && W.components.forEach((c) => {
463
- c.forceUpdate();
464
- }), h;
465
- },
466
- updateInitialState: (y) => {
467
- I.clear(), k++;
468
- const r = mt(
469
- t,
470
- i,
471
- S,
472
- g
473
- ), h = o.getState().initialStateGlobal[t], M = ct(t), C = tt(M?.localStorage?.key) ? M?.localStorage?.key(h) : M?.localStorage?.key, X = `${g}-${t}-${C}`;
474
- return localStorage.getItem(X) && localStorage.removeItem(X), Ut(() => {
475
- Tt(t, y), o.getState().initializeShadowState(t, y), St(t, r), ot(t, y);
476
- const f = o.getState().stateComponents.get(t);
477
- f && f.components.forEach((W) => {
478
- W.forceUpdate();
479
- });
480
- }), {
481
- fetchId: (f) => r.get()[f]
482
- };
483
- },
484
- _initialState: o.getState().initialStateGlobal[t],
485
- _serverState: o.getState().serverState[t],
486
- _isLoading: o.getState().isLoadingGlobal[t],
487
- _isServerSynced: () => {
488
- const y = o.getState().serverState[t];
489
- return !!(y && Q(y, Ot(t)));
490
- }
491
- };
492
- function s(y) {
493
- const r = [t, ...y].join(".");
494
- return o.getState().shadowStateStore.get(r)?.arrayKeys || null;
495
- }
496
- function $(y, r = [], h) {
497
- const M = r.map(String).join(".");
498
- I.get(M);
499
- const C = function() {
500
- return o().getNestedState(t, r);
501
- };
502
- Object.keys(v).forEach((W) => {
503
- C[W] = v[W];
520
+ const ve = (e, s, p) => {
521
+ let g = t.getState().getShadowMetadata(e, s)?.arrayKeys || [];
522
+ if (!p || p.length === 0)
523
+ return g;
524
+ let v = g.map((h) => ({
525
+ key: h,
526
+ value: t.getState().getShadowValue(h)
527
+ }));
528
+ for (const h of p)
529
+ h.type === "filter" ? v = v.filter(
530
+ ({ value: V }, u) => h.fn(V, u)
531
+ ) : h.type === "sort" && v.sort((V, u) => h.fn(V.value, u.value));
532
+ return v.map(({ key: h }) => h);
533
+ }, Ee = (e, s, p) => {
534
+ const g = `${e}////${s}`, h = t.getState().getShadowMetadata(e, [])?.components?.get(g);
535
+ if (!h || h.reactiveType == "none" || !(Array.isArray(h.reactiveType) ? h.reactiveType : [h.reactiveType]).includes("component"))
536
+ return;
537
+ const V = [e, ...p].join(".");
538
+ h.paths.add(V);
539
+ const u = t.getState().getShadowMetadata(e, p) || {}, l = u.pathComponents || /* @__PURE__ */ new Set();
540
+ l.add(g), t.getState().setShadowMetadata(e, p, {
541
+ ...u,
542
+ pathComponents: l
543
+ });
544
+ }, he = (e, s, p) => {
545
+ const g = t.getState(), v = g.getShadowMetadata(e, []), h = /* @__PURE__ */ new Set();
546
+ v?.components && v.components.forEach((u, l) => {
547
+ (Array.isArray(u.reactiveType) ? u.reactiveType : [u.reactiveType || "component"]).includes("all") && (u.forceUpdate(), h.add(l));
548
+ }), g.getShadowMetadata(e, [...s, "getSelected"])?.pathComponents?.forEach((u) => {
549
+ v?.components?.get(u)?.forceUpdate();
550
+ });
551
+ const V = g.getShadowMetadata(e, s);
552
+ for (let u of V?.arrayKeys || []) {
553
+ const l = u + ".selected", E = g.getShadowMetadata(
554
+ e,
555
+ l.split(".").slice(1)
556
+ );
557
+ u == p && E?.pathComponents?.forEach((T) => {
558
+ v?.components?.get(T)?.forceUpdate();
504
559
  });
505
- const X = {
506
- apply(W, c, et) {
507
- return o().getNestedState(t, r);
560
+ }
561
+ };
562
+ function Pe(e, s, p, g) {
563
+ const v = /* @__PURE__ */ new Map();
564
+ let h = 0;
565
+ const V = (T) => {
566
+ const o = T.join(".");
567
+ for (const [S] of v)
568
+ (S === o || S.startsWith(o + ".")) && v.delete(S);
569
+ h++;
570
+ };
571
+ function u({
572
+ currentState: T,
573
+ path: o = [],
574
+ meta: S,
575
+ componentId: M
576
+ }) {
577
+ const L = o.map(String).join("."), N = [e, ...o].join(".");
578
+ T = t.getState().getShadowValue(N, S?.validIds);
579
+ const c = function() {
580
+ return t().getShadowValue(e, o);
581
+ }, J = {
582
+ apply(H, f, oe) {
508
583
  },
509
- get(W, c) {
510
- const et = /* @__PURE__ */ new Set([
511
- "insert",
512
- "cut",
513
- "cutByValue",
514
- "toggleByValue",
515
- "uniqueInsert",
516
- "update",
517
- "applyJsonPatch",
518
- "setSelected",
519
- "toggleSelected",
520
- "clearSelected",
521
- "sync",
522
- "validateZodSchema",
523
- "revertToInitialState",
524
- "updateInitialState",
525
- "removeValidation",
526
- "setValidation",
527
- "removeStorage",
528
- "middleware",
529
- "_componentId",
530
- "_stateKey",
531
- "getComponents"
532
- ]);
533
- if (c !== "then" && !c.startsWith("$") && c !== "stateMapNoRender" && !et.has(c)) {
534
- const n = `${t}////${S}`, e = o.getState().stateComponents.get(t);
535
- if (e) {
536
- const a = e.components.get(n);
537
- if (a && !a.paths.has("")) {
538
- const u = r.join(".");
539
- let d = !0;
540
- for (const l of a.paths)
541
- if (u.startsWith(l) && (u === l || u[l.length] === ".")) {
542
- d = !1;
543
- break;
544
- }
545
- d && a.paths.add(u);
546
- }
547
- }
548
- }
549
- if (c === "getDifferences")
550
- return () => Pt(
551
- o.getState().cogsStateStore[t],
552
- o.getState().initialStateGlobal[t]
553
- );
554
- if (c === "sync" && r.length === 0)
584
+ get(H, f) {
585
+ if (f === "_rebuildStateShape")
586
+ return u;
587
+ if (Object.getOwnPropertyNames(l).includes(f) && o.length === 0)
588
+ return l[f];
589
+ if (f === "getDifferences")
590
+ return () => {
591
+ const a = t.getState().getShadowMetadata(e, []), n = t.getState().getShadowValue(e);
592
+ let r;
593
+ return a?.stateSource === "server" && a.baseServerState ? r = a.baseServerState : r = t.getState().initialStateGlobal[e], Ae(n, r);
594
+ };
595
+ if (f === "sync" && o.length === 0)
555
596
  return async function() {
556
- const n = o.getState().getInitialOptions(t), e = n?.sync;
557
- if (!e)
558
- return console.error(`No mutation defined for state key "${t}"`), { success: !1, error: "No mutation defined" };
559
- const a = o.getState().getNestedState(t, []), u = n?.validation?.key;
597
+ const a = t.getState().getInitialOptions(e), n = a?.sync;
598
+ if (!n)
599
+ return console.error(`No mutation defined for state key "${e}"`), { success: !1, error: "No mutation defined" };
600
+ const r = t.getState().getShadowValue(e, []), i = a?.validation?.key;
560
601
  try {
561
- const d = await e.action(a);
562
- return d && !d.success && d.errors && u && (o.getState().removeValidationError(u), d.errors.forEach((l) => {
563
- const m = [u, ...l.path].join(".");
564
- o.getState().addValidationError(m, l.message);
565
- }), nt(t)), d?.success && e.onSuccess ? e.onSuccess(d.data) : !d?.success && e.onError && e.onError(d.error), d;
566
- } catch (d) {
567
- return e.onError && e.onError(d), { success: !1, error: d };
602
+ const m = await n.action(r);
603
+ if (m && !m.success && m.errors && i && (t.getState().removeValidationError(i), m.errors.forEach((d) => {
604
+ const I = [i, ...d.path].join(".");
605
+ t.getState().addValidationError(I, d.message);
606
+ }), re(e)), m?.success) {
607
+ const d = t.getState().getShadowMetadata(e, []);
608
+ t.getState().setShadowMetadata(e, [], {
609
+ ...d,
610
+ isDirty: !1,
611
+ lastServerSync: Date.now(),
612
+ stateSource: "server",
613
+ baseServerState: r
614
+ // Update base server state
615
+ }), n.onSuccess && n.onSuccess(m.data);
616
+ } else !m?.success && n.onError && n.onError(m.error);
617
+ return m;
618
+ } catch (m) {
619
+ return n.onError && n.onError(m), { success: !1, error: m };
568
620
  }
569
621
  };
570
- if (c === "_status") {
571
- const n = o.getState().getNestedState(t, r), e = o.getState().initialStateGlobal[t], a = U(e, r);
572
- return Q(n, a) ? "fresh" : "stale";
573
- }
574
- if (c === "getStatus")
575
- return function() {
576
- const n = o().getNestedState(
577
- t,
578
- r
579
- ), e = o.getState().initialStateGlobal[t], a = U(e, r);
580
- return Q(n, a) ? "fresh" : "stale";
622
+ if (f === "_status" || f === "getStatus") {
623
+ const a = () => {
624
+ const n = t.getState().getShadowMetadata(e, []);
625
+ return n?.stateSource === "server" && !n.isDirty ? "synced" : n?.isDirty ? "dirty" : n?.stateSource === "localStorage" ? "restored" : n?.stateSource === "default" ? "fresh" : "unknown";
581
626
  };
582
- if (c === "removeStorage")
627
+ return f === "_status" ? a() : a;
628
+ }
629
+ if (f === "removeStorage")
583
630
  return () => {
584
- const n = o.getState().initialStateGlobal[t], e = ct(t), a = tt(e?.localStorage?.key) ? e.localStorage.key(n) : e?.localStorage?.key, u = `${g}-${t}-${a}`;
585
- u && localStorage.removeItem(u);
631
+ const a = t.getState().initialStateGlobal[e], n = te(e), r = K(n?.localStorage?.key) ? n.localStorage.key(a) : n?.localStorage?.key, i = `${g}-${e}-${r}`;
632
+ i && localStorage.removeItem(i);
586
633
  };
587
- if (c === "showValidationErrors")
634
+ if (f === "showValidationErrors")
588
635
  return () => {
589
- const n = o.getState().getInitialOptions(t)?.validation;
590
- if (!n?.key) throw new Error("Validation key not found");
591
- return o.getState().getValidationErrors(n.key + "." + r.join("."));
636
+ const a = t.getState().getInitialOptions(e)?.validation;
637
+ if (!a?.key) throw new Error("Validation key not found");
638
+ return t.getState().getValidationErrors(a.key + "." + o.join("."));
592
639
  };
593
- if (Array.isArray(y)) {
594
- if (c === "getSelected")
640
+ if (Array.isArray(T)) {
641
+ if (f === "getSelected")
595
642
  return () => {
596
- const n = o.getState().getSelectedIndex(t, r.join("."));
597
- if (n === void 0) return;
598
- const e = o.getState().getNestedState(t, r);
599
- if (!e || n >= e.length)
643
+ const a = e + "." + o.join(".");
644
+ Ee(e, M, [
645
+ ...o,
646
+ "getSelected"
647
+ ]);
648
+ const n = t.getState().selectedIndicesMap;
649
+ if (!n || !n.has(a))
600
650
  return;
601
- const a = e[n], u = `id:${a.id}`;
602
- return $(a, [...r, u], h);
603
- };
604
- if (c === "clearSelected")
605
- return () => {
606
- o.getState().clearSelectedIndex({ stateKey: t, path: r });
651
+ const r = n.get(a);
652
+ if (S?.validIds && !S.validIds.includes(r))
653
+ return;
654
+ const i = t.getState().getShadowValue(r);
655
+ if (i)
656
+ return u({
657
+ currentState: i,
658
+ path: r.split(".").slice(1),
659
+ componentId: M
660
+ });
607
661
  };
608
- if (c === "getSelectedIndex")
609
- return () => {
610
- const n = o.getState().getSelectedIndex(t, r.join("."));
611
- if (n === void 0) return -1;
612
- if (h?.validIds) {
613
- const a = (s(r) || [])[n];
614
- return a ? h.validIds.indexOf(a) : -1;
615
- }
616
- return n;
662
+ if (f === "getSelectedIndex")
663
+ return () => t.getState().getSelectedIndex(
664
+ e + "." + o.join("."),
665
+ S?.validIds
666
+ );
667
+ if (f === "clearSelected")
668
+ return he(e, o), () => {
669
+ t.getState().clearSelectedIndex({
670
+ arrayKey: e + "." + o.join(".")
671
+ });
617
672
  };
618
- if (c === "useVirtualView")
619
- return (n) => {
673
+ if (f === "useVirtualView")
674
+ return (a) => {
620
675
  const {
621
- itemHeight: e = 50,
622
- overscan: a = 6,
623
- stickToBottom: u = !1,
624
- dependencies: d = []
625
- } = n, l = B(null), [m, x] = lt({
676
+ itemHeight: n = 50,
677
+ overscan: r = 6,
678
+ stickToBottom: i = !1,
679
+ scrollStickTolerance: m = 75
680
+ } = a, d = q(null), [I, P] = Z({
626
681
  startIndex: 0,
627
682
  endIndex: 10
628
- }), [T, R] = lt(0), z = B(!0), D = B(!1), H = B(0), it = B(m);
629
- rt(() => o.getState().subscribeToShadowState(t, () => {
630
- R((O) => O + 1);
631
- }), [t]);
632
- const _ = o().getNestedState(
633
- t,
634
- r
635
- ), E = _.length, V = s(r), { totalHeight: N, positions: A } = At(() => {
636
- let p = 0;
637
- const O = [];
638
- for (let F = 0; F < E; F++) {
639
- O[F] = p;
640
- const Z = V?.[F];
641
- let q = e;
642
- if (Z) {
643
- const L = [...r, Z];
644
- q = o.getState().getShadowMetadata(t, L)?.virtualizer?.itemHeight || e;
683
+ }), [U, x] = Z({}), _ = q(!0), R = q({
684
+ isUserScrolling: !1,
685
+ lastScrollTop: 0,
686
+ scrollUpCount: 0,
687
+ isNearBottom: !0
688
+ }), B = q(
689
+ /* @__PURE__ */ new Map()
690
+ );
691
+ ue(() => {
692
+ if (!i || !d.current || R.current.isUserScrolling)
693
+ return;
694
+ const y = d.current;
695
+ y.scrollTo({
696
+ top: y.scrollHeight,
697
+ behavior: _.current ? "instant" : "smooth"
698
+ });
699
+ }, [U, i]);
700
+ const O = t.getState().getShadowMetadata(e, o)?.arrayKeys || [], { totalHeight: W, itemOffsets: b } = de(() => {
701
+ let y = 0;
702
+ const w = /* @__PURE__ */ new Map();
703
+ return (t.getState().getShadowMetadata(e, o)?.arrayKeys || []).forEach(($) => {
704
+ const j = $.split(".").slice(1), D = t.getState().getShadowMetadata(e, j)?.virtualizer?.itemHeight || n;
705
+ w.set($, {
706
+ height: D,
707
+ offset: y
708
+ }), y += D;
709
+ }), B.current = w, { totalHeight: y, itemOffsets: w };
710
+ }, [O.length, n]);
711
+ ue(() => {
712
+ if (i && O.length > 0 && d.current && !R.current.isUserScrolling && _.current) {
713
+ const y = d.current, w = () => {
714
+ if (y.clientHeight > 0) {
715
+ const C = Math.ceil(
716
+ y.clientHeight / n
717
+ ), $ = O.length - 1, j = Math.max(
718
+ 0,
719
+ $ - C - r
720
+ );
721
+ P({ startIndex: j, endIndex: $ }), requestAnimationFrame(() => {
722
+ A("instant"), _.current = !1;
723
+ });
724
+ } else
725
+ requestAnimationFrame(w);
726
+ };
727
+ w();
728
+ }
729
+ }, [O.length, i, n, r]);
730
+ const k = ce(() => {
731
+ const y = d.current;
732
+ if (!y) return;
733
+ const w = y.scrollTop, { scrollHeight: C, clientHeight: $ } = y, j = R.current, D = C - (w + $), z = j.isNearBottom;
734
+ j.isNearBottom = D <= m, w < j.lastScrollTop ? (j.scrollUpCount++, j.scrollUpCount > 3 && z && (j.isUserScrolling = !0, console.log("User scrolled away from bottom"))) : j.isNearBottom && (j.isUserScrolling = !1, j.scrollUpCount = 0), j.lastScrollTop = w;
735
+ let Q = 0;
736
+ for (let X = 0; X < O.length; X++) {
737
+ const ge = O[X], Se = B.current.get(ge);
738
+ if (Se && Se.offset + Se.height > w) {
739
+ Q = X;
740
+ break;
645
741
  }
646
- p += q;
647
742
  }
648
- return { totalHeight: p, positions: O };
649
- }, [
650
- E,
651
- t,
652
- r.join("."),
653
- e,
654
- T,
655
- V
656
- // Add `orderedIds` to the dependency array
657
- ]), b = At(() => {
658
- const p = Math.max(0, m.startIndex), O = Math.min(E, m.endIndex), F = V?.slice(p, O), Z = new Map(
659
- _.map((L) => [`id:${L.id}`, L])
660
- ), q = F?.map((L) => Z.get(L)).filter(Boolean) || [];
661
- return $(q, r, {
662
- ...h,
663
- validIds: F
664
- // Pass the sliced IDs as the new `validIds`
665
- });
743
+ if (Q !== I.startIndex) {
744
+ const X = Math.ceil($ / n);
745
+ P({
746
+ startIndex: Math.max(0, Q - r),
747
+ endIndex: Math.min(
748
+ O.length - 1,
749
+ Q + X + r
750
+ )
751
+ });
752
+ }
666
753
  }, [
667
- m.startIndex,
668
- m.endIndex,
669
- _,
670
- E,
671
- V
754
+ O.length,
755
+ I.startIndex,
756
+ n,
757
+ r,
758
+ m
672
759
  ]);
673
- rt(() => {
674
- if (!u || E === 0) return;
675
- E > H.current && z.current && !D.current && setTimeout(() => G(E - 1, "smooth"), 50), H.current = E;
676
- }, [E, u]), rt(() => {
677
- const p = l.current;
678
- if (!p) return;
679
- const O = () => {
680
- const { scrollTop: F, scrollHeight: Z, clientHeight: q } = p, L = Z - F - q;
681
- z.current = L < 5, L > 100 && (D.current = !0), L < 5 && (D.current = !1);
682
- let st = 0;
683
- for (let Y = 0; Y < A.length; Y++)
684
- if (A[Y] > F - e * a) {
685
- st = Math.max(0, Y - 1);
686
- break;
687
- }
688
- let dt = st;
689
- const jt = F + q;
690
- for (let Y = st; Y < A.length && !(A[Y] > jt + e * a); Y++)
691
- dt = Y;
692
- const vt = Math.max(0, st), ht = Math.min(
693
- E,
694
- dt + 1 + a
695
- );
696
- (vt !== it.current.startIndex || ht !== it.current.endIndex) && (it.current = {
697
- startIndex: vt,
698
- endIndex: ht
699
- }, x({
700
- startIndex: vt,
701
- endIndex: ht
702
- }));
760
+ Y(() => {
761
+ const y = d.current;
762
+ if (!(!y || !i))
763
+ return y.addEventListener("scroll", k, {
764
+ passive: !0
765
+ }), () => {
766
+ y.removeEventListener("scroll", k);
767
+ };
768
+ }, [k, i]);
769
+ const A = ce(
770
+ (y = "smooth") => {
771
+ const w = d.current;
772
+ if (!w) return;
773
+ R.current.isUserScrolling = !1, R.current.isNearBottom = !0, R.current.scrollUpCount = 0;
774
+ const C = () => {
775
+ const $ = (j = 0) => {
776
+ if (j > 5) return;
777
+ const D = w.scrollHeight, z = w.scrollTop, Q = w.clientHeight;
778
+ z + Q >= D - 1 || (w.scrollTo({
779
+ top: D,
780
+ behavior: y
781
+ }), setTimeout(() => {
782
+ const X = w.scrollHeight, ge = w.scrollTop;
783
+ (X !== D || ge + Q < X - 1) && $(j + 1);
784
+ }, 50));
785
+ };
786
+ $();
787
+ };
788
+ "requestIdleCallback" in window ? requestIdleCallback(C, { timeout: 100 }) : requestAnimationFrame(() => {
789
+ requestAnimationFrame(C);
790
+ });
791
+ },
792
+ []
793
+ );
794
+ return Y(() => {
795
+ if (!i || !d.current) return;
796
+ const y = d.current, w = R.current;
797
+ let C;
798
+ const $ = () => {
799
+ clearTimeout(C), C = setTimeout(() => {
800
+ !w.isUserScrolling && w.isNearBottom && A(
801
+ _.current ? "instant" : "smooth"
802
+ );
803
+ }, 100);
804
+ }, j = new MutationObserver(() => {
805
+ w.isUserScrolling || $();
806
+ });
807
+ j.observe(y, {
808
+ childList: !0,
809
+ subtree: !0,
810
+ attributes: !0,
811
+ attributeFilter: ["style", "class"]
812
+ // More specific than just 'height'
813
+ });
814
+ const D = (z) => {
815
+ z.target instanceof HTMLImageElement && !w.isUserScrolling && $();
703
816
  };
704
- return p.addEventListener("scroll", O, {
705
- passive: !0
706
- }), O(), () => p.removeEventListener("scroll", O);
707
- }, [A, E, e, a]);
708
- const J = Et(() => {
709
- z.current = !0, D.current = !1, l.current && (l.current.scrollTop = l.current.scrollHeight);
710
- }, []), G = Et(
711
- (p, O = "smooth") => {
712
- const F = l.current;
713
- if (!F) return;
714
- const Z = V?.[p];
715
- if (Z) {
716
- const L = [...r, Z], dt = o.getState().getShadowMetadata(t, L)?.virtualizer?.domRef;
717
- if (dt?.scrollIntoView) {
718
- dt.scrollIntoView({ behavior: O, block: "nearest" });
719
- return;
817
+ return y.addEventListener("load", D, !0), _.current ? setTimeout(() => {
818
+ A("instant");
819
+ }, 0) : $(), () => {
820
+ clearTimeout(C), j.disconnect(), y.removeEventListener("load", D, !0);
821
+ };
822
+ }, [i, O.length, A]), {
823
+ virtualState: de(() => {
824
+ const y = t.getState(), w = y.getShadowValue(
825
+ [e, ...o].join(".")
826
+ ), C = y.getShadowMetadata(e, o)?.arrayKeys || [], $ = w.slice(
827
+ I.startIndex,
828
+ I.endIndex + 1
829
+ ), j = C.slice(
830
+ I.startIndex,
831
+ I.endIndex + 1
832
+ );
833
+ return u({
834
+ currentState: $,
835
+ path: o,
836
+ componentId: M,
837
+ meta: { ...S, validIds: j }
838
+ });
839
+ }, [I.startIndex, I.endIndex, O.length]),
840
+ virtualizerProps: {
841
+ outer: {
842
+ ref: d,
843
+ style: {
844
+ overflowY: "auto",
845
+ height: "100%",
846
+ position: "relative"
847
+ }
848
+ },
849
+ inner: {
850
+ style: {
851
+ height: `${W}px`,
852
+ position: "relative"
853
+ }
854
+ },
855
+ list: {
856
+ style: {
857
+ transform: `translateY(${B.current.get(
858
+ O[I.startIndex]
859
+ )?.offset || 0}px)`
720
860
  }
721
861
  }
722
- const q = A[p];
723
- q !== void 0 && F.scrollTo({ top: q, behavior: O });
724
862
  },
725
- [A, t, r, V]
726
- // Add `orderedIds` to dependency array
727
- ), j = {
728
- outer: {
729
- ref: l,
730
- style: { overflowY: "auto", height: "100%" }
731
- },
732
- inner: {
733
- style: { height: `${N}px`, position: "relative" }
734
- },
735
- list: {
736
- style: {
737
- transform: `translateY(${A[m.startIndex] || 0}px)`
863
+ scrollToBottom: A,
864
+ scrollToIndex: (y, w = "smooth") => {
865
+ if (d.current && O[y]) {
866
+ const C = B.current.get(O[y])?.offset || 0;
867
+ d.current.scrollTo({ top: C, behavior: w });
738
868
  }
739
869
  }
740
870
  };
741
- return {
742
- virtualState: b,
743
- virtualizerProps: j,
744
- scrollToBottom: J,
745
- scrollToIndex: G
746
- };
747
871
  };
748
- if (c === "stateMap")
749
- return (n) => {
750
- const e = y, a = h?.validIds || s(r) || [], u = $(y, r, h);
751
- return e.map((d, l) => {
752
- const m = a[l] || `id:${d.id}`, x = [...r, m], T = $(d, x, h);
753
- return n(
754
- d,
755
- T,
756
- l,
757
- y,
758
- u
759
- );
872
+ if (f === "stateMap")
873
+ return (a) => {
874
+ const [n, r] = Z(
875
+ S?.validIds ?? t.getState().getShadowMetadata(e, o)?.arrayKeys
876
+ ), i = t.getState().getShadowValue(N, S?.validIds);
877
+ if (!n)
878
+ throw new Error("No array keys found for mapping");
879
+ const m = u({
880
+ currentState: i,
881
+ path: o,
882
+ componentId: M,
883
+ meta: S
760
884
  });
761
- };
762
- if (c === "stateMapNoRender")
763
- return (n) => {
764
- const e = y, a = h?.validIds || s(r) || [], u = $(y, r, h);
765
- return e.map((d, l) => {
766
- const m = a[l] || `id:${d.id}`, x = [...r, m], T = $(d, x, h);
767
- return n(
768
- d,
769
- T,
770
- l,
771
- y,
772
- u
885
+ return i.map((d, I) => {
886
+ const P = n[I]?.split(".").slice(1), U = u({
887
+ currentState: d,
888
+ path: P,
889
+ componentId: M,
890
+ meta: S
891
+ });
892
+ return a(
893
+ U,
894
+ I,
895
+ m
773
896
  );
774
897
  });
775
898
  };
776
- if (c === "$stateMap")
777
- return (n) => gt(Kt, {
778
- proxy: { _stateKey: t, _path: r, _mapFn: n },
779
- rebuildStateShape: $
899
+ if (f === "$stateMap")
900
+ return (a) => le(ze, {
901
+ proxy: {
902
+ _stateKey: e,
903
+ _path: o,
904
+ _mapFn: a,
905
+ _meta: S
906
+ },
907
+ rebuildStateShape: u
780
908
  });
781
- if (c === "stateList")
782
- return (n) => {
783
- const e = y;
784
- if (!Array.isArray(e)) return null;
785
- const a = h?.validIds || s(r) || [], u = s(r) || [], d = $(
786
- e,
787
- r,
788
- h
909
+ if (f === "stateFilter")
910
+ return (a) => {
911
+ const n = S?.validIds ?? t.getState().getShadowMetadata(e, o)?.arrayKeys;
912
+ if (!n)
913
+ throw new Error("No array keys found for filtering.");
914
+ const r = [], i = T.filter(
915
+ (m, d) => a(m, d) ? (r.push(n[d]), !0) : !1
789
916
  );
790
- return e.map((l, m) => {
791
- const x = a[m] || `id:${l.id}`, T = u.indexOf(x), R = [...r, x], z = $(l, R, h), D = `${S}-${r.join(".")}-${x}`;
792
- return gt(ee, {
793
- key: x,
794
- stateKey: t,
795
- itemComponentId: D,
796
- itemPath: R,
797
- children: n(
798
- l,
799
- z,
800
- { localIndex: m, originalIndex: T },
801
- e,
802
- d
803
- )
804
- });
917
+ return u({
918
+ currentState: i,
919
+ path: o,
920
+ componentId: M,
921
+ meta: {
922
+ validIds: r,
923
+ transforms: [
924
+ ...S?.transforms || [],
925
+ {
926
+ type: "filter",
927
+ fn: a
928
+ }
929
+ ]
930
+ }
805
931
  });
806
932
  };
807
- if (c === "stateFlattenOn")
808
- return (n) => {
809
- const e = y;
810
- I.clear(), k++;
811
- const a = e.flatMap(
812
- (u) => u[n] ?? []
813
- );
814
- return $(
815
- a,
816
- [...r, "[*]", n],
817
- h
933
+ if (f === "stateSort")
934
+ return (a) => {
935
+ const n = S?.validIds ?? t.getState().getShadowMetadata(e, o)?.arrayKeys;
936
+ if (!n)
937
+ throw new Error("No array keys found for sorting");
938
+ const r = T.map((i, m) => ({
939
+ item: i,
940
+ key: n[m]
941
+ }));
942
+ return r.sort((i, m) => a(i.item, m.item)).filter(Boolean), u({
943
+ currentState: r.map((i) => i.item),
944
+ path: o,
945
+ componentId: M,
946
+ meta: {
947
+ validIds: r.map((i) => i.key),
948
+ transforms: [
949
+ ...S?.transforms || [],
950
+ { type: "sort", fn: a }
951
+ ]
952
+ }
953
+ });
954
+ };
955
+ if (f === "stream")
956
+ return function(a = {}) {
957
+ const {
958
+ bufferSize: n = 100,
959
+ flushInterval: r = 100,
960
+ bufferStrategy: i = "accumulate",
961
+ store: m,
962
+ onFlush: d
963
+ } = a;
964
+ let I = [], P = !1, U = null;
965
+ const x = (W) => {
966
+ if (!P) {
967
+ if (i === "sliding" && I.length >= n)
968
+ I.shift();
969
+ else if (i === "dropping" && I.length >= n)
970
+ return;
971
+ I.push(W), I.length >= n && _();
972
+ }
973
+ }, _ = () => {
974
+ if (I.length === 0) return;
975
+ const W = [...I];
976
+ if (I = [], m) {
977
+ const b = m(W);
978
+ b !== void 0 && (Array.isArray(b) ? b : [b]).forEach((A) => {
979
+ s(A, o, {
980
+ updateType: "insert"
981
+ });
982
+ });
983
+ } else
984
+ W.forEach((b) => {
985
+ s(b, o, {
986
+ updateType: "insert"
987
+ });
988
+ });
989
+ d?.(W);
990
+ };
991
+ r > 0 && (U = setInterval(_, r));
992
+ const R = ee(), B = t.getState().getShadowMetadata(e, o) || {}, O = B.streams || /* @__PURE__ */ new Map();
993
+ return O.set(R, { buffer: I, flushTimer: U }), t.getState().setShadowMetadata(e, o, {
994
+ ...B,
995
+ streams: O
996
+ }), {
997
+ write: (W) => x(W),
998
+ writeMany: (W) => W.forEach(x),
999
+ flush: () => _(),
1000
+ pause: () => {
1001
+ P = !0;
1002
+ },
1003
+ resume: () => {
1004
+ P = !1, I.length > 0 && _();
1005
+ },
1006
+ close: () => {
1007
+ _(), U && clearInterval(U);
1008
+ const W = t.getState().getShadowMetadata(e, o);
1009
+ W?.streams && W.streams.delete(R);
1010
+ }
1011
+ };
1012
+ };
1013
+ if (f === "stateList")
1014
+ return (a) => /* @__PURE__ */ ae(() => {
1015
+ const r = q(/* @__PURE__ */ new Map()), i = S?.transforms && S.transforms.length > 0 ? `${M}-${qe(S.transforms)}` : `${M}-base`, [m, d] = Z({}), { validIds: I, arrayValues: P } = de(() => {
1016
+ const x = t.getState().getShadowMetadata(e, o)?.transformCaches?.get(i);
1017
+ let _;
1018
+ x && x.validIds ? _ = x.validIds : (_ = ve(
1019
+ e,
1020
+ o,
1021
+ S?.transforms
1022
+ ), t.getState().setTransformCache(e, o, i, {
1023
+ validIds: _,
1024
+ computedAt: Date.now(),
1025
+ transforms: S?.transforms || []
1026
+ }));
1027
+ const R = t.getState().getShadowValue(N, _);
1028
+ return {
1029
+ validIds: _,
1030
+ arrayValues: R || []
1031
+ };
1032
+ }, [i, m]);
1033
+ if (Y(() => {
1034
+ const x = t.getState().subscribeToPath(N, (_) => {
1035
+ if (console.log("statelsit subscribed to path", _), _.type === "GET_SELECTED")
1036
+ return;
1037
+ const B = t.getState().getShadowMetadata(e, o)?.transformCaches;
1038
+ if (B)
1039
+ for (const O of B.keys())
1040
+ O.startsWith(M) && B.delete(O);
1041
+ _.type === "INSERT" && d({});
1042
+ });
1043
+ return () => {
1044
+ x();
1045
+ };
1046
+ }, [M, N]), !Array.isArray(P))
1047
+ return null;
1048
+ const U = u({
1049
+ currentState: P,
1050
+ path: o,
1051
+ componentId: M,
1052
+ meta: {
1053
+ ...S,
1054
+ validIds: I
1055
+ }
1056
+ });
1057
+ return /* @__PURE__ */ ae(ke, { children: P.map((x, _) => {
1058
+ const R = I[_];
1059
+ if (!R)
1060
+ return null;
1061
+ let B = r.current.get(R);
1062
+ B || (B = ee(), r.current.set(R, B));
1063
+ const O = R.split(".").slice(1);
1064
+ return le(we, {
1065
+ key: R,
1066
+ stateKey: e,
1067
+ itemComponentId: B,
1068
+ itemPath: O,
1069
+ localIndex: _,
1070
+ arraySetter: U,
1071
+ rebuildStateShape: u,
1072
+ renderFn: a
1073
+ });
1074
+ }) });
1075
+ }, {});
1076
+ if (f === "stateFlattenOn")
1077
+ return (a) => {
1078
+ const n = T;
1079
+ v.clear(), h++;
1080
+ const r = n.flatMap(
1081
+ (i) => i[a] ?? []
818
1082
  );
1083
+ return u({
1084
+ currentState: r,
1085
+ path: [...o, "[*]", a],
1086
+ componentId: M,
1087
+ meta: S
1088
+ });
819
1089
  };
820
- if (c === "index")
821
- return (n) => {
822
- const a = (h?.validIds || s(r))?.[n];
823
- if (!a)
824
- return $(void 0, [
825
- ...r,
826
- n.toString()
827
- ]);
828
- const d = o.getState().getNestedState(t, r).find(
829
- (m) => `id:${m.id}` === a
830
- ), l = [...r, a];
831
- return $(d, l, h);
1090
+ if (f === "index")
1091
+ return (a) => {
1092
+ const r = t.getState().getShadowMetadata(e, o)?.arrayKeys?.filter(
1093
+ (d) => !S?.validIds || S?.validIds && S?.validIds?.includes(d)
1094
+ )?.[a];
1095
+ if (!r) return;
1096
+ const i = t.getState().getShadowValue(r, S?.validIds);
1097
+ return u({
1098
+ currentState: i,
1099
+ path: r.split(".").slice(1),
1100
+ componentId: M,
1101
+ meta: S
1102
+ });
832
1103
  };
833
- if (c === "last")
1104
+ if (f === "last")
834
1105
  return () => {
835
- const n = o.getState().getNestedState(t, r);
836
- if (n.length === 0) return;
837
- const e = n.length - 1, a = n[e], u = [...r, e.toString()];
838
- return $(a, u);
1106
+ const a = t.getState().getShadowValue(e, o);
1107
+ if (a.length === 0) return;
1108
+ const n = a.length - 1, r = a[n], i = [...o, n.toString()];
1109
+ return u({
1110
+ currentState: r,
1111
+ path: i,
1112
+ componentId: M,
1113
+ meta: S
1114
+ });
839
1115
  };
840
- if (c === "insert")
841
- return (n) => (w(r), wt(i, n, r, t), $(
842
- o.getState().getNestedState(t, r),
843
- r
844
- ));
845
- if (c === "uniqueInsert")
846
- return (n, e, a) => {
847
- const u = o.getState().getNestedState(t, r), d = tt(n) ? n(u) : n;
848
- let l = null;
849
- if (!u.some((x) => {
850
- const T = e ? e.every(
851
- (R) => Q(x[R], d[R])
852
- ) : Q(x, d);
853
- return T && (l = x), T;
1116
+ if (f === "insert")
1117
+ return (a, n) => (s(a, o, { updateType: "insert" }), u({
1118
+ currentState: t.getState().getShadowValue(e, o),
1119
+ path: o,
1120
+ componentId: M,
1121
+ meta: S
1122
+ }));
1123
+ if (f === "uniqueInsert")
1124
+ return (a, n, r) => {
1125
+ const i = t.getState().getShadowValue(e, o), m = K(a) ? a(i) : a;
1126
+ let d = null;
1127
+ if (!i.some((P) => {
1128
+ const U = n ? n.every(
1129
+ (x) => ie(P[x], m[x])
1130
+ ) : ie(P, m);
1131
+ return U && (d = P), U;
854
1132
  }))
855
- w(r), wt(i, d, r, t);
856
- else if (a && l) {
857
- const x = a(l), T = u.map(
858
- (R) => Q(R, l) ? x : R
1133
+ V(o), s(m, o, { updateType: "insert" });
1134
+ else if (r && d) {
1135
+ const P = r(d), U = i.map(
1136
+ (x) => ie(x, d) ? P : x
859
1137
  );
860
- w(r), ut(i, T, r);
1138
+ V(o), s(U, o, {
1139
+ updateType: "update"
1140
+ });
861
1141
  }
862
1142
  };
863
- if (c === "cut")
864
- return (n, e) => {
865
- if (!e?.waitForSync)
866
- return w(r), ft(i, r, t, n), $(
867
- o.getState().getNestedState(t, r),
868
- r
869
- );
1143
+ if (f === "cut")
1144
+ return (a, n) => {
1145
+ const r = S?.validIds ?? t.getState().getShadowMetadata(e, o)?.arrayKeys;
1146
+ if (!r || r.length === 0) return;
1147
+ const i = a == -1 ? r.length - 1 : a !== void 0 ? a : r.length - 1, m = r[i];
1148
+ if (!m) return;
1149
+ const d = m.split(".").slice(1);
1150
+ s(T, d, {
1151
+ updateType: "cut"
1152
+ });
870
1153
  };
871
- if (c === "cutByValue")
872
- return (n) => {
873
- const e = y.findIndex((a) => a === n);
874
- e > -1 && ft(i, r, t, e);
1154
+ if (f === "cutSelected")
1155
+ return () => {
1156
+ t.getState().getShadowMetadata(e, o)?.arrayKeys;
1157
+ const a = ve(
1158
+ e,
1159
+ o,
1160
+ S?.transforms
1161
+ );
1162
+ if (console.log("validKeys", a), !a || a.length === 0) return;
1163
+ const n = t.getState().selectedIndicesMap.get(N);
1164
+ let r = a.findIndex(
1165
+ (m) => m === n
1166
+ );
1167
+ console.log("indexToCut", r);
1168
+ const i = a[r == -1 ? a.length - 1 : r]?.split(".").slice(1);
1169
+ console.log("pathForCut", i), s(T, i, {
1170
+ updateType: "cut"
1171
+ });
875
1172
  };
876
- if (c === "toggleByValue")
877
- return (n) => {
878
- const e = y.findIndex((a) => a === n);
879
- e > -1 ? ft(i, r, t, e) : wt(i, n, r, t);
1173
+ if (f === "cutByValue")
1174
+ return (a) => {
1175
+ const n = t.getState().getShadowMetadata(e, o), r = S?.validIds ?? n?.arrayKeys;
1176
+ if (!r) return;
1177
+ let i = null;
1178
+ for (const m of r)
1179
+ if (t.getState().getShadowValue(m) === a) {
1180
+ i = m;
1181
+ break;
1182
+ }
1183
+ if (i) {
1184
+ const m = i.split(".").slice(1);
1185
+ s(null, m, { updateType: "cut" });
1186
+ }
880
1187
  };
881
- if (c === "stateFilter")
882
- return (n) => {
883
- const e = h?.validIds || s(r) || [], a = o.getState().getNestedState(t, r), u = new Map(
884
- a.map((m) => [`id:${m.id}`, m])
885
- ), d = [], l = [];
886
- return e.forEach((m, x) => {
887
- const T = u.get(m);
888
- T && n(T, x) && (d.push(m), l.push(T));
889
- }), $(l, r, {
890
- validIds: d
891
- });
1188
+ if (f === "toggleByValue")
1189
+ return (a) => {
1190
+ const n = t.getState().getShadowMetadata(e, o), r = S?.validIds ?? n?.arrayKeys;
1191
+ if (!r) return;
1192
+ let i = null;
1193
+ for (const m of r) {
1194
+ const d = t.getState().getShadowValue(m);
1195
+ if (console.log("itemValue sdasdasdasd", d), d === a) {
1196
+ i = m;
1197
+ break;
1198
+ }
1199
+ }
1200
+ if (console.log("itemValue keyToCut", i), i) {
1201
+ const m = i.split(".").slice(1);
1202
+ console.log("itemValue keyToCut", i), s(a, m, {
1203
+ updateType: "cut"
1204
+ });
1205
+ } else
1206
+ s(a, o, { updateType: "insert" });
892
1207
  };
893
- if (c === "stateSort")
894
- return (n) => {
895
- const a = y.map((l) => ({
896
- item: l,
897
- id: `id:${l.id}`
898
- }));
899
- a.sort((l, m) => n(l.item, m.item));
900
- const u = a.map((l) => l.item), d = a.map((l) => l.id);
901
- return $(u, r, {
902
- validIds: d
1208
+ if (f === "findWith")
1209
+ return (a, n) => {
1210
+ const r = t.getState().getShadowMetadata(e, o)?.arrayKeys;
1211
+ if (!r)
1212
+ throw new Error("No array keys found for sorting");
1213
+ let i = null, m = [];
1214
+ for (const d of r) {
1215
+ let I = t.getState().getShadowValue(d, S?.validIds);
1216
+ if (I && I[a] === n) {
1217
+ i = I, m = d.split(".").slice(1);
1218
+ break;
1219
+ }
1220
+ }
1221
+ return u({
1222
+ currentState: i,
1223
+ path: m,
1224
+ componentId: M,
1225
+ meta: S
903
1226
  });
904
1227
  };
905
- if (c === "findWith")
906
- return (n, e) => {
907
- const a = y.find(
908
- (l) => l[n] === e
909
- );
910
- if (!a) return;
911
- const u = `id:${a.id}`, d = [...r, u];
912
- return $(a, d, h);
913
- };
914
- }
915
- const P = r[r.length - 1];
916
- if (!isNaN(Number(P))) {
917
- const n = r.slice(0, -1), e = o.getState().getNestedState(t, n);
918
- if (Array.isArray(e) && c === "cut")
919
- return () => ft(
920
- i,
921
- n,
922
- t,
923
- Number(P)
924
- );
925
1228
  }
926
- if (c === "get")
1229
+ if (f === "cut") {
1230
+ let a = t.getState().getShadowValue(o.join("."));
927
1231
  return () => {
928
- if (h?.validIds && Array.isArray(y)) {
929
- const n = o.getState().getNestedState(t, r);
930
- if (!Array.isArray(n)) return [];
931
- const e = new Map(
932
- n.map((a) => [`id:${a.id}`, a])
933
- );
934
- return h.validIds.map((a) => e.get(a)).filter(Boolean);
935
- }
936
- return o.getState().getNestedState(t, r);
1232
+ s(a, o, { updateType: "cut" });
937
1233
  };
938
- if (c === "$derive")
939
- return (n) => Ct({
940
- _stateKey: t,
941
- _path: r,
942
- _effect: n.toString()
1234
+ }
1235
+ if (f === "get")
1236
+ return () => (Ee(e, M, o), t.getState().getShadowValue(N, S?.validIds));
1237
+ if (f === "$derive")
1238
+ return (a) => be({
1239
+ _stateKey: e,
1240
+ _path: o,
1241
+ _effect: a.toString(),
1242
+ _meta: S
943
1243
  });
944
- if (c === "$get")
945
- return () => Ct({ _stateKey: t, _path: r });
946
- if (c === "lastSynced") {
947
- const n = `${t}:${r.join(".")}`;
948
- return o.getState().getSyncInfo(n);
1244
+ if (f === "$get")
1245
+ return () => be({ _stateKey: e, _path: o, _meta: S });
1246
+ if (f === "lastSynced") {
1247
+ const a = `${e}:${o.join(".")}`;
1248
+ return t.getState().getSyncInfo(a);
949
1249
  }
950
- if (c == "getLocalStorage")
951
- return (n) => It(g + "-" + t + "-" + n);
952
- if (c === "_selected") {
953
- const n = r.slice(0, -1), e = n.join(".");
954
- if (Array.isArray(
955
- o.getState().getNestedState(t, n)
1250
+ if (f == "getLocalStorage")
1251
+ return (a) => fe(g + "-" + e + "-" + a);
1252
+ if (f === "isSelected") {
1253
+ const a = [e, ...o].slice(0, -1);
1254
+ if (he(e, o, void 0), Array.isArray(
1255
+ t.getState().getShadowValue(a.join("."), S?.validIds)
956
1256
  )) {
957
- const a = r[r.length - 1];
958
- return s(n)?.indexOf(a) === o.getState().getSelectedIndex(t, e);
1257
+ o[o.length - 1];
1258
+ const n = a.join("."), r = t.getState().selectedIndicesMap.get(n), i = e + "." + o.join(".");
1259
+ return r === i;
959
1260
  }
960
1261
  return;
961
1262
  }
962
- if (c === "setSelected")
963
- return (n) => {
964
- const e = r.slice(0, -1), a = r[r.length - 1], d = s(e)?.indexOf(a);
965
- if (d === void 0 || d === -1) return;
966
- const l = e.join(".");
967
- o.getState().setSelectedIndex(
968
- t,
969
- l,
970
- n ? d : void 0
971
- );
972
- const m = o.getState().getNestedState(t, [...e]);
973
- ut(i, m, e), w(e);
1263
+ if (f === "setSelected")
1264
+ return (a) => {
1265
+ const n = o.slice(0, -1), r = e + "." + n.join("."), i = e + "." + o.join(".");
1266
+ he(e, n, void 0), t.getState().selectedIndicesMap.get(r), a && t.getState().setSelectedIndex(r, i);
974
1267
  };
975
- if (c === "toggleSelected")
1268
+ if (f === "toggleSelected")
976
1269
  return () => {
977
- const n = r.slice(0, -1), e = r[r.length - 1], u = s(n)?.indexOf(e);
978
- if (u === void 0 || u === -1) return;
979
- const d = n.join("."), l = o.getState().getSelectedIndex(t, d);
980
- o.getState().setSelectedIndex(
981
- t,
982
- d,
983
- l === u ? void 0 : u
984
- );
985
- const m = o.getState().getNestedState(t, [...n]);
986
- ut(i, m, n), w(n);
1270
+ const a = o.slice(0, -1), n = e + "." + a.join("."), r = e + "." + o.join(".");
1271
+ t.getState().selectedIndicesMap.get(n) === r ? t.getState().clearSelectedIndex({ arrayKey: n }) : t.getState().setSelectedIndex(n, r);
987
1272
  };
988
- if (r.length == 0) {
989
- if (c === "addValidation")
990
- return (n) => {
991
- const e = o.getState().getInitialOptions(t)?.validation;
992
- if (!e?.key) throw new Error("Validation key not found");
993
- K(e.key), n.forEach((a) => {
994
- const u = [e.key, ...a.path].join(".");
995
- xt(u, a.message);
996
- }), nt(t);
1273
+ if (f === "_componentId")
1274
+ return M;
1275
+ if (o.length == 0) {
1276
+ if (f === "addValidation")
1277
+ return (a) => {
1278
+ const n = t.getState().getInitialOptions(e)?.validation;
1279
+ if (!n?.key) throw new Error("Validation key not found");
1280
+ ne(n.key), a.forEach((r) => {
1281
+ const i = [n.key, ...r.path].join(".");
1282
+ pe(i, r.message);
1283
+ }), re(e);
997
1284
  };
998
- if (c === "applyJsonPatch")
999
- return (n) => {
1000
- const e = o.getState().cogsStateStore[t], a = zt(e, n).newDocument;
1001
- Rt(
1002
- t,
1003
- o.getState().initialStateGlobal[t],
1004
- a,
1005
- i,
1006
- S,
1007
- g
1008
- ), nt(t);
1285
+ if (f === "applyJsonPatch")
1286
+ return (a) => {
1287
+ const n = t.getState().getShadowValue(N, S?.validIds);
1288
+ Le(n, a).newDocument, re(e);
1009
1289
  };
1010
- if (c === "validateZodSchema")
1290
+ if (f === "validateZodSchema")
1011
1291
  return () => {
1012
- const n = o.getState().getInitialOptions(t)?.validation;
1013
- if (!n?.zodSchema || !n?.key)
1292
+ const a = t.getState().getInitialOptions(e)?.validation;
1293
+ if (!a?.zodSchema || !a?.key)
1014
1294
  throw new Error("Zod schema or validation key not found");
1015
- K(n.key);
1016
- const e = o.getState().cogsStateStore[t], a = n.zodSchema.safeParse(e);
1017
- return a.success ? !0 : (a.error.errors.forEach((u) => {
1018
- const d = [n.key, ...u.path].join(".");
1019
- xt(d, u.message);
1020
- }), nt(t), !1);
1295
+ ne(a.key);
1296
+ const n = t.getState().getShadowValue(e), r = a.zodSchema.safeParse(n);
1297
+ return r.success ? !0 : (r.error.errors.forEach((i) => {
1298
+ const m = [a.key, ...i.path].join(".");
1299
+ pe(m, i.message);
1300
+ }), re(e), !1);
1021
1301
  };
1022
- if (c === "_componentId") return S;
1023
- if (c === "getComponents")
1024
- return () => o().stateComponents.get(t);
1025
- if (c === "getAllFormRefs")
1026
- return () => Vt.getState().getFormRefsByStateKey(t);
1027
- if (c === "_initialState")
1028
- return o.getState().initialStateGlobal[t];
1029
- if (c === "_serverState")
1030
- return o.getState().serverState[t];
1031
- if (c === "_isLoading")
1032
- return o.getState().isLoadingGlobal[t];
1033
- if (c === "revertToInitialState")
1034
- return v.revertToInitialState;
1035
- if (c === "updateInitialState") return v.updateInitialState;
1036
- if (c === "removeValidation") return v.removeValidation;
1302
+ if (f === "getComponents")
1303
+ return () => t.getState().getShadowMetadata(e, [])?.components;
1304
+ if (f === "getAllFormRefs")
1305
+ return () => ye.getState().getFormRefsByStateKey(e);
1037
1306
  }
1038
- if (c === "getFormRef")
1039
- return () => Vt.getState().getFormRef(t + "." + r.join("."));
1040
- if (c === "validationWrapper")
1307
+ if (f === "getFormRef")
1308
+ return () => ye.getState().getFormRef(e + "." + o.join("."));
1309
+ if (f === "validationWrapper")
1041
1310
  return ({
1042
- children: n,
1043
- hideMessage: e
1044
- }) => /* @__PURE__ */ $t(
1045
- Lt,
1311
+ children: a,
1312
+ hideMessage: n
1313
+ }) => /* @__PURE__ */ ae(
1314
+ Me,
1046
1315
  {
1047
- formOpts: e ? { validation: { message: "" } } : void 0,
1048
- path: r,
1049
- stateKey: t,
1050
- children: n
1316
+ formOpts: n ? { validation: { message: "" } } : void 0,
1317
+ path: o,
1318
+ stateKey: e,
1319
+ children: a
1051
1320
  }
1052
1321
  );
1053
- if (c === "_stateKey") return t;
1054
- if (c === "_path") return r;
1055
- if (c === "_isServerSynced") return v._isServerSynced;
1056
- if (c === "update")
1057
- return (n, e) => {
1058
- if (e?.debounce)
1059
- Gt(() => {
1060
- ut(i, n, r, "");
1061
- const a = o.getState().getNestedState(t, r);
1062
- e?.afterUpdate && e.afterUpdate(a);
1063
- }, e.debounce);
1064
- else {
1065
- ut(i, n, r, "");
1066
- const a = o.getState().getNestedState(t, r);
1067
- e?.afterUpdate && e.afterUpdate(a);
1068
- }
1069
- w(r);
1322
+ if (f === "_stateKey") return e;
1323
+ if (f === "_path") return o;
1324
+ if (f === "update")
1325
+ return (a) => {
1326
+ s(a, o, { updateType: "update" });
1070
1327
  };
1071
- if (c === "formElement")
1072
- return (n, e) => /* @__PURE__ */ $t(
1073
- Wt,
1328
+ if (f === "toggle") {
1329
+ const a = t.getState().getShadowValue([e, ...o].join("."));
1330
+ if (console.log("currentValueAtPath", a), typeof T != "boolean")
1331
+ throw new Error("toggle() can only be used on boolean values");
1332
+ return () => {
1333
+ s(!a, o, {
1334
+ updateType: "update"
1335
+ });
1336
+ };
1337
+ }
1338
+ if (f === "formElement")
1339
+ return (a, n) => /* @__PURE__ */ ae(
1340
+ Me,
1074
1341
  {
1075
- setState: i,
1076
- stateKey: t,
1077
- path: r,
1078
- child: n,
1079
- formOpts: e
1342
+ formOpts: n,
1343
+ path: o,
1344
+ stateKey: e,
1345
+ children: /* @__PURE__ */ ae(
1346
+ Ze,
1347
+ {
1348
+ stateKey: e,
1349
+ path: o,
1350
+ rebuildStateShape: u,
1351
+ setState: s,
1352
+ formOpts: n,
1353
+ renderFn: a
1354
+ }
1355
+ )
1080
1356
  }
1081
1357
  );
1082
- const at = [...r, c], yt = o.getState().getNestedState(t, at);
1083
- return $(yt, at, h);
1358
+ const se = [...o, f], Ie = t.getState().getShadowValue(e, se);
1359
+ return u({
1360
+ currentState: Ie,
1361
+ path: se,
1362
+ componentId: M,
1363
+ meta: S
1364
+ });
1084
1365
  }
1085
- }, f = new Proxy(C, X);
1086
- return I.set(M, {
1087
- proxy: f,
1088
- stateVersion: k
1089
- }), f;
1366
+ }, G = new Proxy(c, J);
1367
+ return v.set(L, {
1368
+ proxy: G,
1369
+ stateVersion: h
1370
+ }), G;
1090
1371
  }
1091
- return $(
1092
- o.getState().getNestedState(t, [])
1093
- );
1372
+ const l = {
1373
+ removeValidation: (T) => {
1374
+ T?.validationKey && ne(T.validationKey);
1375
+ },
1376
+ revertToInitialState: (T) => {
1377
+ const o = t.getState().getInitialOptions(e)?.validation;
1378
+ o?.key && ne(o.key), T?.validationKey && ne(T.validationKey);
1379
+ const S = t.getState().getShadowMetadata(e, []);
1380
+ S?.stateSource === "server" && S.baseServerState ? S.baseServerState : t.getState().initialStateGlobal[e];
1381
+ const M = t.getState().initialStateGlobal[e];
1382
+ t.getState().clearSelectedIndexesForState(e), v.clear(), h++, t.getState().initializeShadowState(e, M), u({
1383
+ currentState: M,
1384
+ path: [],
1385
+ componentId: p
1386
+ });
1387
+ const L = te(e), N = K(L?.localStorage?.key) ? L?.localStorage?.key(M) : L?.localStorage?.key, c = `${g}-${e}-${N}`;
1388
+ c && localStorage.removeItem(c);
1389
+ const J = t.getState().getShadowMetadata(e, []);
1390
+ return J && J?.components?.forEach((G) => {
1391
+ G.forceUpdate();
1392
+ }), M;
1393
+ },
1394
+ updateInitialState: (T) => {
1395
+ v.clear(), h++;
1396
+ const o = Pe(
1397
+ e,
1398
+ s,
1399
+ p,
1400
+ g
1401
+ ), S = t.getState().initialStateGlobal[e], M = te(e), L = K(M?.localStorage?.key) ? M?.localStorage?.key(S) : M?.localStorage?.key, N = `${g}-${e}-${L}`;
1402
+ return localStorage.getItem(N) && localStorage.removeItem(N), je(() => {
1403
+ _e(e, T), t.getState().initializeShadowState(e, T);
1404
+ const c = t.getState().getShadowMetadata(e, []);
1405
+ c && c?.components?.forEach((J) => {
1406
+ J.forceUpdate();
1407
+ });
1408
+ }), {
1409
+ fetchId: (c) => o.get()[c]
1410
+ };
1411
+ }
1412
+ };
1413
+ return u({
1414
+ currentState: t.getState().getShadowValue(e, []),
1415
+ componentId: p,
1416
+ path: []
1417
+ });
1094
1418
  }
1095
- function Ct(t) {
1096
- return gt(te, { proxy: t });
1419
+ function be(e) {
1420
+ return le(Ge, { proxy: e });
1097
1421
  }
1098
- function Kt({
1099
- proxy: t,
1100
- rebuildStateShape: i
1422
+ function ze({
1423
+ proxy: e,
1424
+ rebuildStateShape: s
1101
1425
  }) {
1102
- const S = o().getNestedState(t._stateKey, t._path);
1103
- return Array.isArray(S) ? i(
1104
- S,
1105
- t._path
1106
- ).stateMapNoRender(
1107
- (I, k, w, v, s) => t._mapFn(I, k, w, v, s)
1108
- ) : null;
1426
+ const p = q(null), g = q(`map-${crypto.randomUUID()}`), v = q(!1), h = q(/* @__PURE__ */ new Map());
1427
+ Y(() => {
1428
+ const u = p.current;
1429
+ if (!u || v.current) return;
1430
+ const l = setTimeout(() => {
1431
+ const E = t.getState().getShadowMetadata(e._stateKey, e._path) || {}, T = E.mapWrappers || [];
1432
+ T.push({
1433
+ instanceId: g.current,
1434
+ mapFn: e._mapFn,
1435
+ containerRef: u,
1436
+ rebuildStateShape: s,
1437
+ path: e._path,
1438
+ componentId: g.current,
1439
+ meta: e._meta
1440
+ }), t.getState().setShadowMetadata(e._stateKey, e._path, {
1441
+ ...E,
1442
+ mapWrappers: T
1443
+ }), v.current = !0, V();
1444
+ }, 0);
1445
+ return () => {
1446
+ if (clearTimeout(l), g.current) {
1447
+ const E = t.getState().getShadowMetadata(e._stateKey, e._path) || {};
1448
+ E.mapWrappers && (E.mapWrappers = E.mapWrappers.filter(
1449
+ (T) => T.instanceId !== g.current
1450
+ ), t.getState().setShadowMetadata(e._stateKey, e._path, E));
1451
+ }
1452
+ h.current.forEach((E) => E.unmount());
1453
+ };
1454
+ }, []);
1455
+ const V = () => {
1456
+ const u = p.current;
1457
+ if (!u) return;
1458
+ const l = t.getState().getShadowValue(
1459
+ [e._stateKey, ...e._path].join("."),
1460
+ e._meta?.validIds
1461
+ );
1462
+ if (!Array.isArray(l)) return;
1463
+ const E = e._meta?.validIds ?? t.getState().getShadowMetadata(e._stateKey, e._path)?.arrayKeys ?? [], T = s({
1464
+ currentState: l,
1465
+ path: e._path,
1466
+ componentId: g.current,
1467
+ meta: e._meta
1468
+ });
1469
+ l.forEach((o, S) => {
1470
+ const M = E[S];
1471
+ if (!M) return;
1472
+ const L = ee(), N = document.createElement("div");
1473
+ N.setAttribute("data-item-path", M), u.appendChild(N);
1474
+ const c = Ce(N);
1475
+ h.current.set(M, c);
1476
+ const J = M.split(".").slice(1);
1477
+ c.render(
1478
+ le(we, {
1479
+ stateKey: e._stateKey,
1480
+ itemComponentId: L,
1481
+ itemPath: J,
1482
+ localIndex: S,
1483
+ arraySetter: T,
1484
+ rebuildStateShape: s,
1485
+ renderFn: e._mapFn
1486
+ })
1487
+ );
1488
+ });
1489
+ };
1490
+ return /* @__PURE__ */ ae("div", { ref: p, "data-map-container": g.current });
1109
1491
  }
1110
- function te({
1111
- proxy: t
1492
+ function Ge({
1493
+ proxy: e
1112
1494
  }) {
1113
- const i = B(null), S = `${t._stateKey}-${t._path.join(".")}`;
1114
- return rt(() => {
1115
- const g = i.current;
1116
- if (!g || !g.parentElement) return;
1117
- const I = g.parentElement, w = Array.from(I.childNodes).indexOf(g);
1118
- let v = I.getAttribute("data-parent-id");
1119
- v || (v = `parent-${crypto.randomUUID()}`, I.setAttribute("data-parent-id", v));
1120
- const $ = {
1121
- instanceId: `instance-${crypto.randomUUID()}`,
1122
- parentId: v,
1123
- position: w,
1124
- effect: t._effect
1125
- };
1126
- o.getState().addSignalElement(S, $);
1127
- const y = o.getState().getNestedState(t._stateKey, t._path);
1128
- let r = y;
1129
- if (t._effect)
1130
- try {
1131
- r = new Function(
1132
- "state",
1133
- `return (${t._effect})(state)`
1134
- )(y);
1135
- } catch (M) {
1136
- console.error("Error evaluating effect function:", M);
1495
+ const s = q(null), p = q(null), g = q(!1), v = `${e._stateKey}-${e._path.join(".")}`, h = t.getState().getShadowValue(
1496
+ [e._stateKey, ...e._path].join("."),
1497
+ e._meta?.validIds
1498
+ );
1499
+ return Y(() => {
1500
+ const V = s.current;
1501
+ if (!V || g.current) return;
1502
+ const u = setTimeout(() => {
1503
+ if (!V.parentElement) {
1504
+ console.warn("Parent element not found for signal", v);
1505
+ return;
1506
+ }
1507
+ const l = V.parentElement, T = Array.from(l.childNodes).indexOf(V);
1508
+ let o = l.getAttribute("data-parent-id");
1509
+ o || (o = `parent-${crypto.randomUUID()}`, l.setAttribute("data-parent-id", o)), p.current = `instance-${crypto.randomUUID()}`;
1510
+ const S = t.getState().getShadowMetadata(e._stateKey, e._path) || {}, M = S.signals || [];
1511
+ M.push({
1512
+ instanceId: p.current,
1513
+ parentId: o,
1514
+ position: T,
1515
+ effect: e._effect
1516
+ }), t.getState().setShadowMetadata(e._stateKey, e._path, {
1517
+ ...S,
1518
+ signals: M
1519
+ });
1520
+ let L = h;
1521
+ if (e._effect)
1522
+ try {
1523
+ L = new Function(
1524
+ "state",
1525
+ `return (${e._effect})(state)`
1526
+ )(h);
1527
+ } catch (c) {
1528
+ console.error("Error evaluating effect function:", c);
1529
+ }
1530
+ L !== null && typeof L == "object" && (L = JSON.stringify(L));
1531
+ const N = document.createTextNode(String(L ?? ""));
1532
+ V.replaceWith(N), g.current = !0;
1533
+ }, 0);
1534
+ return () => {
1535
+ if (clearTimeout(u), p.current) {
1536
+ const l = t.getState().getShadowMetadata(e._stateKey, e._path) || {};
1537
+ l.signals && (l.signals = l.signals.filter(
1538
+ (E) => E.instanceId !== p.current
1539
+ ), t.getState().setShadowMetadata(e._stateKey, e._path, l));
1137
1540
  }
1138
- r !== null && typeof r == "object" && (r = JSON.stringify(r));
1139
- const h = document.createTextNode(String(r));
1140
- g.replaceWith(h);
1141
- }, [t._stateKey, t._path.join("."), t._effect]), gt("span", {
1142
- ref: i,
1143
- style: { display: "none" },
1144
- "data-signal-id": S
1541
+ };
1542
+ }, []), le("span", {
1543
+ ref: s,
1544
+ style: { display: "contents" },
1545
+ "data-signal-id": v
1145
1546
  });
1146
1547
  }
1147
- function ye(t) {
1148
- const i = Ft(
1149
- (S) => {
1150
- const g = o.getState().stateComponents.get(t._stateKey) || { components: /* @__PURE__ */ new Map() };
1151
- return g.components.set(t._stateKey, {
1152
- forceUpdate: S,
1153
- paths: /* @__PURE__ */ new Set([t._path.join(".")])
1154
- }), o.getState().stateComponents.set(t._stateKey, g), () => g.components.delete(t._stateKey);
1548
+ const we = Re(
1549
+ Ye,
1550
+ (e, s) => e.itemPath.join(".") === s.itemPath.join(".") && e.stateKey === s.stateKey && e.itemComponentId === s.itemComponentId && e.localIndex === s.localIndex
1551
+ ), Je = (e) => {
1552
+ const [s, p] = Z(!1);
1553
+ return ue(() => {
1554
+ if (!e.current) {
1555
+ p(!0);
1556
+ return;
1557
+ }
1558
+ const g = Array.from(e.current.querySelectorAll("img"));
1559
+ if (g.length === 0) {
1560
+ p(!0);
1561
+ return;
1562
+ }
1563
+ let v = 0;
1564
+ const h = () => {
1565
+ v++, v === g.length && p(!0);
1566
+ };
1567
+ return g.forEach((V) => {
1568
+ V.complete ? h() : (V.addEventListener("load", h), V.addEventListener("error", h));
1569
+ }), () => {
1570
+ g.forEach((V) => {
1571
+ V.removeEventListener("load", h), V.removeEventListener("error", h);
1572
+ });
1573
+ };
1574
+ }, [e.current]), s;
1575
+ };
1576
+ function Ye({
1577
+ stateKey: e,
1578
+ itemComponentId: s,
1579
+ itemPath: p,
1580
+ localIndex: g,
1581
+ arraySetter: v,
1582
+ rebuildStateShape: h,
1583
+ renderFn: V
1584
+ }) {
1585
+ const [, u] = Z({}), { ref: l, inView: E } = Oe(), T = q(null), o = Je(T), S = q(!1), M = [e, ...p].join(".");
1586
+ Ue(e, s, u);
1587
+ const L = ce(
1588
+ (H) => {
1589
+ T.current = H, l(H);
1155
1590
  },
1156
- () => o.getState().getNestedState(t._stateKey, t._path)
1591
+ [l]
1157
1592
  );
1158
- return gt("text", {}, String(i));
1593
+ Y(() => {
1594
+ t.getState().subscribeToPath(M, (H) => {
1595
+ u({});
1596
+ });
1597
+ }, []), Y(() => {
1598
+ if (!E || !o || S.current)
1599
+ return;
1600
+ const H = T.current;
1601
+ if (H && H.offsetHeight > 0) {
1602
+ S.current = !0;
1603
+ const f = H.offsetHeight;
1604
+ t.getState().setShadowMetadata(e, p, {
1605
+ virtualizer: {
1606
+ itemHeight: f,
1607
+ domRef: H
1608
+ }
1609
+ });
1610
+ const oe = p.slice(0, -1), se = [e, ...oe].join(".");
1611
+ t.getState().notifyPathSubscribers(se, {
1612
+ type: "ITEMHEIGHT",
1613
+ itemKey: p.join("."),
1614
+ ref: T.current
1615
+ });
1616
+ }
1617
+ }, [E, o, e, p]);
1618
+ const N = [e, ...p].join("."), c = t.getState().getShadowValue(N);
1619
+ if (c === void 0)
1620
+ return null;
1621
+ const J = h({
1622
+ currentState: c,
1623
+ path: p,
1624
+ componentId: s
1625
+ }), G = V(J, g, v);
1626
+ return /* @__PURE__ */ ae("div", { ref: L, children: G });
1159
1627
  }
1160
- function ee({
1161
- stateKey: t,
1162
- itemComponentId: i,
1163
- itemPath: S,
1164
- children: g
1628
+ function Ze({
1629
+ stateKey: e,
1630
+ path: s,
1631
+ rebuildStateShape: p,
1632
+ renderFn: g,
1633
+ formOpts: v,
1634
+ setState: h
1165
1635
  }) {
1166
- const [, I] = lt({}), [k, w] = Ht(), v = B(null), s = B(null), $ = Et(
1167
- (y) => {
1168
- k(y), v.current = y;
1636
+ const [V] = Z(() => ee()), [, u] = Z({}), l = [e, ...s].join(".");
1637
+ Ue(e, V, u);
1638
+ const E = t.getState().getShadowValue(l), [T, o] = Z(E), S = q(!1), M = q(null);
1639
+ Y(() => {
1640
+ !S.current && !ie(E, T) && o(E);
1641
+ }, [E]), Y(() => {
1642
+ const G = t.getState().subscribeToPath(l, (H) => {
1643
+ u({});
1644
+ });
1645
+ return () => {
1646
+ G(), M.current && (clearTimeout(M.current), S.current = !1);
1647
+ };
1648
+ }, []);
1649
+ const L = ce(
1650
+ (G) => {
1651
+ o(G), S.current = !0, M.current && clearTimeout(M.current);
1652
+ const H = v?.debounceTime ?? 200;
1653
+ M.current = setTimeout(() => {
1654
+ S.current = !1, h(G, s, { updateType: "update" });
1655
+ }, H);
1169
1656
  },
1170
- [k]
1171
- );
1172
- return rt(() => {
1173
- w.height > 0 && w.height !== s.current && (s.current = w.height, o.getState().setShadowMetadata(t, S, {
1174
- virtualizer: { itemHeight: w.height, domRef: v.current }
1175
- }));
1176
- }, [w.height, t, S]), _t(() => {
1177
- const y = `${t}////${i}`, r = o.getState().stateComponents.get(t) || { components: /* @__PURE__ */ new Map() };
1178
- return r.components.set(y, {
1179
- forceUpdate: () => I({}),
1180
- paths: /* @__PURE__ */ new Set([S.join(".")])
1181
- }), o.getState().stateComponents.set(t, r), () => {
1182
- const h = o.getState().stateComponents.get(t);
1183
- h && h.components.delete(y);
1657
+ [h, s, v?.debounceTime]
1658
+ ), N = ce(() => {
1659
+ M.current && (clearTimeout(M.current), S.current = !1, h(T, s, { updateType: "update" }));
1660
+ }, [h, s, T]), c = p({
1661
+ currentState: E,
1662
+ path: s,
1663
+ componentId: V
1664
+ }), J = new Proxy(c, {
1665
+ get(G, H) {
1666
+ return H === "inputProps" ? {
1667
+ value: T ?? "",
1668
+ onChange: (f) => {
1669
+ L(f.target.value);
1670
+ },
1671
+ onBlur: N,
1672
+ ref: ye.getState().getFormRef(e + "." + s.join("."))
1673
+ } : G[H];
1674
+ }
1675
+ });
1676
+ return /* @__PURE__ */ ae(ke, { children: g(J) });
1677
+ }
1678
+ function Ue(e, s, p) {
1679
+ const g = `${e}////${s}`;
1680
+ ue(() => {
1681
+ const v = t.getState().getShadowMetadata(e, []), h = v?.components || /* @__PURE__ */ new Map();
1682
+ return h.set(g, {
1683
+ forceUpdate: () => p({}),
1684
+ paths: /* @__PURE__ */ new Set(),
1685
+ reactiveType: ["component"]
1686
+ }), t.getState().setShadowMetadata(e, [], {
1687
+ ...v,
1688
+ components: h
1689
+ }), () => {
1690
+ const V = t.getState().getShadowMetadata(e, []);
1691
+ V?.components && V.components.delete(g);
1184
1692
  };
1185
- }, [t, i, S.join(".")]), /* @__PURE__ */ $t("div", { ref: $, children: g });
1693
+ }, [e, g]);
1186
1694
  }
1187
1695
  export {
1188
- Ct as $cogsSignal,
1189
- ye as $cogsSignalStore,
1190
- Se as addStateOptions,
1191
- me as createCogsState,
1192
- Ie as notifyComponent,
1193
- Xt as useCogsStateFn
1696
+ be as $cogsSignal,
1697
+ lt as addStateOptions,
1698
+ ut as createCogsState,
1699
+ dt as notifyComponent,
1700
+ Be as useCogsStateFn
1194
1701
  };
1195
1702
  //# sourceMappingURL=CogsState.jsx.map