cogsbox-state 0.5.432 → 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,1231 +1,1702 @@
1
1
  "use client";
2
- import { jsx as $t } from "react/jsx-runtime";
3
- import { useState as dt, useRef as q, useEffect as at, useLayoutEffect as pt, useMemo as Et, createElement as gt, useSyncExternalStore as Ft, startTransition as Ut, useCallback as St } from "react";
4
- import { transformStateFunc as Dt, isDeepEqual as X, isFunction as et, getNestedValue as L, getDifferences as Pt, debounce as Lt } from "./utility.js";
5
- import { pushFunc as At, updateFn as ut, cutFunc as ft, ValidationWrapper as Gt, FormControlComponent as Ht } from "./Functions.jsx";
6
- import zt 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 bt } from "./store.js";
10
- import { useCogsConfig as Rt } from "./CogsStateClient.jsx";
11
- import { applyPatch as Wt } from "fast-json-patch";
12
- import Bt from "react-use-measure";
13
- import "ulid";
14
- function Mt(t, s) {
15
- const S = o.getState().getInitialOptions, g = o.getState().setInitialStateOptions, I = S(t) || {};
16
- g(t, {
17
- ...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
18
  ...s
19
19
  });
20
20
  }
21
- function Nt({
22
- stateKey: t,
21
+ function Ve({
22
+ stateKey: e,
23
23
  options: s,
24
- initialOptionsPart: S
24
+ initialOptionsPart: p
25
25
  }) {
26
- const g = lt(t) || {}, I = S[t] || {}, T = o.getState().setInitialStateOptions, A = { ...I, ...g };
27
- let v = !1;
26
+ const g = te(e) || {}, v = p[e] || {}, h = t.getState().setInitialStateOptions, V = { ...v, ...g };
27
+ let u = !1;
28
28
  if (s)
29
- for (const i in s)
30
- A.hasOwnProperty(i) ? (i == "localStorage" && s[i] && A[i].key !== s[i]?.key && (v = !0, A[i] = s[i]), i == "initialState" && s[i] && A[i] !== s[i] && // Different references
31
- !X(A[i], s[i]) && (v = !0, A[i] = s[i])) : (v = !0, A[i] = s[i]);
32
- v && T(t, A);
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: s, validation: S }) {
35
- return { initialState: t, formElements: s, validation: S };
33
+ function lt(e, { formElements: s, validation: p }) {
34
+ return { initialState: e, formElements: s, validation: p };
36
35
  }
37
- const me = (t, s) => {
38
- let S = t;
39
- const [g, I] = Dt(S);
40
- (Object.keys(I).length > 0 || s && Object.keys(s).length > 0) && Object.keys(I).forEach((v) => {
41
- I[v] = I[v] || {}, I[v].formElements = {
42
- ...s?.formElements,
43
- // Global defaults first
44
- ...s?.validation,
45
- ...I[v].formElements || {}
46
- // State-specific overrides
47
- }, lt(v) || o.getState().setInitialStateOptions(v, I[v]);
48
- }), o.getState().setInitialStates(g), o.getState().setCreatedState(g);
49
- const T = (v, i) => {
50
- const [$] = dt(i?.componentId ?? kt());
51
- Nt({
52
- stateKey: v,
53
- options: i,
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], n = i?.modifyState ? i.modifyState(y) : y, [w, O] = Xt(
57
- n,
58
- {
59
- stateKey: v,
60
- syncUpdate: i?.syncUpdate,
61
- componentId: $,
62
- localStorage: i?.localStorage,
63
- middleware: i?.middleware,
64
- enabledSync: i?.enabledSync,
65
- reactiveType: i?.reactiveType,
66
- reactiveDeps: i?.reactiveDeps,
67
- initialState: i?.initialState,
68
- dependencies: i?.dependencies,
69
- serverState: i?.serverState
70
- }
71
- );
72
- return O;
73
80
  };
74
- function A(v, i) {
75
- Nt({ stateKey: v, options: i, initialOptionsPart: I }), i.localStorage && Yt(v, i), ot(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: T, setCogsOptions: A };
84
+ return { useCogsState: h, setCogsOptions: V };
78
85
  }, {
79
- setUpdaterState: mt,
80
- setState: st,
81
- getInitialOptions: lt,
82
- getKeyState: Ot,
83
- getValidationErrors: qt,
84
- setStateLog: Jt,
85
- updateInitialStateGlobal: xt,
86
- addValidationError: Tt,
87
- removeValidationError: tt,
88
- setServerSyncActions: Zt
89
- } = o.getState(), Ct = (t, s, 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
95
  s,
93
- S.localStorage?.key,
96
+ p.localStorage?.key,
94
97
  g
95
98
  );
96
- const T = et(S?.localStorage?.key) ? S.localStorage?.key(t) : S?.localStorage?.key;
97
- if (T && g) {
98
- const A = `${g}-${s}-${T}`;
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 = yt(A)?.lastSyncedWithServer;
104
+ u = fe(V)?.lastSyncedWithServer;
102
105
  } catch {
103
106
  }
104
- const i = {
105
- state: t,
107
+ const l = t.getState().getShadowMetadata(s, []), E = {
108
+ state: e,
106
109
  lastUpdated: Date.now(),
107
- lastSyncedWithServer: I ?? v
108
- }, $ = zt.serialize(i);
110
+ lastSyncedWithServer: u,
111
+ stateSource: l?.stateSource,
112
+ baseServerState: l?.baseServerState
113
+ }, T = De.serialize(E);
109
114
  window.localStorage.setItem(
110
- A,
111
- JSON.stringify($.json)
115
+ V,
116
+ JSON.stringify(T.json)
112
117
  );
113
118
  }
114
- }, yt = (t) => {
115
- if (!t) return null;
119
+ }, fe = (e) => {
120
+ if (!e) return null;
116
121
  try {
117
- const s = window.localStorage.getItem(t);
122
+ const s = window.localStorage.getItem(e);
118
123
  return s ? JSON.parse(s) : null;
119
124
  } catch (s) {
120
125
  return console.error("Error loading from localStorage:", s), null;
121
126
  }
122
- }, Yt = (t, s) => {
123
- const S = o.getState().cogsStateStore[t], { sessionId: g } = Rt(), I = et(s?.localStorage?.key) ? s.localStorage.key(S) : s?.localStorage?.key;
124
- if (I && g) {
125
- const T = yt(
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 (T && T.lastUpdated > (T.lastSyncedWithServer || 0))
129
- return st(t, T.state), ot(t), !0;
133
+ if (h && h.lastUpdated > (h.lastSyncedWithServer || 0))
134
+ return re(e), !0;
130
135
  }
131
136
  return !1;
132
- }, jt = (t, s, S, g, I, T) => {
133
- const A = {
134
- initialState: s,
135
- updaterState: It(
136
- t,
137
- g,
138
- I,
139
- T
140
- ),
141
- state: S
142
- };
143
- xt(t, A.initialState), mt(t, A.updaterState), st(t, A.state);
144
- }, ot = (t) => {
145
- const s = o.getState().stateComponents.get(t);
137
+ }, re = (e) => {
138
+ const s = t.getState().getShadowMetadata(e, []);
146
139
  if (!s) return;
147
- const S = /* @__PURE__ */ new Set();
148
- s.components.forEach((g) => {
149
- (g ? Array.isArray(g.reactiveType) ? g.reactiveType : [g.reactiveType || "component"] : null)?.includes("none") || S.add(() => g.forceUpdate());
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, s) => {
154
- const S = o.getState().stateComponents.get(t);
155
- if (S) {
156
- const g = `${t}////${s}`, 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, s, S, g) => {
162
- switch (t) {
163
- case "update":
164
- return {
165
- oldValue: L(s, g),
166
- newValue: L(S, g)
167
- };
168
- case "insert":
169
- return {
170
- oldValue: null,
171
- // or undefined
172
- newValue: L(S, g)
173
- };
174
- case "cut":
175
- return {
176
- oldValue: L(s, 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, {
155
+ function Be(e, {
185
156
  stateKey: s,
186
- serverSync: S,
157
+ serverSync: p,
187
158
  localStorage: g,
188
- formElements: I,
189
- reactiveDeps: T,
190
- reactiveType: A,
191
- componentId: v,
192
- initialState: i,
193
- syncUpdate: $,
194
- dependencies: y,
195
- serverState: n
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 [w, O] = dt({}), { sessionId: p } = Rt();
198
- let K = !s;
199
- const [f] = dt(s ?? kt()), z = o.getState().stateLog[f], c = q(/* @__PURE__ */ new Set()), nt = q(v ?? kt()), R = q(
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
- R.current = lt(f) ?? null, at(() => {
203
- if ($ && $.stateKey === f && $.path?.[0]) {
204
- st(f, (e) => ({
205
- ...e,
206
- [$.path[0]]: $.newValue
207
- }));
208
- const r = `${$.stateKey}:${$.path.join(".")}`;
209
- o.getState().setSyncInfo(r, {
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
- }, [$]), at(() => {
215
- if (i) {
216
- Mt(f, {
217
- initialState: i
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 r = R.current, a = r?.serverState?.id !== void 0 && r?.serverState?.status === "success" && r?.serverState?.data, d = o.getState().initialStateGlobal[f];
220
- if (!(d && !X(d, i) || !d) && !a)
221
- return;
222
- let l = null;
223
- const m = et(r?.localStorage?.key) ? r?.localStorage?.key(i) : r?.localStorage?.key;
224
- m && p && (l = yt(`${p}-${f}-${m}`));
225
- let x = i, b = !1;
226
- const F = a ? Date.now() : 0, W = l?.lastUpdated || 0, D = l?.lastSyncedWithServer || 0;
227
- a && F > W ? (x = r.serverState.data, b = !0) : l && W > D && (x = l.state, r?.localStorage?.onChange && r?.localStorage?.onChange(x)), o.getState().initializeShadowState(f, i), jt(
228
- f,
229
- i,
230
- x,
231
- it,
232
- nt.current,
233
- p
234
- ), b && m && p && Ct(x, f, r, p, Date.now()), ot(f), (Array.isArray(A) ? A : [A || "component"]).includes("none") || O({});
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
- i,
238
- n?.status,
239
- n?.data,
240
- ...y || []
241
- ]), pt(() => {
242
- K && Mt(f, {
243
- serverSync: S,
244
- formElements: I,
245
- initialState: i,
257
+ }, [c, ...T || []]), ue(() => {
258
+ N && me(c, {
259
+ serverSync: p,
260
+ formElements: v,
261
+ defaultState: l,
246
262
  localStorage: g,
247
- middleware: R.current?.middleware
263
+ middleware: f.current?.middleware
248
264
  });
249
- const r = `${f}////${nt.current}`, e = o.getState().stateComponents.get(f) || {
250
- components: /* @__PURE__ */ new Map()
251
- };
252
- return e.components.set(r, {
253
- forceUpdate: () => O({}),
265
+ const a = `${c}////${H.current}`, n = t.getState().getShadowMetadata(c, []), r = n?.components || /* @__PURE__ */ new Map();
266
+ return r.set(a, {
267
+ forceUpdate: () => M({}),
268
+ reactiveType: V ?? ["component", "deps"],
254
269
  paths: /* @__PURE__ */ new Set(),
255
- deps: [],
256
- depsFunction: T || void 0,
257
- reactiveType: A ?? ["component", "deps"]
258
- }), o.getState().stateComponents.set(f, e), O({}), () => {
259
- e && (e.components.delete(r), 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 it = (r, e, a, d) => {
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);
289
+ }
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
+ }
266
313
  }
267
- const u = o.getState();
268
- st(f, (l) => {
269
- const m = et(r) ? r(l) : r, x = `${f}-${e.join(".")}`;
270
- if (x) {
271
- let P = !1, h = u.signalDomElements.get(x);
272
- if ((!h || h.size === 0) && (a.updateType === "insert" || a.updateType === "cut")) {
273
- const C = e.slice(0, -1), V = L(m, C);
274
- if (Array.isArray(V)) {
275
- P = !0;
276
- const E = `${f}-${C.join(".")}`;
277
- h = u.signalDomElements.get(E);
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 (h) {
281
- const C = P ? L(m, e.slice(0, -1)) : L(m, e);
282
- h.forEach(({ parentId: V, position: E, effect: M }) => {
283
- const Z = document.querySelector(
284
- `[data-parent-id="${V}"]`
285
- );
286
- if (Z) {
287
- const G = Array.from(Z.childNodes);
288
- if (G[E]) {
289
- const U = M ? new Function("state", `return (${M})(state)`)(C) : C;
290
- G[E].textContent = String(U);
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" && (d || R.current?.validation?.key) && e && tt(
297
- (d || R.current?.validation?.key) + "." + e.join(".")
298
- );
299
- const b = e.slice(0, e.length - 1);
300
- a.updateType === "cut" && R.current?.validation?.key && tt(
301
- R.current?.validation?.key + "." + b.join(".")
302
- ), a.updateType === "insert" && R.current?.validation?.key && qt(
303
- R.current?.validation?.key + "." + b.join(".")
304
- ).filter((h) => {
305
- let C = h?.split(".").length;
306
- const V = "";
307
- if (h == b.join(".") && C == b.length - 1) {
308
- let E = h + "." + b;
309
- tt(h), Tt(E, V);
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 F = u.stateComponents.get(f);
313
- if (F) {
314
- const P = Pt(l, m), h = new Set(P), C = a.updateType === "update" ? e.join(".") : e.slice(0, -1).join(".") || "";
315
- for (const [
316
- V,
317
- E
318
- ] of F.components.entries()) {
319
- let M = !1;
320
- const Z = Array.isArray(E.reactiveType) ? E.reactiveType : [E.reactiveType || "component"];
321
- if (!Z.includes("none")) {
322
- if (Z.includes("all")) {
323
- E.forceUpdate();
324
- continue;
325
- }
326
- if (Z.includes("component") && ((E.paths.has(C) || E.paths.has("")) && (M = !0), !M))
327
- for (const G of h) {
328
- let U = G;
329
- for (; ; ) {
330
- if (E.paths.has(U)) {
331
- M = !0;
332
- break;
333
- }
334
- const k = U.lastIndexOf(".");
335
- if (k !== -1) {
336
- const N = U.substring(
337
- 0,
338
- k
339
- );
340
- if (!isNaN(
341
- Number(U.substring(k + 1))
342
- ) && E.paths.has(N)) {
343
- M = !0;
344
- break;
345
- }
346
- U = N;
347
- } else
348
- U = "";
349
- if (U === "")
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 (M) break;
353
- }
354
- if (!M && Z.includes("deps") && E.depsFunction) {
355
- const G = E.depsFunction(m);
356
- let U = !1;
357
- typeof G == "boolean" ? G && (U = !0) : X(E.deps, G) || (E.deps = G, U = !0), U && (M = !0);
464
+ D != null && typeof D == "object" && (D = JSON.stringify(D)), j[w].textContent = String(D ?? "");
358
465
  }
359
- M && E.forceUpdate();
360
466
  }
361
- }
467
+ });
362
468
  }
363
- const W = Date.now();
364
- let { oldValue: D, newValue: B } = Qt(
365
- a.updateType,
366
- l,
367
- m,
368
- e
369
- );
370
- const ct = {
371
- timeStamp: W,
372
- stateKey: f,
373
- path: e,
374
- updateType: a.updateType,
375
- status: "new",
376
- oldValue: D,
377
- newValue: B
378
- };
379
- switch (a.updateType) {
380
- case "insert": {
381
- const P = e.slice(0, -1), C = e[e.length - 1].split(":")[1];
382
- B = L(m, P).find((E) => E.id == C), D = null, u.insertShadowArrayElement(f, P, B);
383
- break;
384
- }
385
- case "cut": {
386
- D = L(l, e), B = null, u.removeShadowArrayElement(f, e);
387
- break;
388
- }
389
- case "update": {
390
- D = L(l, e), B = L(m, e);
391
- const P = e.map((h, C) => {
392
- const V = e.slice(0, C + 1), E = L(m, V);
393
- return E?.id ? `id:${E.id}` : h;
394
- });
395
- u.updateShadowAtPath(f, P, B);
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, (P) => {
400
- const h = [...P ?? [], ct], C = /* @__PURE__ */ new Map();
401
- return h.forEach((V) => {
402
- const E = `${V.stateKey}:${JSON.stringify(V.path)}`, M = C.get(E);
403
- M ? (M.timeStamp = Math.max(M.timeStamp, V.timeStamp), M.newValue = V.newValue, M.oldValue = M.oldValue ?? V.oldValue, M.updateType = V.updateType) : C.set(E, { ...V });
404
- }), Array.from(C.values());
405
- }), Ct(
406
- m,
407
- f,
408
- R.current,
409
- p
410
- ), R.current?.middleware && R.current.middleware({
411
- updateLog: z,
412
- update: ct
413
- }), R.current?.serverSync) {
414
- const P = u.serverState[f], h = R.current?.serverSync;
415
- Zt(f, {
416
- syncKey: typeof h.syncKey == "string" ? h.syncKey : h.syncKey({ state: m }),
417
- rollBackState: P,
418
- actionTimeStamp: Date.now() + (h.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] || (mt(
426
- f,
427
- It(
428
- f,
429
- it,
430
- nt.current,
431
- p
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] || st(f, t), o.getState().initialStateGlobal[f] || xt(f, t));
434
- const vt = Et(() => It(
435
- f,
436
- it,
437
- nt.current,
438
- p
439
- ), [f, p]);
440
- return [Ot(f), vt];
518
+ ).join("");
441
519
  }
442
- function It(t, s, S, g) {
443
- const I = /* @__PURE__ */ new Map();
444
- let T = 0;
445
- const A = (y) => {
446
- const n = y.join(".");
447
- for (const [w] of I)
448
- (w === n || w.startsWith(n + ".")) && I.delete(w);
449
- T++;
450
- }, v = {
451
- removeValidation: (y) => {
452
- y?.validationKey && tt(y.validationKey);
453
- },
454
- revertToInitialState: (y) => {
455
- const n = o.getState().getInitialOptions(t)?.validation;
456
- n?.key && tt(n?.key), y?.validationKey && tt(y.validationKey);
457
- const w = o.getState().initialStateGlobal[t];
458
- o.getState().initializeShadowState(t, w), o.getState().clearSelectedIndexesForState(t), I.clear(), T++;
459
- const O = $(w, []), p = lt(t), K = et(p?.localStorage?.key) ? p?.localStorage?.key(w) : p?.localStorage?.key, f = `${g}-${t}-${K}`;
460
- f && localStorage.removeItem(f), mt(t, O), st(t, w);
461
- const z = o.getState().stateComponents.get(t);
462
- return z && z.components.forEach((c) => {
463
- c.forceUpdate();
464
- }), w;
465
- },
466
- updateInitialState: (y) => {
467
- I.clear(), T++;
468
- const n = It(
469
- t,
470
- s,
471
- S,
472
- g
473
- ), w = o.getState().initialStateGlobal[t], O = lt(t), p = et(O?.localStorage?.key) ? O?.localStorage?.key(w) : O?.localStorage?.key, K = `${g}-${t}-${p}`;
474
- return localStorage.getItem(K) && localStorage.removeItem(K), Ut(() => {
475
- xt(t, y), o.getState().initializeShadowState(t, y), mt(t, n), st(t, y);
476
- const f = o.getState().stateComponents.get(t);
477
- f && f.components.forEach((z) => {
478
- z.forceUpdate();
479
- });
480
- }), {
481
- fetchId: (f) => n.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 && X(y, Ot(t)));
490
- }
491
- };
492
- function i(y) {
493
- const n = [t, ...y].join(".");
494
- return o.getState().shadowStateStore.get(n)?.arrayKeys || null;
495
- }
496
- function $(y, n = [], w) {
497
- const O = n.map(String).join(".");
498
- I.get(O);
499
- const p = function() {
500
- return o().getNestedState(t, n);
501
- };
502
- Object.keys(v).forEach((z) => {
503
- p[z] = v[z];
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 K = {
506
- apply(z, c, nt) {
507
- return o().getNestedState(t, n);
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(z, c) {
510
- const nt = /* @__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" && !nt.has(c)) {
534
- const r = `${t}////${S}`, e = o.getState().stateComponents.get(t);
535
- if (e) {
536
- const a = e.components.get(r);
537
- if (a && !a.paths.has("")) {
538
- const d = n.join(".");
539
- let u = !0;
540
- for (const l of a.paths)
541
- if (d.startsWith(l) && (d === l || d[l.length] === ".")) {
542
- u = !1;
543
- break;
544
- }
545
- u && a.paths.add(d);
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" && n.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 r = o.getState().getInitialOptions(t), e = r?.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, []), d = r?.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 u = await e.action(a);
562
- return u && !u.success && u.errors && d && (o.getState().removeValidationError(d), u.errors.forEach((l) => {
563
- const m = [d, ...l.path].join(".");
564
- o.getState().addValidationError(m, l.message);
565
- }), ot(t)), u?.success && e.onSuccess ? e.onSuccess(u.data) : !u?.success && e.onError && e.onError(u.error), u;
566
- } catch (u) {
567
- return e.onError && e.onError(u), { success: !1, error: u };
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 r = o.getState().getNestedState(t, n), e = o.getState().initialStateGlobal[t], a = L(e, n);
572
- return X(r, a) ? "fresh" : "stale";
573
- }
574
- if (c === "getStatus")
575
- return function() {
576
- const r = o().getNestedState(
577
- t,
578
- n
579
- ), e = o.getState().initialStateGlobal[t], a = L(e, n);
580
- return X(r, 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 r = o.getState().initialStateGlobal[t], e = lt(t), a = et(e?.localStorage?.key) ? e.localStorage.key(r) : e?.localStorage?.key, d = `${g}-${t}-${a}`;
585
- d && localStorage.removeItem(d);
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 r = o.getState().getInitialOptions(t)?.validation;
590
- if (!r?.key) throw new Error("Validation key not found");
591
- return o.getState().getValidationErrors(r.key + "." + n.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 r = o.getState().getSelectedIndex(t, n.join("."));
597
- if (r === void 0) return;
598
- const e = o.getState().getNestedState(t, n);
599
- if (!e || r >= 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[r], d = `id:${a.id}`;
602
- return $(a, [...n, d], w);
603
- };
604
- if (c === "clearSelected")
605
- return () => {
606
- o.getState().clearSelectedIndex({ stateKey: t, path: n });
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 r = o.getState().getSelectedIndex(t, n.join("."));
611
- if (r === void 0) return -1;
612
- if (w?.validIds) {
613
- const a = (i(n) || [])[r];
614
- return a ? w.validIds.indexOf(a) : -1;
615
- }
616
- return r;
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 (r) => {
673
+ if (f === "useVirtualView")
674
+ return (a) => {
620
675
  const {
621
- itemHeight: e = 50,
622
- overscan: a = 6,
623
- stickToBottom: d = !1,
624
- dependencies: u = []
625
- } = r, l = q(null), [m, x] = dt({
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
- }), [b, F] = dt(0), W = q(!0), D = q(!1), B = q(0), ct = q(m);
629
- i(n), at(() => o.getState().subscribeToShadowState(t, () => {
630
- F((N) => N + 1);
631
- }), [t]);
632
- const P = o().getNestedState(
633
- t,
634
- n
635
- ), h = P.length, { totalHeight: C, positions: V } = Et(() => {
636
- const N = o.getState().getShadowMetadata(t, n)?.arrayKeys || [];
637
- let _ = 0;
638
- const H = [];
639
- for (let j = 0; j < h; j++) {
640
- H[j] = _;
641
- const Y = N[j];
642
- let J = e;
643
- Y && (J = o.getState().getShadowMetadata(t, [...n, Y])?.virtualizer?.itemHeight || e), _ += J;
644
- }
645
- return { totalHeight: _, positions: H };
646
- }, [
647
- h,
648
- t,
649
- n.join("."),
650
- e,
651
- b
652
- ]), E = Et(() => {
653
- const k = Math.max(0, m.startIndex), N = Math.min(h, m.endIndex), H = o.getState().getShadowMetadata(t, n)?.arrayKeys || [], j = P.slice(k, N), Y = H.slice(k, N);
654
- return $(j, n, {
655
- ...w,
656
- validIds: Y
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"
657
698
  });
658
- }, [m.startIndex, m.endIndex, P, h]), M = St(() => {
659
- const k = o.getState().getShadowMetadata(t, n);
660
- if (!k || k && k?.arrayKeys?.length === 0)
661
- return !1;
662
- const N = h - 1, _ = [...n, k.arrayKeys[N]];
663
- if (N >= 0) {
664
- const H = o.getState().getShadowMetadata(t, _);
665
- if (H?.virtualizer?.domRef) {
666
- const j = H.virtualizer.domRef;
667
- if (j && j.scrollIntoView)
668
- return j.scrollIntoView({
669
- behavior: "auto",
670
- block: "end",
671
- inline: "nearest"
672
- }), !0;
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;
673
741
  }
674
742
  }
675
- return !1;
676
- }, [t, n, h]);
677
- at(() => {
678
- if (!d || h === 0) return;
679
- const k = h > B.current, N = B.current === 0 && h > 0;
680
- if ((k || N) && W.current && !D.current) {
681
- const _ = Math.ceil(
682
- (l.current?.clientHeight || 0) / e
683
- ), H = {
684
- startIndex: Math.max(
685
- 0,
686
- h - _ - a
687
- ),
688
- endIndex: h
689
- };
690
- x(H);
691
- const j = setTimeout(() => {
692
- G(h - 1, "smooth");
693
- }, 50);
694
- return () => clearTimeout(j);
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
+ });
695
752
  }
696
- B.current = h;
697
- }, [h, e, a]), at(() => {
698
- const k = l.current;
699
- if (!k) return;
700
- const N = () => {
701
- const { scrollTop: _, scrollHeight: H, clientHeight: j } = k, Y = H - _ - j;
702
- W.current = Y < 5, Y > 100 && (D.current = !0), Y < 5 && (D.current = !1);
703
- let J = 0;
704
- for (let Q = 0; Q < V.length; Q++)
705
- if (V[Q] > _ - e * a) {
706
- J = Math.max(0, Q - 1);
707
- break;
708
- }
709
- let rt = J;
710
- const Vt = _ + j;
711
- for (let Q = J; Q < V.length && !(V[Q] > Vt + e * a); Q++)
712
- rt = Q;
713
- const ht = Math.max(0, J), wt = Math.min(
714
- h,
715
- rt + 1 + a
716
- );
717
- (ht !== ct.current.startIndex || wt !== ct.current.endIndex) && (ct.current = {
718
- startIndex: ht,
719
- endIndex: wt
720
- }, x({
721
- startIndex: ht,
722
- endIndex: wt
723
- }));
753
+ }, [
754
+ O.length,
755
+ I.startIndex,
756
+ n,
757
+ r,
758
+ m
759
+ ]);
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 && $();
724
816
  };
725
- if (k.addEventListener("scroll", N, {
726
- passive: !0
727
- }), d && h > 0 && !D.current) {
728
- const { scrollTop: _ } = k;
729
- _ === 0 && (k.scrollTop = k.scrollHeight, W.current = !0);
730
- }
731
- return N(), () => {
732
- k.removeEventListener("scroll", N);
817
+ return y.addEventListener("load", D, !0), _.current ? setTimeout(() => {
818
+ A("instant");
819
+ }, 0) : $(), () => {
820
+ clearTimeout(C), j.disconnect(), y.removeEventListener("load", D, !0);
733
821
  };
734
- }, [V, h, e, a, d]);
735
- const Z = St(() => {
736
- W.current = !0, D.current = !1, !M() && l.current && (l.current.scrollTop = l.current.scrollHeight);
737
- }, [M]), G = St(
738
- (k, N = "smooth") => {
739
- const _ = l.current;
740
- if (!_) return;
741
- if (k === h - 1) {
742
- _.scrollTo({
743
- top: _.scrollHeight,
744
- behavior: N
745
- });
746
- return;
747
- }
748
- const J = (o.getState().getShadowMetadata(t, n)?.arrayKeys || [])[k];
749
- let rt;
750
- J && (rt = o.getState().getShadowMetadata(t, [...n, J])?.virtualizer?.domRef), rt ? rt.scrollIntoView({
751
- behavior: N,
752
- block: "center"
753
- }) : V[k] !== void 0 && _.scrollTo({
754
- top: V[k],
755
- behavior: N
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 }
756
838
  });
757
- },
758
- [V, t, n, h]
759
- // Add totalCount to the dependencies
760
- ), U = {
761
- outer: {
762
- ref: l,
763
- style: { overflowY: "auto", height: "100%" }
764
- },
765
- inner: {
766
- style: {
767
- height: `${C}px`,
768
- position: "relative"
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)`
860
+ }
769
861
  }
770
862
  },
771
- list: {
772
- style: {
773
- transform: `translateY(${V[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 });
774
868
  }
775
869
  }
776
870
  };
777
- return {
778
- virtualState: E,
779
- virtualizerProps: U,
780
- scrollToBottom: Z,
781
- scrollToIndex: G
782
- };
783
871
  };
784
- if (c === "stateMap")
785
- return (r) => {
786
- const e = y, a = w?.validIds || i(n) || [], d = $(y, n, w);
787
- return e.map((u, l) => {
788
- const m = a[l] || `id:${u.id}`, x = [...n, m], b = $(u, x, w);
789
- return r(
790
- u,
791
- b,
792
- l,
793
- y,
794
- d
795
- );
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
796
884
  });
797
- };
798
- if (c === "stateMapNoRender")
799
- return (r) => {
800
- const e = y, a = w?.validIds || i(n) || [], d = $(y, n, w);
801
- return e.map((u, l) => {
802
- const m = a[l] || `id:${u.id}`, x = [...n, m], b = $(u, x, w);
803
- return r(
804
- u,
805
- b,
806
- l,
807
- y,
808
- d
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
809
896
  );
810
897
  });
811
898
  };
812
- if (c === "$stateMap")
813
- return (r) => gt(Kt, {
814
- proxy: { _stateKey: t, _path: n, _mapFn: r },
815
- 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
816
908
  });
817
- if (c === "stateList")
818
- return (r) => {
819
- const e = y;
820
- if (!Array.isArray(e)) return null;
821
- const a = w?.validIds || i(n) || [], d = i(n) || [], u = $(
822
- e,
823
- n,
824
- w
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
825
916
  );
826
- return e.map((l, m) => {
827
- const x = a[m] || `id:${l.id}`, b = d.indexOf(x), F = [...n, x], W = $(l, F, w), D = `${S}-${n.join(".")}-${x}`;
828
- return gt(ee, {
829
- key: x,
830
- stateKey: t,
831
- itemComponentId: D,
832
- itemPath: F,
833
- children: r(
834
- l,
835
- W,
836
- { localIndex: m, originalIndex: b },
837
- e,
838
- u
839
- )
840
- });
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
+ }
841
931
  });
842
932
  };
843
- if (c === "stateFlattenOn")
844
- return (r) => {
845
- const e = y;
846
- I.clear(), T++;
847
- const a = e.flatMap(
848
- (d) => d[r] ?? []
849
- );
850
- return $(
851
- a,
852
- [...n, "[*]", r],
853
- w
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] ?? []
854
1082
  );
1083
+ return u({
1084
+ currentState: r,
1085
+ path: [...o, "[*]", a],
1086
+ componentId: M,
1087
+ meta: S
1088
+ });
855
1089
  };
856
- if (c === "index")
857
- return (r) => {
858
- const a = (w?.validIds || i(n))?.[r];
859
- if (!a)
860
- return $(void 0, [
861
- ...n,
862
- r.toString()
863
- ]);
864
- const u = o.getState().getNestedState(t, n).find(
865
- (m) => `id:${m.id}` === a
866
- ), l = [...n, a];
867
- return $(u, l, w);
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
+ });
868
1103
  };
869
- if (c === "last")
1104
+ if (f === "last")
870
1105
  return () => {
871
- const r = o.getState().getNestedState(t, n);
872
- if (r.length === 0) return;
873
- const e = r.length - 1, a = r[e], d = [...n, e.toString()];
874
- return $(a, d);
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
+ });
875
1115
  };
876
- if (c === "insert")
877
- return (r) => (A(n), At(s, r, n, t), $(
878
- o.getState().getNestedState(t, n),
879
- n
880
- ));
881
- if (c === "uniqueInsert")
882
- return (r, e, a) => {
883
- const d = o.getState().getNestedState(t, n), u = et(r) ? r(d) : r;
884
- let l = null;
885
- if (!d.some((x) => {
886
- const b = e ? e.every(
887
- (F) => X(x[F], u[F])
888
- ) : X(x, u);
889
- return b && (l = x), b;
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;
890
1132
  }))
891
- A(n), At(s, u, n, t);
892
- else if (a && l) {
893
- const x = a(l), b = d.map(
894
- (F) => X(F, l) ? x : F
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
895
1137
  );
896
- A(n), ut(s, b, n);
1138
+ V(o), s(U, o, {
1139
+ updateType: "update"
1140
+ });
897
1141
  }
898
1142
  };
899
- if (c === "cut")
900
- return (r, e) => {
901
- if (!e?.waitForSync)
902
- return A(n), ft(s, n, t, r), $(
903
- o.getState().getNestedState(t, n),
904
- n
905
- );
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
+ });
906
1153
  };
907
- if (c === "cutByValue")
908
- return (r) => {
909
- const e = y.findIndex((a) => a === r);
910
- e > -1 && ft(s, n, 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
+ });
911
1172
  };
912
- if (c === "toggleByValue")
913
- return (r) => {
914
- const e = y.findIndex((a) => a === r);
915
- e > -1 ? ft(s, n, t, e) : At(s, r, n, 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
+ }
916
1187
  };
917
- if (c === "stateFilter")
918
- return (r) => {
919
- const e = w?.validIds || i(n) || [], a = o.getState().getNestedState(t, n), d = new Map(
920
- a.map((m) => [`id:${m.id}`, m])
921
- ), u = [], l = [];
922
- return e.forEach((m, x) => {
923
- const b = d.get(m);
924
- b && r(b, x) && (u.push(m), l.push(b));
925
- }), $(l, n, {
926
- validIds: u
927
- });
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" });
928
1207
  };
929
- if (c === "stateSort")
930
- return (r) => {
931
- const a = y.map((l) => ({
932
- item: l,
933
- id: `id:${l.id}`
934
- }));
935
- a.sort((l, m) => r(l.item, m.item));
936
- const d = a.map((l) => l.item), u = a.map((l) => l.id);
937
- return $(d, n, {
938
- validIds: u
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
939
1226
  });
940
1227
  };
941
- if (c === "findWith")
942
- return (r, e) => {
943
- const a = y.find(
944
- (l) => l[r] === e
945
- );
946
- if (!a) return;
947
- const d = `id:${a.id}`, u = [...n, d];
948
- return $(a, u, w);
949
- };
950
- }
951
- const R = n[n.length - 1];
952
- if (!isNaN(Number(R))) {
953
- const r = n.slice(0, -1), e = o.getState().getNestedState(t, r);
954
- if (Array.isArray(e) && c === "cut")
955
- return () => ft(
956
- s,
957
- r,
958
- t,
959
- Number(R)
960
- );
961
1228
  }
962
- if (c === "get")
1229
+ if (f === "cut") {
1230
+ let a = t.getState().getShadowValue(o.join("."));
963
1231
  return () => {
964
- if (w?.validIds && Array.isArray(y)) {
965
- const r = o.getState().getNestedState(t, n);
966
- if (!Array.isArray(r)) return [];
967
- const e = new Map(
968
- r.map((a) => [`id:${a.id}`, a])
969
- );
970
- return w.validIds.map((a) => e.get(a)).filter(Boolean);
971
- }
972
- return o.getState().getNestedState(t, n);
1232
+ s(a, o, { updateType: "cut" });
973
1233
  };
974
- if (c === "$derive")
975
- return (r) => _t({
976
- _stateKey: t,
977
- _path: n,
978
- _effect: r.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
979
1243
  });
980
- if (c === "$get")
981
- return () => _t({ _stateKey: t, _path: n });
982
- if (c === "lastSynced") {
983
- const r = `${t}:${n.join(".")}`;
984
- return o.getState().getSyncInfo(r);
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);
985
1249
  }
986
- if (c == "getLocalStorage")
987
- return (r) => yt(g + "-" + t + "-" + r);
988
- if (c === "_selected") {
989
- const r = n.slice(0, -1), e = r.join(".");
990
- if (Array.isArray(
991
- o.getState().getNestedState(t, r)
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)
992
1256
  )) {
993
- const a = n[n.length - 1];
994
- return i(r)?.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;
995
1260
  }
996
1261
  return;
997
1262
  }
998
- if (c === "setSelected")
999
- return (r) => {
1000
- const e = n.slice(0, -1), a = n[n.length - 1], u = i(e)?.indexOf(a);
1001
- if (u === void 0 || u === -1) return;
1002
- const l = e.join(".");
1003
- o.getState().setSelectedIndex(
1004
- t,
1005
- l,
1006
- r ? u : void 0
1007
- );
1008
- const m = o.getState().getNestedState(t, [...e]);
1009
- ut(s, m, e), A(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);
1010
1267
  };
1011
- if (c === "toggleSelected")
1268
+ if (f === "toggleSelected")
1012
1269
  return () => {
1013
- const r = n.slice(0, -1), e = n[n.length - 1], d = i(r)?.indexOf(e);
1014
- if (d === void 0 || d === -1) return;
1015
- const u = r.join("."), l = o.getState().getSelectedIndex(t, u);
1016
- o.getState().setSelectedIndex(
1017
- t,
1018
- u,
1019
- l === d ? void 0 : d
1020
- );
1021
- const m = o.getState().getNestedState(t, [...r]);
1022
- ut(s, m, r), A(r);
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);
1023
1272
  };
1024
- if (n.length == 0) {
1025
- if (c === "addValidation")
1026
- return (r) => {
1027
- const e = o.getState().getInitialOptions(t)?.validation;
1028
- if (!e?.key) throw new Error("Validation key not found");
1029
- tt(e.key), r.forEach((a) => {
1030
- const d = [e.key, ...a.path].join(".");
1031
- Tt(d, a.message);
1032
- }), ot(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);
1033
1284
  };
1034
- if (c === "applyJsonPatch")
1035
- return (r) => {
1036
- const e = o.getState().cogsStateStore[t], a = Wt(e, r).newDocument;
1037
- jt(
1038
- t,
1039
- o.getState().initialStateGlobal[t],
1040
- a,
1041
- s,
1042
- S,
1043
- g
1044
- ), ot(t);
1285
+ if (f === "applyJsonPatch")
1286
+ return (a) => {
1287
+ const n = t.getState().getShadowValue(N, S?.validIds);
1288
+ Le(n, a).newDocument, re(e);
1045
1289
  };
1046
- if (c === "validateZodSchema")
1290
+ if (f === "validateZodSchema")
1047
1291
  return () => {
1048
- const r = o.getState().getInitialOptions(t)?.validation;
1049
- if (!r?.zodSchema || !r?.key)
1292
+ const a = t.getState().getInitialOptions(e)?.validation;
1293
+ if (!a?.zodSchema || !a?.key)
1050
1294
  throw new Error("Zod schema or validation key not found");
1051
- tt(r.key);
1052
- const e = o.getState().cogsStateStore[t], a = r.zodSchema.safeParse(e);
1053
- return a.success ? !0 : (a.error.errors.forEach((d) => {
1054
- const u = [r.key, ...d.path].join(".");
1055
- Tt(u, d.message);
1056
- }), ot(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);
1057
1301
  };
1058
- if (c === "_componentId") return S;
1059
- if (c === "getComponents")
1060
- return () => o().stateComponents.get(t);
1061
- if (c === "getAllFormRefs")
1062
- return () => bt.getState().getFormRefsByStateKey(t);
1063
- if (c === "_initialState")
1064
- return o.getState().initialStateGlobal[t];
1065
- if (c === "_serverState")
1066
- return o.getState().serverState[t];
1067
- if (c === "_isLoading")
1068
- return o.getState().isLoadingGlobal[t];
1069
- if (c === "revertToInitialState")
1070
- return v.revertToInitialState;
1071
- if (c === "updateInitialState") return v.updateInitialState;
1072
- 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);
1073
1306
  }
1074
- if (c === "getFormRef")
1075
- return () => bt.getState().getFormRef(t + "." + n.join("."));
1076
- if (c === "validationWrapper")
1307
+ if (f === "getFormRef")
1308
+ return () => ye.getState().getFormRef(e + "." + o.join("."));
1309
+ if (f === "validationWrapper")
1077
1310
  return ({
1078
- children: r,
1079
- hideMessage: e
1080
- }) => /* @__PURE__ */ $t(
1081
- Gt,
1311
+ children: a,
1312
+ hideMessage: n
1313
+ }) => /* @__PURE__ */ ae(
1314
+ Me,
1082
1315
  {
1083
- formOpts: e ? { validation: { message: "" } } : void 0,
1084
- path: n,
1085
- stateKey: t,
1086
- children: r
1316
+ formOpts: n ? { validation: { message: "" } } : void 0,
1317
+ path: o,
1318
+ stateKey: e,
1319
+ children: a
1087
1320
  }
1088
1321
  );
1089
- if (c === "_stateKey") return t;
1090
- if (c === "_path") return n;
1091
- if (c === "_isServerSynced") return v._isServerSynced;
1092
- if (c === "update")
1093
- return (r, e) => {
1094
- if (e?.debounce)
1095
- Lt(() => {
1096
- ut(s, r, n, "");
1097
- const a = o.getState().getNestedState(t, n);
1098
- e?.afterUpdate && e.afterUpdate(a);
1099
- }, e.debounce);
1100
- else {
1101
- ut(s, r, n, "");
1102
- const a = o.getState().getNestedState(t, n);
1103
- e?.afterUpdate && e.afterUpdate(a);
1104
- }
1105
- A(n);
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" });
1106
1327
  };
1107
- if (c === "formElement")
1108
- return (r, e) => /* @__PURE__ */ $t(
1109
- Ht,
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,
1110
1341
  {
1111
- setState: s,
1112
- stateKey: t,
1113
- path: n,
1114
- child: r,
1115
- 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
+ )
1116
1356
  }
1117
1357
  );
1118
- const it = [...n, c], vt = o.getState().getNestedState(t, it);
1119
- return $(vt, it, w);
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
+ });
1120
1365
  }
1121
- }, f = new Proxy(p, K);
1122
- return I.set(O, {
1123
- proxy: f,
1124
- stateVersion: T
1125
- }), f;
1366
+ }, G = new Proxy(c, J);
1367
+ return v.set(L, {
1368
+ proxy: G,
1369
+ stateVersion: h
1370
+ }), G;
1126
1371
  }
1127
- return $(
1128
- o.getState().getNestedState(t, [])
1129
- );
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
+ });
1130
1418
  }
1131
- function _t(t) {
1132
- return gt(te, { proxy: t });
1419
+ function be(e) {
1420
+ return le(Ge, { proxy: e });
1133
1421
  }
1134
- function Kt({
1135
- proxy: t,
1422
+ function ze({
1423
+ proxy: e,
1136
1424
  rebuildStateShape: s
1137
1425
  }) {
1138
- const S = o().getNestedState(t._stateKey, t._path);
1139
- return Array.isArray(S) ? s(
1140
- S,
1141
- t._path
1142
- ).stateMapNoRender(
1143
- (I, T, A, v, i) => t._mapFn(I, T, A, v, i)
1144
- ) : 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 });
1145
1491
  }
1146
- function te({
1147
- proxy: t
1492
+ function Ge({
1493
+ proxy: e
1148
1494
  }) {
1149
- const s = q(null), S = `${t._stateKey}-${t._path.join(".")}`;
1150
- return at(() => {
1151
- const g = s.current;
1152
- if (!g || !g.parentElement) return;
1153
- const I = g.parentElement, A = Array.from(I.childNodes).indexOf(g);
1154
- let v = I.getAttribute("data-parent-id");
1155
- v || (v = `parent-${crypto.randomUUID()}`, I.setAttribute("data-parent-id", v));
1156
- const $ = {
1157
- instanceId: `instance-${crypto.randomUUID()}`,
1158
- parentId: v,
1159
- position: A,
1160
- effect: t._effect
1161
- };
1162
- o.getState().addSignalElement(S, $);
1163
- const y = o.getState().getNestedState(t._stateKey, t._path);
1164
- let n = y;
1165
- if (t._effect)
1166
- try {
1167
- n = new Function(
1168
- "state",
1169
- `return (${t._effect})(state)`
1170
- )(y);
1171
- } catch (O) {
1172
- console.error("Error evaluating effect function:", O);
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;
1173
1506
  }
1174
- n !== null && typeof n == "object" && (n = JSON.stringify(n));
1175
- const w = document.createTextNode(String(n));
1176
- g.replaceWith(w);
1177
- }, [t._stateKey, t._path.join("."), t._effect]), gt("span", {
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));
1540
+ }
1541
+ };
1542
+ }, []), le("span", {
1178
1543
  ref: s,
1179
- style: { display: "none" },
1180
- "data-signal-id": S
1544
+ style: { display: "contents" },
1545
+ "data-signal-id": v
1181
1546
  });
1182
1547
  }
1183
- function ye(t) {
1184
- const s = Ft(
1185
- (S) => {
1186
- const g = o.getState().stateComponents.get(t._stateKey) || { components: /* @__PURE__ */ new Map() };
1187
- return g.components.set(t._stateKey, {
1188
- forceUpdate: S,
1189
- paths: /* @__PURE__ */ new Set([t._path.join(".")])
1190
- }), 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);
1191
1590
  },
1192
- () => o.getState().getNestedState(t._stateKey, t._path)
1591
+ [l]
1193
1592
  );
1194
- return gt("text", {}, String(s));
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 });
1195
1627
  }
1196
- function ee({
1197
- stateKey: t,
1198
- itemComponentId: s,
1199
- itemPath: S,
1200
- children: g
1628
+ function Ze({
1629
+ stateKey: e,
1630
+ path: s,
1631
+ rebuildStateShape: p,
1632
+ renderFn: g,
1633
+ formOpts: v,
1634
+ setState: h
1201
1635
  }) {
1202
- const [, I] = dt({}), [T, A] = Bt(), v = q(null), i = q(null), $ = St(
1203
- (y) => {
1204
- T(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);
1205
1656
  },
1206
- [T]
1207
- );
1208
- return at(() => {
1209
- A.height > 0 && A.height !== i.current && (i.current = A.height, o.getState().setShadowMetadata(t, S, {
1210
- virtualizer: { itemHeight: A.height, domRef: v.current }
1211
- }));
1212
- }, [A.height, t, S]), pt(() => {
1213
- const y = `${t}////${s}`, n = o.getState().stateComponents.get(t) || { components: /* @__PURE__ */ new Map() };
1214
- return n.components.set(y, {
1215
- forceUpdate: () => I({}),
1216
- paths: /* @__PURE__ */ new Set([S.join(".")])
1217
- }), o.getState().stateComponents.set(t, n), () => {
1218
- const w = o.getState().stateComponents.get(t);
1219
- w && w.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);
1220
1692
  };
1221
- }, [t, s, S.join(".")]), /* @__PURE__ */ $t("div", { ref: $, children: g });
1693
+ }, [e, g]);
1222
1694
  }
1223
1695
  export {
1224
- _t as $cogsSignal,
1225
- ye as $cogsSignalStore,
1226
- Se as addStateOptions,
1227
- me as createCogsState,
1228
- Ie as notifyComponent,
1229
- Xt as useCogsStateFn
1696
+ be as $cogsSignal,
1697
+ lt as addStateOptions,
1698
+ ut as createCogsState,
1699
+ dt as notifyComponent,
1700
+ Be as useCogsStateFn
1230
1701
  };
1231
1702
  //# sourceMappingURL=CogsState.jsx.map