cogsbox-state 0.5.3 → 0.5.4

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,72 +1,72 @@
1
1
  "use client";
2
- import { j as X } from "./node_modules/react/jsx-runtime.jsx";
3
- import { r as _ } from "./node_modules/react/index.js";
4
- import { transformStateFunc as ct, isFunction as nt, getNestedValue as W, isDeepEqual as M } from "./utility.js";
5
- import { updateFn as Y, ValidationWrapper as lt, FormControlComponent as dt, pushFunc as Z, cutFunc as ut } from "./updaterFunctions.jsx";
2
+ import { j as Y } from "./node_modules/react/jsx-runtime.jsx";
3
+ import { r as w } from "./node_modules/react/index.js";
4
+ import { transformStateFunc as ut, isFunction as at, getNestedValue as R, isDeepEqual as L } from "./utility.js";
5
+ import { pushFunc as Z, cutFunc as K, updateFn as tt, ValidationWrapper as St, FormControlComponent as gt } from "./Functions.jsx";
6
6
  import "zod";
7
- import { getGlobalStore as n } from "./store.js";
8
- import { useCogsConfig as St } from "./CogsStateClient.jsx";
9
- import q from "./node_modules/uuid/dist/esm-browser/v4.js";
10
- function Ot(t, { formElements: i, zodSchema: S }) {
11
- return { initialState: t, formElements: i, zodSchema: S };
7
+ import { getGlobalStore as a } from "./store.js";
8
+ import { useCogsConfig as ft } from "./CogsStateClient.jsx";
9
+ import k from "./node_modules/uuid/dist/esm-browser/v4.js";
10
+ function Mt(t, { formElements: i, zodSchema: d }) {
11
+ return { initialState: t, formElements: i, zodSchema: d };
12
12
  }
13
- function K(t, i) {
14
- const S = n.getState().getInitialOptions, u = n.getState().setInitialStateOptions, g = S(t) || {};
13
+ function et(t, i) {
14
+ const d = a.getState().getInitialOptions, u = a.getState().setInitialStateOptions, S = d(t) || {};
15
15
  u(t, {
16
- ...g,
16
+ ...S,
17
17
  ...i
18
18
  });
19
19
  }
20
- function tt({
20
+ function nt({
21
21
  stateKey: t,
22
22
  options: i,
23
- initialOptionsPart: S
23
+ initialOptionsPart: d
24
24
  }) {
25
- const u = k(t) || {}, g = S[t] || {}, E = n.getState().setInitialStateOptions, f = { ...g, ...u };
26
- let m = !1;
25
+ const u = z(t) || {}, S = d[t] || {}, I = a.getState().setInitialStateOptions, _ = { ...S, ...u };
26
+ let E = !1;
27
27
  if (i)
28
- for (const w in i)
29
- f.hasOwnProperty(w) || (m = !0, f[w] = i[w]);
30
- m && E(t, f);
28
+ for (const y in i)
29
+ _.hasOwnProperty(y) || (E = !0, _[y] = i[y]);
30
+ E && I(t, _);
31
31
  }
32
- const ht = (t) => {
33
- let i = t;
34
- const [S, u] = ct(i);
35
- n.getState().setInitialStates(S);
36
- const g = (f, m) => {
37
- const [w] = _.useState(q());
38
- tt({ stateKey: f, options: m, initialOptionsPart: u });
39
- const I = n.getState().cogsStateStore[f] || S[f], s = m?.modifyState ? m.modifyState(I) : I, [e, v] = Et(
40
- s,
32
+ const Ot = (t, i) => {
33
+ let d = t;
34
+ const [u, S] = ut(d);
35
+ a.getState().setInitialStates(u);
36
+ const I = (E, y) => {
37
+ const [p] = w.useState(k());
38
+ nt({ stateKey: E, options: y, initialOptionsPart: S });
39
+ const o = a.getState().cogsStateStore[E] || u[E], r = y?.modifyState ? y.modifyState(o) : o, [v, N] = wt(
40
+ r,
41
41
  {
42
- stateKey: f,
43
- syncUpdate: m?.syncUpdate,
44
- componentId: w,
45
- localStorage: m?.localStorage,
46
- middleware: m?.middleware,
47
- enabledSync: m?.enabledSync,
48
- reactiveDeps: m?.reactiveDeps,
49
- initState: m?.initState
42
+ stateKey: E,
43
+ syncUpdate: y?.syncUpdate,
44
+ componentId: p,
45
+ localStorage: y?.localStorage,
46
+ middleware: y?.middleware,
47
+ enabledSync: y?.enabledSync,
48
+ reactiveDeps: y?.reactiveDeps,
49
+ initState: y?.initState
50
50
  }
51
51
  );
52
- return [e, v];
52
+ return N;
53
53
  };
54
- function E(f, m) {
55
- tt({ stateKey: f, options: m, initialOptionsPart: u });
54
+ function _(E, y) {
55
+ nt({ stateKey: E, options: y, initialOptionsPart: S });
56
56
  }
57
- return { useCogsState: g, setCogsOptions: E };
57
+ return { useCogsState: I, setCogsOptions: _ };
58
58
  }, {
59
- setUpdaterState: R,
60
- setState: A,
61
- getInitialOptions: k,
62
- getKeyState: rt,
63
- getValidationErrors: gt,
64
- setStateLog: ft,
59
+ setUpdaterState: G,
60
+ setState: M,
61
+ getInitialOptions: z,
62
+ getKeyState: it,
63
+ getValidationErrors: mt,
64
+ setStateLog: yt,
65
65
  updateInitialStateGlobal: J,
66
- addValidationError: mt,
67
- removeValidationError: D,
68
- setServerSyncActions: pt
69
- } = n.getState(), ot = (t) => {
66
+ addValidationError: pt,
67
+ removeValidationError: U,
68
+ setServerSyncActions: vt
69
+ } = a.getState(), ot = (t) => {
70
70
  if (!t) return null;
71
71
  try {
72
72
  const i = window.localStorage.getItem(t);
@@ -74,535 +74,584 @@ const ht = (t) => {
74
74
  } catch (i) {
75
75
  return console.error("Error loading from localStorage:", i), null;
76
76
  }
77
- }, It = (t, i, S, u) => {
78
- if (S?.initState) {
79
- const g = {
77
+ }, It = (t, i, d, u) => {
78
+ if (d?.initState) {
79
+ const S = {
80
80
  state: t,
81
81
  lastUpdated: Date.now(),
82
- lastSyncedWithServer: n.getState().serverSyncLog[i]?.[0]?.timeStamp,
83
- baseServerState: n.getState().serverState[i]
84
- }, E = S.initState ? `${u}-${i}-${S.initState.localStorageKey}` : i;
85
- window.localStorage.setItem(E, JSON.stringify(g));
82
+ lastSyncedWithServer: a.getState().serverSyncLog[i]?.[0]?.timeStamp,
83
+ baseServerState: a.getState().serverState[i]
84
+ }, I = d.initState ? `${u}-${i}-${d.initState.localStorageKey}` : i;
85
+ window.localStorage.setItem(I, JSON.stringify(S));
86
86
  }
87
- }, vt = (t, i, S, u, g, E) => {
88
- const f = {
87
+ }, _t = (t, i, d, u, S, I) => {
88
+ const _ = {
89
89
  initialState: i,
90
- updaterState: G(
90
+ updaterState: W(
91
91
  t,
92
92
  u,
93
- g,
94
- E
93
+ S,
94
+ I
95
95
  ),
96
- state: S
96
+ state: d
97
97
  };
98
- _.startTransition(() => {
99
- J(t, f.initialState), R(t, f.updaterState), A(t, f.state);
98
+ w.startTransition(() => {
99
+ J(t, _.initialState), G(t, _.updaterState), M(t, _.state);
100
100
  });
101
- }, yt = (t) => {
102
- const i = n.getState().stateComponents.get(t);
101
+ }, Et = (t) => {
102
+ const i = a.getState().stateComponents.get(t);
103
103
  if (!i) return;
104
- const S = /* @__PURE__ */ new Set();
104
+ const d = /* @__PURE__ */ new Set();
105
105
  i.components.forEach((u) => {
106
- S.add(() => u.forceUpdate());
106
+ d.add(() => u.forceUpdate());
107
107
  }), queueMicrotask(() => {
108
- _.startTransition(() => {
109
- S.forEach((u) => u());
108
+ w.startTransition(() => {
109
+ d.forEach((u) => u());
110
110
  });
111
111
  });
112
112
  };
113
- function Et(t, {
113
+ function wt(t, {
114
114
  stateKey: i,
115
- serverSync: S,
115
+ serverSync: d,
116
116
  zodSchema: u,
117
- localStorage: g,
118
- formElements: E,
119
- middleware: f,
120
- reactiveDeps: m,
121
- componentId: w,
122
- initState: I,
123
- syncUpdate: s
117
+ localStorage: S,
118
+ formElements: I,
119
+ middleware: _,
120
+ reactiveDeps: E,
121
+ componentId: y,
122
+ initState: p,
123
+ syncUpdate: o
124
124
  } = {}) {
125
- const [e, v] = _.useState({}), { sessionId: x } = St();
126
- let j = !i;
127
- const [c] = _.useState(i ?? q()), L = n.getState().stateLog[c], z = _.useRef(/* @__PURE__ */ new Set()), l = _.useRef(w ?? q()), V = _.useRef(null);
128
- V.current = k(c), _.useEffect(() => {
129
- if (s && s.stateKey === c && s.path?.[0]) {
130
- A(c, (r) => ({
131
- ...r,
132
- [s.path[0]]: s.newValue
125
+ const [r, v] = w.useState({}), { sessionId: N } = ft();
126
+ let F = !i;
127
+ const [c] = w.useState(i ?? k()), b = a.getState().stateLog[c], B = w.useRef(/* @__PURE__ */ new Set()), s = w.useRef(y ?? k()), A = w.useRef(null);
128
+ A.current = z(c), w.useEffect(() => {
129
+ if (o && o.stateKey === c && o.path?.[0]) {
130
+ M(c, (n) => ({
131
+ ...n,
132
+ [o.path[0]]: o.newValue
133
133
  }));
134
- const a = `${s.stateKey}:${s.path.join(".")}`;
135
- n.getState().setSyncInfo(a, {
136
- timeStamp: s.timeStamp,
137
- userId: s.userId
134
+ const e = `${o.stateKey}:${o.path.join(".")}`;
135
+ a.getState().setSyncInfo(e, {
136
+ timeStamp: o.timeStamp,
137
+ userId: o.userId
138
138
  });
139
139
  }
140
- }, [s]), _.useEffect(() => {
141
- if (I) {
142
- const { initialState: a, dependencies: r } = I;
143
- K(c, {
144
- initState: I
145
- });
146
- const d = ot(
147
- x + "-" + c + "-" + I?.localStorageKey
148
- );
149
- let p = a;
150
- d && d.lastUpdated > (d.lastSyncedWithServer || 0) && (p = d.state), vt(
151
- c,
152
- a,
153
- p,
154
- P,
155
- l.current,
156
- x
157
- ), yt(c);
158
- }
159
- }, [I?.localStorageKey, ...I?.dependencies || []]), _.useEffect(() => {
160
- j && K(c, {
161
- serverSync: S,
162
- formElements: E,
140
+ }, [o]), w.useEffect(() => {
141
+ et(c, {
142
+ initState: p
143
+ });
144
+ const e = ot(
145
+ N + "-" + c + "-" + p?.localStorageKey
146
+ );
147
+ let n = null;
148
+ p?.initialState && (n = p?.initialState, e && e.lastUpdated > (e.lastSyncedWithServer || 0) && (n = e.state), _t(
149
+ c,
150
+ p?.initialState,
151
+ n,
152
+ h,
153
+ s.current,
154
+ N
155
+ )), Et(c);
156
+ }, [p?.localStorageKey, ...p?.dependencies || []]), w.useEffect(() => {
157
+ F && et(c, {
158
+ serverSync: d,
159
+ formElements: I,
163
160
  zodSchema: u,
164
- initState: I,
165
- localStorage: g,
166
- middleware: f
161
+ initState: p,
162
+ localStorage: S,
163
+ middleware: _
167
164
  });
168
- const a = `${c}////${l.current}`, r = n.getState().stateComponents.get(c) || {
165
+ const e = `${c}////${s.current}`, n = a.getState().stateComponents.get(c) || {
169
166
  components: /* @__PURE__ */ new Map()
170
167
  };
171
- return r.components.set(a, {
168
+ return n.components.set(e, {
172
169
  forceUpdate: () => v({}),
173
170
  paths: /* @__PURE__ */ new Set(),
174
171
  deps: [],
175
- depsFunction: m || void 0
176
- }), n.getState().stateComponents.set(c, r), () => {
177
- const d = `${c}////${l.current}`;
178
- r && (r.components.delete(d), r.components.size === 0 && n.getState().stateComponents.delete(c));
172
+ depsFunction: E || void 0
173
+ }), a.getState().stateComponents.set(c, n), () => {
174
+ const l = `${c}////${s.current}`;
175
+ n && (n.components.delete(l), n.components.size === 0 && a.getState().stateComponents.delete(c));
179
176
  };
180
177
  }, []);
181
- const P = (a, r, d, p) => {
182
- if (Array.isArray(r)) {
183
- const $ = `${c}-${r.join(".")}`;
184
- z.current.add($);
178
+ const h = (e, n, l, g) => {
179
+ if (Array.isArray(n)) {
180
+ const m = `${c}-${n.join(".")}`;
181
+ B.current.add(m);
185
182
  }
186
- A(c, ($) => {
187
- const N = nt(a) ? a($) : a, B = `${c}-${r.join(".")}`;
188
- if (B) {
189
- const F = n.getState().signalDomElements.get(B);
190
- if (F) {
191
- const y = W(N, r);
192
- F.forEach(({ parentId: T, position: O }) => {
183
+ M(c, (m) => {
184
+ const $ = at(e) ? e(m) : e, P = `${c}-${n.join(".")}`;
185
+ if (P) {
186
+ let j = !1, f = a.getState().signalDomElements.get(P);
187
+ if ((!f || f.size === 0) && (l.updateType === "insert" || l.updateType === "cut")) {
188
+ const V = n.slice(0, -1), x = R($, V);
189
+ if (Array.isArray(x)) {
190
+ j = !0;
191
+ const T = `${c}-${V.join(".")}`;
192
+ f = a.getState().signalDomElements.get(T);
193
+ }
194
+ }
195
+ if (f) {
196
+ const V = j ? R($, n.slice(0, -1)) : R($, n);
197
+ f.forEach(({ parentId: x, position: T, effect: D }) => {
193
198
  const C = document.querySelector(
194
- `[data-parent-id="${T}"]`
199
+ `[data-parent-id="${x}"]`
195
200
  );
196
201
  if (C) {
197
- const b = Array.from(C.childNodes);
198
- b[O] && (b[O].textContent = String(y));
202
+ const X = Array.from(C.childNodes);
203
+ if (X[T]) {
204
+ const dt = D ? new Function(
205
+ "state",
206
+ `return (${D})(state)`
207
+ )(V) : V;
208
+ X[T].textContent = String(dt);
209
+ }
199
210
  }
200
211
  });
201
212
  }
202
213
  }
203
- d.updateType === "update" && (p || V.current?.validationKey) && r && D(
204
- (p || V.current?.validationKey) + "." + r.join(".")
214
+ l.updateType === "update" && (g || A.current?.validationKey) && n && U(
215
+ (g || A.current?.validationKey) + "." + n.join(".")
205
216
  );
206
- const U = r.slice(0, r.length - 1);
207
- d.updateType === "cut" && V.current?.validationKey && D(
208
- V.current?.validationKey + "." + U.join(".")
209
- ), d.updateType === "insert" && V.current?.validationKey && gt(
210
- V.current?.validationKey + "." + U.join(".")
211
- ).filter(([y, T]) => {
212
- let O = y?.split(".").length;
213
- if (y == U.join(".") && O == U.length - 1) {
214
- let C = y + "." + U;
215
- D(y), mt(C, T);
217
+ const O = n.slice(0, n.length - 1);
218
+ l.updateType === "cut" && A.current?.validationKey && U(
219
+ A.current?.validationKey + "." + O.join(".")
220
+ ), l.updateType === "insert" && A.current?.validationKey && mt(
221
+ A.current?.validationKey + "." + O.join(".")
222
+ ).filter(([f, V]) => {
223
+ let x = f?.split(".").length;
224
+ if (f == O.join(".") && x == O.length - 1) {
225
+ let T = f + "." + O;
226
+ U(f), pt(T, V);
216
227
  }
217
228
  });
218
- const at = W($, r), it = W(N, r), st = d.updateType === "update" ? r.join(".") : [...r].slice(0, -1).join("."), H = n.getState().stateComponents.get(c);
229
+ const st = R(m, n), ct = R($, n), lt = l.updateType === "update" ? n.join(".") : [...n].slice(0, -1).join("."), H = a.getState().stateComponents.get(c);
219
230
  if (H) {
220
231
  for (const [
221
- F,
222
- y
232
+ j,
233
+ f
223
234
  ] of H.components.entries())
224
- if (y.depsFunction || y.paths && y.paths.has(st))
225
- if (y.depsFunction) {
226
- const T = y.depsFunction(N);
227
- typeof T == "boolean" ? T && y.forceUpdate() : M(y.deps, T) || (y.deps = T, y.forceUpdate());
235
+ if (f.depsFunction || f.paths && f.paths.has(lt))
236
+ if (f.depsFunction) {
237
+ const V = f.depsFunction($);
238
+ typeof V == "boolean" ? V && f.forceUpdate() : L(f.deps, V) || (f.deps = V, f.forceUpdate());
228
239
  } else
229
- y.forceUpdate();
240
+ f.forceUpdate();
230
241
  }
231
242
  const Q = {
232
243
  timeStamp: Date.now(),
233
244
  stateKey: c,
234
- path: r,
235
- updateType: d.updateType,
245
+ path: n,
246
+ updateType: l.updateType,
236
247
  status: "new",
237
- oldValue: at,
238
- newValue: it
248
+ oldValue: st,
249
+ newValue: ct
239
250
  };
240
- if (ft(c, (F) => {
241
- const T = [...F ?? [], Q].reduce((O, C) => {
242
- const b = `${C.stateKey}:${JSON.stringify(C.path)}`, h = O.get(b);
243
- return h ? (h.timeStamp = Math.max(
244
- h.timeStamp,
245
- C.timeStamp
246
- ), h.newValue = C.newValue, h.oldValue = h.oldValue ?? C.oldValue, h.updateType = C.updateType) : O.set(b, { ...C }), O;
251
+ if (yt(c, (j) => {
252
+ const V = [...j ?? [], Q].reduce((x, T) => {
253
+ const D = `${T.stateKey}:${JSON.stringify(T.path)}`, C = x.get(D);
254
+ return C ? (C.timeStamp = Math.max(
255
+ C.timeStamp,
256
+ T.timeStamp
257
+ ), C.newValue = T.newValue, C.oldValue = C.oldValue ?? T.oldValue, C.updateType = T.updateType) : x.set(D, { ...T }), x;
247
258
  }, /* @__PURE__ */ new Map());
248
- return Array.from(T.values());
259
+ return Array.from(V.values());
249
260
  }), It(
250
- N,
261
+ $,
251
262
  c,
252
- V.current,
253
- x
254
- ), f && f({ updateLog: L, update: Q }), V.current?.serverSync) {
255
- const F = n.getState().serverState[c], y = V.current?.serverSync;
256
- pt(c, {
257
- syncKey: typeof y.syncKey == "string" ? y.syncKey : y.syncKey({ state: N }),
258
- rollBackState: F,
259
- actionTimeStamp: Date.now() + (y.debounce ?? 3e3),
263
+ A.current,
264
+ N
265
+ ), _ && _({ updateLog: b, update: Q }), A.current?.serverSync) {
266
+ const j = a.getState().serverState[c], f = A.current?.serverSync;
267
+ vt(c, {
268
+ syncKey: typeof f.syncKey == "string" ? f.syncKey : f.syncKey({ state: $ }),
269
+ rollBackState: j,
270
+ actionTimeStamp: Date.now() + (f.debounce ?? 3e3),
260
271
  status: "waiting"
261
272
  });
262
273
  }
263
- return N;
274
+ return $;
264
275
  });
265
276
  };
266
- n.getState().updaterState[c] || (console.log("Initializing state for", c, t), R(
277
+ a.getState().updaterState[c] || (console.log("Initializing state for", c, t), G(
267
278
  c,
268
- G(
279
+ W(
269
280
  c,
270
- P,
271
- l.current,
272
- x
281
+ h,
282
+ s.current,
283
+ N
273
284
  )
274
- ), n.getState().cogsStateStore[c] || A(c, t), n.getState().initialStateGlobal[c] || J(c, t));
275
- const o = _.useMemo(() => G(
285
+ ), a.getState().cogsStateStore[c] || M(c, t), a.getState().initialStateGlobal[c] || J(c, t));
286
+ const q = w.useMemo(() => W(
276
287
  c,
277
- P,
278
- l.current,
279
- x
288
+ h,
289
+ s.current,
290
+ N
280
291
  ), [c]);
281
- return [rt(c), o];
282
- }
283
- function _t({
284
- proxy: t
285
- }) {
286
- const i = _.useRef(null), S = `${t._stateKey}-${t._path.join(".")}`;
287
- return _.useEffect(() => {
288
- const u = i.current;
289
- if (!u || !u.parentElement) {
290
- console.log("No element or parent");
291
- return;
292
- }
293
- const g = u.parentElement, f = Array.from(g.childNodes).indexOf(u);
294
- let m = g.getAttribute("data-parent-id");
295
- m || (m = `parent-${crypto.randomUUID()}`, g.setAttribute("data-parent-id", m));
296
- const I = { instanceId: `instance-${crypto.randomUUID()}`, parentId: m, position: f };
297
- n.getState().addSignalElement(S, I);
298
- const s = document.createTextNode(
299
- String(
300
- n.getState().getNestedState(t._stateKey, t._path)
301
- )
302
- );
303
- u.replaceWith(s);
304
- }, [t._stateKey, t._path.join(".")]), _.createElement("span", {
305
- ref: i,
306
- style: { display: "none" }
307
- });
292
+ return [it(c), q];
308
293
  }
309
- function G(t, i, S, u) {
310
- const g = /* @__PURE__ */ new Map();
311
- let E = 0;
312
- const f = (s) => {
313
- const e = s.join(".");
314
- for (const [v] of g)
315
- (v === e || v.startsWith(e + ".")) && g.delete(v);
316
- E++;
317
- }, m = /* @__PURE__ */ new Map(), w = {
318
- removeValidation: (s) => {
319
- s?.validationKey && D(s.validationKey);
294
+ function W(t, i, d, u) {
295
+ const S = /* @__PURE__ */ new Map();
296
+ let I = 0;
297
+ const _ = (o) => {
298
+ const r = o.join(".");
299
+ for (const [v] of S)
300
+ (v === r || v.startsWith(r + ".")) && S.delete(v);
301
+ I++;
302
+ }, E = /* @__PURE__ */ new Map(), y = {
303
+ removeValidation: (o) => {
304
+ o?.validationKey && U(o.validationKey);
320
305
  },
321
- revertToInitialState: (s) => {
322
- s?.validationKey && D(s.validationKey);
323
- const e = n.getState().initialStateGlobal[t];
324
- g.clear(), E++;
325
- const v = I(e, []);
326
- _.startTransition(() => {
327
- R(t, v), A(t, e);
328
- const x = n.getState().stateComponents.get(t);
329
- x && x.components.forEach((c) => {
306
+ revertToInitialState: (o) => {
307
+ o?.validationKey && U(o.validationKey);
308
+ const r = a.getState().initialStateGlobal[t];
309
+ S.clear(), I++;
310
+ const v = p(r, []);
311
+ w.startTransition(() => {
312
+ G(t, v), M(t, r);
313
+ const N = a.getState().stateComponents.get(t);
314
+ N && N.components.forEach((c) => {
330
315
  c.forceUpdate();
331
316
  });
332
- const j = k(t);
333
- j?.initState && localStorage.removeItem(
334
- j?.initState ? u + "-" + t + "-" + j?.initState.localStorageKey : t
317
+ const F = z(t);
318
+ F?.initState && localStorage.removeItem(
319
+ F?.initState ? u + "-" + t + "-" + F?.initState.localStorageKey : t
335
320
  ), localStorage.removeItem(t);
336
321
  });
337
322
  },
338
- updateInitialState: (s) => {
339
- g.clear(), E++;
340
- const e = G(
323
+ updateInitialState: (o) => {
324
+ S.clear(), I++;
325
+ const r = W(
341
326
  t,
342
327
  i,
343
- S,
328
+ d,
344
329
  u
345
330
  );
346
- return _.startTransition(() => {
347
- J(t, s), R(t, e), A(t, s);
348
- const v = n.getState().stateComponents.get(t);
349
- v && v.components.forEach((x) => {
350
- x.forceUpdate();
331
+ return w.startTransition(() => {
332
+ J(t, o), G(t, r), M(t, o);
333
+ const v = a.getState().stateComponents.get(t);
334
+ v && v.components.forEach((N) => {
335
+ N.forceUpdate();
351
336
  }), localStorage.removeItem(t);
352
337
  }), {
353
- fetchId: (v) => e.get()[v]
338
+ fetchId: (v) => r.get()[v]
354
339
  };
355
340
  },
356
- _initialState: n.getState().initialStateGlobal[t],
357
- _serverState: n.getState().serverState[t],
358
- _isLoading: n.getState().isLoadingGlobal[t],
341
+ _initialState: a.getState().initialStateGlobal[t],
342
+ _serverState: a.getState().serverState[t],
343
+ _isLoading: a.getState().isLoadingGlobal[t],
359
344
  _isServerSynced: () => {
360
- const s = n.getState().serverState[t];
361
- return !!(s && M(s, rt(t)));
345
+ const o = a.getState().serverState[t];
346
+ return !!(o && L(o, it(t)));
362
347
  }
363
348
  };
364
- function I(s, e = [], v) {
365
- const x = e.map(String).join("."), j = g.get(x);
366
- if (j?.stateVersion === E)
367
- return j.proxy;
349
+ function p(o, r = [], v) {
350
+ const N = r.map(String).join("."), F = S.get(N);
351
+ if (F?.stateVersion === I)
352
+ return F.proxy;
368
353
  const c = {
369
- get(z, l) {
370
- if (l !== "then" && l !== "$get") {
371
- const o = e.join("."), a = `${t}////${S}`, r = n.getState().stateComponents.get(t);
372
- if (r && o) {
373
- const d = r.components.get(a);
374
- d && d.paths.add(o);
354
+ get(B, s) {
355
+ if (s !== "then" && !s.startsWith("$")) {
356
+ const e = r.join("."), n = `${t}////${d}`, l = a.getState().stateComponents.get(t);
357
+ if (l && e) {
358
+ const g = l.components.get(n);
359
+ g && g.paths.add(e);
375
360
  }
376
361
  }
377
- if (l === "lastSynced") {
378
- const o = `${t}:${e.join(".")}`;
379
- return n.getState().getSyncInfo(o);
380
- }
381
- if (l === "_selected") {
382
- const o = e.slice(0, -1), a = o.join("."), r = n.getState().getNestedState(t, o);
383
- return Array.isArray(r) ? Number(e[e.length - 1]) === m.get(a) : void 0;
384
- }
385
- if (l == "getLocalStorage")
386
- return (o) => ot(
387
- u + "-" + t + "-" + o
388
- );
389
- if (l === "setSelected")
390
- return (o) => {
391
- const a = e.slice(0, -1), r = Number(e[e.length - 1]), d = a.join(".");
392
- o ? m.set(d, r) : m.delete(d);
393
- const p = n.getState().getNestedState(t, [...a]);
394
- Y(i, p, a), f(a);
395
- };
396
- if (e.length == 0) {
397
- if (l == "_componentId") return S;
398
- if (l === "_initialState")
399
- return n.getState().initialStateGlobal[t];
400
- if (l === "_serverState")
401
- return n.getState().serverState[t];
402
- if (l === "_isLoading")
403
- return n.getState().isLoadingGlobal[t];
404
- if (l === "revertToInitialState")
405
- return w.revertToInitialState;
406
- if (l === "updateInitialState")
407
- return w.updateInitialState;
408
- if (l === "removeValidation")
409
- return w.removeValidation;
410
- }
411
- if (l === "validationWrapper")
412
- return ({
413
- children: o,
414
- hideMessage: a
415
- }) => /* @__PURE__ */ X.jsx(
416
- lt,
417
- {
418
- formOpts: a ? { validation: { message: "" } } : void 0,
419
- path: e,
420
- validationKey: n.getState().getInitialOptions(t)?.validationKey || "",
421
- stateKey: t,
422
- validIndices: v?.validIndices,
423
- children: o
424
- }
425
- );
426
- if (l === "_stateKey") return t;
427
- if (l === "_path") return e;
428
- if (l === "_isServerSynced") return w._isServerSynced;
429
- if (l === "update")
430
- return (o, a) => {
431
- f(e), Y(i, o, e, "");
432
- };
433
- if (l === "get")
434
- return () => n.getState().getNestedState(t, e);
435
- if (l === "$get")
436
- return () => et({ _stateKey: t, _path: e });
437
- if (l === "formElement")
438
- return (o, a, r) => /* @__PURE__ */ X.jsx(
439
- dt,
440
- {
441
- setState: i,
442
- validationKey: o,
443
- stateKey: t,
444
- path: e,
445
- child: a,
446
- formOpts: r
447
- }
448
- );
449
- if (Array.isArray(s)) {
450
- if (l === "getSelected")
362
+ if (Array.isArray(o)) {
363
+ if (s === "getSelected")
451
364
  return () => {
452
- const o = m.get(
453
- e.join(".")
365
+ const e = E.get(
366
+ r.join(".")
454
367
  );
455
- if (o !== void 0)
456
- return I(
457
- s[o],
458
- [...e, o.toString()],
368
+ if (e !== void 0)
369
+ return p(
370
+ o[e],
371
+ [...r, e.toString()],
459
372
  v
460
373
  );
461
374
  };
462
- if (l === "$get")
463
- return () => et({ _stateKey: t, _path: e });
464
- if (l === "stateEach")
465
- return (o) => {
466
- const a = v?.filtered?.some(
467
- (d) => d.join(".") === e.join(".")
468
- ), r = a ? s : n.getState().getNestedState(t, e);
469
- return g.clear(), E++, r.map((d, p) => {
470
- const $ = a && d.__origIndex ? d.__origIndex : p, N = I(
471
- d,
472
- [...e, $.toString()],
375
+ if (s === "stateMap")
376
+ return (e) => {
377
+ const n = v?.filtered?.some(
378
+ (g) => g.join(".") === r.join(".")
379
+ ), l = n ? o : a.getState().getNestedState(t, r);
380
+ return S.clear(), I++, l.map((g, m) => {
381
+ const $ = n && g.__origIndex ? g.__origIndex : m, P = p(
382
+ g,
383
+ [...r, $.toString()],
473
384
  v
474
385
  );
475
- return o(
476
- d,
477
- N,
478
- p,
479
- s,
480
- I(
481
- s,
482
- e,
386
+ return e(
387
+ g,
388
+ P,
389
+ m,
390
+ o,
391
+ p(
392
+ o,
393
+ r,
483
394
  v
484
395
  )
485
396
  );
486
397
  });
487
398
  };
488
- if (l === "stateFlattenOn")
489
- return (o) => {
490
- const r = v?.filtered?.some(
491
- (p) => p.join(".") === e.join(".")
492
- ) ? s : n.getState().getNestedState(t, e);
493
- g.clear(), E++;
494
- const d = r.flatMap(
495
- (p, $) => p[o] ?? []
399
+ if (s === "$stateMap")
400
+ return (e) => w.createElement($t, {
401
+ proxy: {
402
+ _stateKey: t,
403
+ _path: r,
404
+ _mapFn: e
405
+ // Pass the actual function, not string
406
+ }
407
+ });
408
+ if (s === "stateFlattenOn")
409
+ return (e) => {
410
+ const l = v?.filtered?.some(
411
+ (m) => m.join(".") === r.join(".")
412
+ ) ? o : a.getState().getNestedState(t, r);
413
+ S.clear(), I++;
414
+ const g = l.flatMap(
415
+ (m, $) => m[e] ?? []
496
416
  );
497
- return I(
498
- d,
499
- [...e, "[*]", o],
417
+ return p(
418
+ g,
419
+ [...r, "[*]", e],
500
420
  v
501
421
  );
502
422
  };
503
- if (l === "findWith")
504
- return (o, a) => {
505
- const r = s.findIndex(
506
- ($) => $[o] === a
423
+ if (s === "findWith")
424
+ return (e, n) => {
425
+ const l = o.findIndex(
426
+ ($) => $[e] === n
507
427
  );
508
- if (r === -1) return;
509
- const d = s[r], p = [...e, r.toString()];
510
- return g.clear(), E++, I(d, p);
428
+ if (l === -1) return;
429
+ const g = o[l], m = [...r, l.toString()];
430
+ return S.clear(), I++, S.clear(), I++, p(g, m);
511
431
  };
512
- if (l === "index")
513
- return (o) => {
514
- const a = s[o];
515
- return I(a, [
516
- ...e,
517
- o.toString()
432
+ if (s === "index")
433
+ return (e) => {
434
+ const n = o[e];
435
+ return p(n, [
436
+ ...r,
437
+ e.toString()
518
438
  ]);
519
439
  };
520
- if (l === "insert")
521
- return (o) => (f(e), Z(
440
+ if (s === "insert")
441
+ return (e) => (_(r), Z(
522
442
  i,
523
- o,
524
443
  e,
444
+ r,
525
445
  t
526
- ), I(
527
- n.getState().cogsStateStore[t],
446
+ ), p(
447
+ a.getState().cogsStateStore[t],
528
448
  []
529
449
  ));
530
- if (l === "uniqueInsert")
531
- return (o, a) => {
532
- const r = n.getState().getNestedState(t, e), d = nt(o) ? o(r) : o;
533
- !r.some(($) => a ? a.every(
534
- (N) => M(
535
- $[N],
536
- d[N]
450
+ if (s === "uniqueInsert")
451
+ return (e, n) => {
452
+ const l = a.getState().getNestedState(t, r), g = at(e) ? e(l) : e;
453
+ !l.some(($) => n ? n.every(
454
+ (P) => L(
455
+ $[P],
456
+ g[P]
537
457
  )
538
- ) : M($, d)) && (f(e), Z(
458
+ ) : L($, g)) && (_(r), Z(
539
459
  i,
540
- d,
541
- e,
460
+ g,
461
+ r,
542
462
  t
543
463
  ));
544
464
  };
545
- if (l === "cut")
546
- return (o, a) => {
547
- a?.waitForSync || (f(e), ut(i, e, t, o));
465
+ if (s === "cut")
466
+ return (e, n) => {
467
+ n?.waitForSync || (_(r), K(i, r, t, e));
548
468
  };
549
- if (l === "stateFilter")
550
- return (o) => {
551
- const a = s.map(
552
- (p, $) => ({
553
- ...p,
469
+ if (s === "stateFilter")
470
+ return (e) => {
471
+ const n = o.map(
472
+ (m, $) => ({
473
+ ...m,
554
474
  __origIndex: $.toString()
555
475
  })
556
- ), r = [], d = [];
557
- for (let p = 0; p < a.length; p++)
558
- o(a[p], p) && (r.push(p), d.push(a[p]));
559
- return g.clear(), E++, I(
560
- d,
561
- e,
476
+ ), l = [], g = [];
477
+ for (let m = 0; m < n.length; m++)
478
+ e(n[m], m) && (l.push(m), g.push(n[m]));
479
+ return S.clear(), I++, p(
480
+ g,
481
+ r,
562
482
  {
563
- filtered: [...v?.filtered || [], e],
564
- validIndices: r
483
+ filtered: [...v?.filtered || [], r],
484
+ validIndices: l
565
485
  // Pass through the meta
566
486
  }
567
487
  );
568
488
  };
569
489
  }
570
- const V = [...e, l], P = n.getState().getNestedState(t, V);
571
- return I(P, V, v);
490
+ const A = r[r.length - 1];
491
+ if (!isNaN(Number(A))) {
492
+ const e = r.slice(0, -1), n = a.getState().getNestedState(t, e);
493
+ if (Array.isArray(n) && s === "cut")
494
+ return () => K(
495
+ i,
496
+ e,
497
+ t,
498
+ Number(A)
499
+ );
500
+ }
501
+ if (s === "get")
502
+ return () => a.getState().getNestedState(t, r);
503
+ if (s === "$effect")
504
+ return (e) => rt({
505
+ _stateKey: t,
506
+ _path: r,
507
+ _effect: e.toString()
508
+ });
509
+ if (s === "$get")
510
+ return () => rt({
511
+ _stateKey: t,
512
+ _path: r
513
+ });
514
+ if (s === "lastSynced") {
515
+ const e = `${t}:${r.join(".")}`;
516
+ return a.getState().getSyncInfo(e);
517
+ }
518
+ if (s === "_selected") {
519
+ const e = r.slice(0, -1), n = e.join("."), l = a.getState().getNestedState(t, e);
520
+ return Array.isArray(l) ? Number(r[r.length - 1]) === E.get(n) : void 0;
521
+ }
522
+ if (s == "getLocalStorage")
523
+ return (e) => ot(
524
+ u + "-" + t + "-" + e
525
+ );
526
+ if (s === "setSelected")
527
+ return (e) => {
528
+ const n = r.slice(0, -1), l = Number(r[r.length - 1]), g = n.join(".");
529
+ e ? E.set(g, l) : E.delete(g);
530
+ const m = a.getState().getNestedState(t, [...n]);
531
+ tt(i, m, n), _(n);
532
+ };
533
+ if (r.length == 0) {
534
+ if (s == "_componentId") return d;
535
+ if (s === "_initialState")
536
+ return a.getState().initialStateGlobal[t];
537
+ if (s === "_serverState")
538
+ return a.getState().serverState[t];
539
+ if (s === "_isLoading")
540
+ return a.getState().isLoadingGlobal[t];
541
+ if (s === "revertToInitialState")
542
+ return y.revertToInitialState;
543
+ if (s === "updateInitialState")
544
+ return y.updateInitialState;
545
+ if (s === "removeValidation")
546
+ return y.removeValidation;
547
+ }
548
+ if (s === "validationWrapper")
549
+ return ({
550
+ children: e,
551
+ hideMessage: n
552
+ }) => /* @__PURE__ */ Y.jsx(
553
+ St,
554
+ {
555
+ formOpts: n ? { validation: { message: "" } } : void 0,
556
+ path: r,
557
+ validationKey: a.getState().getInitialOptions(t)?.validationKey || "",
558
+ stateKey: t,
559
+ validIndices: v?.validIndices,
560
+ children: e
561
+ }
562
+ );
563
+ if (s === "_stateKey") return t;
564
+ if (s === "_path") return r;
565
+ if (s === "_isServerSynced") return y._isServerSynced;
566
+ if (s === "update")
567
+ return (e, n) => {
568
+ _(r), tt(i, e, r, "");
569
+ };
570
+ if (s === "formElement")
571
+ return (e, n, l) => /* @__PURE__ */ Y.jsx(
572
+ gt,
573
+ {
574
+ setState: i,
575
+ validationKey: e,
576
+ stateKey: t,
577
+ path: r,
578
+ child: n,
579
+ formOpts: l
580
+ }
581
+ );
582
+ const h = [...r, s], q = a.getState().getNestedState(t, h);
583
+ return p(q, h, v);
572
584
  }
573
- }, L = new Proxy(w, c);
574
- return g.set(x, {
575
- proxy: L,
576
- stateVersion: E
577
- }), L;
585
+ }, b = new Proxy(y, c);
586
+ return S.set(N, {
587
+ proxy: b,
588
+ stateVersion: I
589
+ }), b;
578
590
  }
579
- return I(
580
- n.getState().getNestedState(t, [])
591
+ return p(
592
+ a.getState().getNestedState(t, [])
581
593
  );
582
594
  }
583
- function et(t) {
584
- return _.createElement(_t, { proxy: t });
595
+ function rt(t) {
596
+ return w.createElement(Nt, { proxy: t });
597
+ }
598
+ function $t({
599
+ proxy: t
600
+ }) {
601
+ const i = a().getNestedState(t._stateKey, t._path);
602
+ return console.log("value", i), Array.isArray(i) ? i.map((d, u) => t._mapFn(
603
+ d,
604
+ a.getState().updaterState[t._stateKey],
605
+ u,
606
+ i,
607
+ a.getState().updaterState[t._stateKey]
608
+ )) : null;
609
+ }
610
+ function Nt({
611
+ proxy: t
612
+ }) {
613
+ const i = w.useRef(null), d = `${t._stateKey}-${t._path.join(".")}`;
614
+ return console.log("SignalRenderer", d), w.useEffect(() => {
615
+ const u = i.current;
616
+ if (!u || !u.parentElement) return;
617
+ const S = u.parentElement, _ = Array.from(S.childNodes).indexOf(u);
618
+ let E = S.getAttribute("data-parent-id");
619
+ E || (E = `parent-${crypto.randomUUID()}`, S.setAttribute("data-parent-id", E));
620
+ const p = {
621
+ instanceId: `instance-${crypto.randomUUID()}`,
622
+ parentId: E,
623
+ position: _,
624
+ effect: t._effect
625
+ };
626
+ a.getState().addSignalElement(d, p);
627
+ const o = a.getState().getNestedState(t._stateKey, t._path), r = document.createTextNode(String(o));
628
+ u.replaceWith(r);
629
+ }, [t._stateKey, t._path.join("."), t._effect]), w.createElement("span", {
630
+ ref: i,
631
+ style: { display: "none" },
632
+ "data-signal-id": d
633
+ });
585
634
  }
586
- function At(t) {
587
- const i = _.useSyncExternalStore(
588
- (S) => {
589
- const u = n.getState().stateComponents.get(t._stateKey) || {
635
+ function Dt(t) {
636
+ const i = w.useSyncExternalStore(
637
+ (d) => {
638
+ const u = a.getState().stateComponents.get(t._stateKey) || {
590
639
  components: /* @__PURE__ */ new Map()
591
640
  };
592
641
  return u.components.set(t._stateKey, {
593
- forceUpdate: S,
642
+ forceUpdate: d,
594
643
  paths: /* @__PURE__ */ new Set([t._path.join(".")])
595
644
  }), () => u.components.delete(t._stateKey);
596
645
  },
597
- () => n.getState().getNestedState(t._stateKey, t._path)
646
+ () => a.getState().getNestedState(t._stateKey, t._path)
598
647
  );
599
- return _.createElement("text", {}, String(i));
648
+ return w.createElement("text", {}, String(i));
600
649
  }
601
650
  export {
602
- et as $cogsSignal,
603
- At as $cogsSignalStore,
604
- Ot as addStateOptions,
605
- ht as createCogsState,
606
- Et as useCogsStateFn
651
+ rt as $cogsSignal,
652
+ Dt as $cogsSignalStore,
653
+ Mt as addStateOptions,
654
+ Ot as createCogsState,
655
+ wt as useCogsStateFn
607
656
  };
608
657
  //# sourceMappingURL=CogsState.jsx.map