cogsbox-state 0.5.126 → 0.5.127

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,39 +1,39 @@
1
- import { jsx as v, Fragment as I } from "react/jsx-runtime";
1
+ import { jsx as V, Fragment as M } from "react/jsx-runtime";
2
2
  import "./CogsState.jsx";
3
- import { getNestedValue as F, isFunction as B, updateNestedProperty as V } from "./utility.js";
4
- import G, { useState as N, useRef as y, useEffect as b } from "react";
5
- import { getGlobalStore as l, formRefStore as W } from "./store.js";
6
- import { validateZodPathFunc as Y } from "./useValidateZodPath.js";
7
- function Z(o, t, n, r) {
8
- o(
9
- (e) => {
10
- if (B(t)) {
11
- const s = t(F(e, n));
12
- let i = V(n, e, s);
3
+ import { getNestedValue as R, isFunction as U, updateNestedProperty as F } from "./utility.js";
4
+ import G, { useRef as b, useState as z, useEffect as j } from "react";
5
+ import { getGlobalStore as d, formRefStore as O } from "./store.js";
6
+ import { validateZodPathFunc as W } from "./useValidateZodPath.js";
7
+ function I(n, e, t, r) {
8
+ n(
9
+ (o) => {
10
+ if (U(e)) {
11
+ const s = e(R(o, t));
12
+ let i = F(t, o, s);
13
13
  return typeof i == "string" && (i = i.trim()), i;
14
14
  } else {
15
- let s = !n || n.length == 0 ? t : V(n, e, t);
15
+ let s = !t || t.length == 0 ? e : F(t, o, e);
16
16
  return typeof s == "string" && (s = s.trim()), s;
17
17
  }
18
18
  },
19
- n,
19
+ t,
20
20
  { updateType: "update" },
21
21
  r
22
22
  );
23
23
  }
24
- function tt(o, t, n, r, e) {
25
- const s = l.getState().getNestedState(r, n);
26
- o(
24
+ function p(n, e, t, r, o) {
25
+ const s = d.getState().getNestedState(r, t);
26
+ n(
27
27
  (i) => {
28
- let u = !n || n.length == 0 ? i : F(i, [...n]), c = [...u];
28
+ let u = !t || t.length == 0 ? i : R(i, [...t]), c = [...u];
29
29
  return c.splice(
30
- Number(e) == 0 ? e : u.length,
30
+ Number(o) == 0 ? o : u.length,
31
31
  0,
32
- B(t) ? t(u) : t
33
- ), n.length == 0 ? c : V([...n], i, c);
32
+ U(e) ? e(u) : e
33
+ ), t.length == 0 ? c : F([...t], i, c);
34
34
  },
35
35
  [
36
- ...n,
36
+ ...t,
37
37
  (s.length - 1).toString()
38
38
  ],
39
39
  {
@@ -41,173 +41,162 @@ function tt(o, t, n, r, e) {
41
41
  }
42
42
  );
43
43
  }
44
- function et(o, t, n, r) {
45
- const e = l.getState().getNestedState(n, t);
46
- o(
44
+ function ee(n, e, t, r) {
45
+ const o = d.getState().getNestedState(t, e);
46
+ n(
47
47
  (s) => {
48
- const i = F(s, [...t]);
48
+ const i = R(s, [...e]);
49
49
  if (r < 0 || r >= i?.length)
50
50
  throw new Error(`Index ${r} does not exist in the array.`);
51
51
  const u = r || Number(r) == 0 ? r : i.length - 1, c = [
52
52
  ...i.slice(0, u),
53
53
  ...i.slice(u + 1)
54
54
  ];
55
- return t.length == 0 ? c : V([...t], s, c);
55
+ return e.length == 0 ? c : F([...e], s, c);
56
56
  },
57
57
  [
58
- ...t,
59
- r || r === 0 ? r?.toString() : (e.length - 1).toString()
58
+ ...e,
59
+ r || r === 0 ? r?.toString() : (o.length - 1).toString()
60
60
  ],
61
61
  { updateType: "cut" }
62
62
  );
63
63
  }
64
- const R = (o, t, n = (r, e) => JSON.stringify(r) === JSON.stringify(e)) => {
65
- const [r, e] = N(
66
- () => t(l.getState(), o)
67
- ), s = y(r), i = y(o);
68
- return b(() => {
69
- i.current = o, e(t(l.getState(), o));
70
- const u = (d) => {
71
- const a = t(d, i.current);
72
- n(s.current, a) || (s.current = a, e(a));
73
- }, c = l.subscribe(u);
64
+ const N = (n, e, t = (r, o) => JSON.stringify(r) === JSON.stringify(o)) => {
65
+ const [r, o] = z(
66
+ () => e(d.getState(), n)
67
+ ), s = b(r), i = b(n);
68
+ return j(() => {
69
+ i.current = n, o(e(d.getState(), n));
70
+ const u = (f) => {
71
+ const l = e(f, i.current);
72
+ t(s.current, l) || (s.current = l, o(l));
73
+ }, c = d.subscribe(u);
74
74
  return () => {
75
75
  c();
76
76
  };
77
- }, [o]), r;
78
- }, _ = (o, t, n) => {
79
- const r = o + "." + (t.length > 0 ? [t.join(".")] : []) + (n && n.length > 0 ? "." + n : "");
80
- return R(
77
+ }, [n]), r;
78
+ }, Z = (n, e, t) => {
79
+ const r = n + "." + (e.length > 0 ? [e.join(".")] : []) + (t && t.length > 0 ? "." + t : "");
80
+ return N(
81
81
  r,
82
82
  (s, i) => s.getValidationErrors(i) || []
83
83
  );
84
- }, q = (o, t) => {
85
- const n = `${o}:${t.join(".")}`;
86
- return R(
87
- n,
88
- (r, e) => r.getSyncInfo(e)
84
+ }, q = (n, e) => {
85
+ const t = `${n}:${e.join(".")}`;
86
+ return N(
87
+ t,
88
+ (r, o) => r.getSyncInfo(o)
89
89
  );
90
- }, H = (o, t) => R(
91
- `${o}:${t.join(".")}`,
92
- (n, r) => n.getNestedState(o, t)
93
- ), nt = ({
94
- setState: o,
95
- path: t,
96
- child: n,
90
+ }, H = (n, e) => N(
91
+ `${n}:${e.join(".")}`,
92
+ (t, r) => t.getNestedState(n, e)
93
+ ), te = ({
94
+ setState: n,
95
+ // This is the real effectiveSetState from the hook
96
+ path: e,
97
+ child: t,
97
98
  formOpts: r,
98
- stateKey: e
99
+ stateKey: o
99
100
  }) => {
100
- const [s, i] = N({}), { registerFormRef: u, getFormRef: c } = W.getState(), d = e + "." + t.join("."), a = y(null), T = c(d);
101
- T || u(e + "." + t.join("."), a);
102
- const M = T || a, {
103
- getValidationErrors: U,
104
- addValidationError: z,
105
- getInitialOptions: A,
106
- removeValidationError: w
107
- } = l.getState(), E = H(e, t), [k, C] = N(
108
- l.getState().getNestedState(e, t)
109
- ), m = A(e);
110
- if (!m?.validation?.key)
111
- throw new Error(
112
- "Validation key not found. You need to set it in the options for the createCogsState function"
113
- );
114
- const f = m.validation.key;
115
- m.validation.onBlur, b(() => {
116
- C(E);
117
- }, [e, t.join("."), E]);
118
- const S = y();
119
- let $ = (g, O) => {
120
- C(g), S.current && clearTimeout(S.current), S.current = setTimeout(
101
+ const { registerFormRef: s, getFormRef: i } = O.getState(), {
102
+ getValidationErrors: u,
103
+ addValidationError: c,
104
+ getInitialOptions: f,
105
+ removeValidationError: l
106
+ } = d.getState(), w = o + "." + e.join("."), k = b(null), C = i(w);
107
+ C || s(w, k);
108
+ const A = C || k, S = H(o, e), [E, $] = z(S), y = b(!1), m = b(null);
109
+ j(() => {
110
+ !y.current && S !== E && $(S);
111
+ }, [S]), j(() => () => {
112
+ m.current && (clearTimeout(m.current), y.current = !1);
113
+ }, []);
114
+ const B = (a) => {
115
+ $(a), y.current = !0, m.current && clearTimeout(m.current), m.current = setTimeout(
121
116
  () => {
122
- Z(o, g, t, f);
117
+ y.current = !1, I(n, a, e, g);
123
118
  },
124
- r?.debounceTime ?? (typeof E == "boolean" ? 20 : 200)
119
+ r?.debounceTime ?? (typeof S == "boolean" ? 20 : 200)
125
120
  );
126
- };
127
- const J = async () => {
128
- if (m.validation?.zodSchema) {
129
- w(f + "." + t.join("."));
121
+ }, v = f(o);
122
+ if (!v?.validation?.key)
123
+ throw new Error("Validation key not found.");
124
+ const g = v.validation.key, D = v.validation.onBlur === !0, J = async () => {
125
+ if (m.current && (clearTimeout(m.current), y.current = !1, I(n, E, e, g)), !(!v.validation?.zodSchema || !D)) {
126
+ l(g + "." + e.join("."));
130
127
  try {
131
- const g = l.getState().getNestedState(e, t);
132
- await Y(
133
- f,
134
- m.validation.zodSchema,
135
- t,
136
- g
137
- ), i({});
138
- } catch (g) {
139
- console.error("Validation error:", g);
128
+ const a = d.getState().getNestedState(o, e);
129
+ await W(
130
+ g,
131
+ v.validation.zodSchema,
132
+ e,
133
+ a
134
+ );
135
+ } catch (a) {
136
+ console.error("Validation error on blur:", a);
140
137
  }
141
138
  }
142
- };
143
- b(() => () => {
144
- S.current && clearTimeout(S.current);
145
- }, []);
146
- const j = q(e, t), P = j ? {
147
- ...j,
148
- date: new Date(j.timeStamp)
149
- } : null, D = n({
150
- get: () => k || l.getState().getNestedState(e, t),
151
- set: $,
139
+ }, T = q(o, e), P = T ? { ...T, date: new Date(T.timeStamp) } : null, L = t({
140
+ // --- START CHANGES ---
141
+ get: () => E,
142
+ // Get should return the immediate local value
143
+ set: B,
144
+ // Use the new debounced updater
145
+ // --- END CHANGES ---
152
146
  syncStatus: P,
153
- path: t,
154
- validationErrors: () => U(f + "." + t.join(".")),
155
- addValidationError: (g) => {
156
- w(f + "." + t.join(".")), z(f + "." + t.join("."), g ?? "");
147
+ path: e,
148
+ validationErrors: () => u(g + "." + e.join(".")),
149
+ addValidationError: (a) => {
150
+ l(g + "." + e.join(".")), c(g + "." + e.join("."), a ?? "");
157
151
  },
158
152
  inputProps: {
159
- value: k || l.getState().getNestedState(e, t) || "",
160
- onChange: (g) => $(g.target.value),
153
+ // --- START CHANGES ---
154
+ value: E ?? "",
155
+ // Input value is always the local state
156
+ onChange: (a) => B(a.target.value),
157
+ // Use debounced updater
158
+ // --- END CHANGES ---
161
159
  onBlur: J,
162
- ref: M
160
+ ref: A
163
161
  }
164
162
  });
165
- return /* @__PURE__ */ v(I, { children: /* @__PURE__ */ v(
166
- L,
167
- {
168
- formOpts: r,
169
- path: t,
170
- validationKey: f,
171
- stateKey: e,
172
- children: D
173
- }
174
- ) });
163
+ return /* @__PURE__ */ V(M, { children: /* @__PURE__ */ V(Q, { formOpts: r, path: e, validationKey: g, stateKey: o, children: L }) });
175
164
  };
176
- function L({
177
- formOpts: o,
178
- path: t,
179
- validationKey: n,
165
+ function Q({
166
+ formOpts: n,
167
+ path: e,
168
+ validationKey: t,
180
169
  stateKey: r,
181
- children: e,
170
+ children: o,
182
171
  validIndices: s
183
172
  }) {
184
- const { getInitialOptions: i } = l.getState(), u = _(
185
- n,
173
+ const { getInitialOptions: i } = d.getState(), u = Z(
186
174
  t,
175
+ e,
187
176
  s
188
177
  ), c = [];
189
178
  if (u) {
190
- const a = u.join(", ");
191
- c.includes(a) || c.push(a);
179
+ const l = u.join(", ");
180
+ c.includes(l) || c.push(l);
192
181
  }
193
- const d = i(r);
194
- return /* @__PURE__ */ v(I, { children: d?.formElements?.validation && !o?.validation?.disable ? d.formElements.validation({
195
- children: /* @__PURE__ */ v(G.Fragment, { children: e }, t.toString()),
182
+ const f = i(r);
183
+ return /* @__PURE__ */ V(M, { children: f?.formElements?.validation && !n?.validation?.disable ? f.formElements.validation({
184
+ children: /* @__PURE__ */ V(G.Fragment, { children: o }, e.toString()),
196
185
  active: u.length > 0,
197
- message: o?.validation?.hideMessage ? "" : o?.validation?.message ? o?.validation?.message : c.map((a) => a).join(", "),
198
- path: t,
199
- ...o?.key && { key: o?.key }
200
- }) : /* @__PURE__ */ v(G.Fragment, { children: e }, t.toString()) });
186
+ message: n?.validation?.hideMessage ? "" : n?.validation?.message ? n?.validation?.message : c.map((l) => l).join(", "),
187
+ path: e,
188
+ ...n?.key && { key: n?.key }
189
+ }) : /* @__PURE__ */ V(G.Fragment, { children: o }, e.toString()) });
201
190
  }
202
191
  export {
203
- nt as FormControlComponent,
204
- L as ValidationWrapper,
205
- et as cutFunc,
206
- tt as pushFunc,
207
- Z as updateFn,
192
+ te as FormControlComponent,
193
+ Q as ValidationWrapper,
194
+ ee as cutFunc,
195
+ p as pushFunc,
196
+ I as updateFn,
208
197
  H as useGetKeyState,
209
198
  q as useGetSyncInfo,
210
- _ as useGetValidationErrors,
211
- R as useStoreSubscription
199
+ Z as useGetValidationErrors,
200
+ N as useStoreSubscription
212
201
  };
213
202
  //# sourceMappingURL=Functions.jsx.map
@@ -1 +1 @@
1
- {"version":3,"file":"Functions.jsx","sources":["../src/Functions.tsx"],"sourcesContent":["import {\r\n notifyComponent,\r\n type EffectiveSetState,\r\n type FormElementParams,\r\n type FormOptsType,\r\n type UpdateArg,\r\n type UpdateOpts,\r\n} from \"./CogsState\";\r\n\r\nimport { getNestedValue, isFunction, updateNestedProperty } from \"./utility\";\r\nimport { useEffect, useRef, useState } from \"react\";\r\nimport React from \"react\";\r\nimport { getGlobalStore, formRefStore } from \"./store\";\r\nimport { validateZodPathFunc } from \"./useValidateZodPath\";\r\n\r\nexport function updateFn<U>(\r\n setState: EffectiveSetState<U>,\r\n payload: UpdateArg<U>,\r\n path: string[],\r\n validationKey?: string\r\n): void {\r\n setState(\r\n (prevState) => {\r\n if (isFunction<U>(payload)) {\r\n const nestedValue = payload(getNestedValue(prevState, path));\r\n let value = updateNestedProperty(path, prevState, nestedValue);\r\n if (typeof value == \"string\") {\r\n value = value.trim();\r\n }\r\n return value;\r\n } else {\r\n let value =\r\n !path || path.length == 0\r\n ? payload\r\n : updateNestedProperty(path, prevState, payload);\r\n if (typeof value == \"string\") {\r\n value = value.trim();\r\n }\r\n return value;\r\n }\r\n },\r\n path,\r\n { updateType: \"update\" },\r\n validationKey\r\n );\r\n}\r\n\r\nexport function pushFunc<U>(\r\n setState: EffectiveSetState<U>,\r\n payload: UpdateArg<U>,\r\n path: string[],\r\n stateKey: string,\r\n index?: number\r\n): void {\r\n const array = getGlobalStore.getState().getNestedState(stateKey, path) as U[];\r\n setState(\r\n (prevState) => {\r\n let arrayToUpdate =\r\n !path || path.length == 0\r\n ? prevState\r\n : getNestedValue(prevState, [...path]);\r\n let returnedArray = [...arrayToUpdate];\r\n\r\n returnedArray.splice(\r\n index || Number(index) == 0 ? index : arrayToUpdate.length,\r\n 0,\r\n isFunction<U>(payload)\r\n ? payload(index == -1 ? undefined : arrayToUpdate)\r\n : payload\r\n );\r\n const value =\r\n path.length == 0\r\n ? returnedArray\r\n : updateNestedProperty([...path], prevState, returnedArray);\r\n\r\n return value as U;\r\n },\r\n [\r\n ...path,\r\n index || index === 0 ? index?.toString() : (array!.length - 1).toString(),\r\n ],\r\n {\r\n updateType: \"insert\",\r\n }\r\n );\r\n}\r\n\r\nexport function cutFunc<U>(\r\n setState: EffectiveSetState<U>,\r\n path: string[],\r\n stateKey: string,\r\n index: number\r\n): void {\r\n const array = getGlobalStore.getState().getNestedState(stateKey, path) as U[];\r\n setState(\r\n (prevState) => {\r\n const arrayToUpdate = getNestedValue(prevState, [...path]);\r\n if (index < 0 || index >= arrayToUpdate?.length) {\r\n throw new Error(`Index ${index} does not exist in the array.`);\r\n }\r\n const indexToCut =\r\n index || Number(index) == 0 ? index : arrayToUpdate.length - 1;\r\n\r\n const updatedArray = [\r\n ...arrayToUpdate.slice(0, indexToCut),\r\n ...arrayToUpdate.slice(indexToCut + 1),\r\n ] as U;\r\n\r\n return path.length == 0\r\n ? updatedArray\r\n : updateNestedProperty([...path], prevState, updatedArray);\r\n },\r\n [\r\n ...path,\r\n index || index === 0 ? index?.toString() : (array!.length - 1).toString(),\r\n ],\r\n { updateType: \"cut\" }\r\n );\r\n}\r\n\r\nexport const useStoreSubscription = <T,>(\r\n fullPath: string,\r\n selector: (\r\n store: ReturnType<typeof getGlobalStore.getState>,\r\n path: string\r\n ) => T,\r\n compare: (a: T, b: T) => boolean = (a, b) =>\r\n JSON.stringify(a) === JSON.stringify(b)\r\n) => {\r\n const [value, setValue] = useState<T>(() =>\r\n selector(getGlobalStore.getState(), fullPath)\r\n );\r\n const previousValueRef = useRef<T>(value);\r\n const fullPathRef = useRef(fullPath);\r\n useEffect(() => {\r\n fullPathRef.current = fullPath; // Ensure latest fullPath is always used\r\n\r\n setValue(selector(getGlobalStore.getState(), fullPath));\r\n\r\n const callback = (store: any) => {\r\n const newValue = selector(store, fullPathRef.current);\r\n\r\n if (!compare(previousValueRef.current, newValue)) {\r\n previousValueRef.current = newValue;\r\n setValue(newValue);\r\n }\r\n };\r\n const unsubscribe = getGlobalStore.subscribe(callback);\r\n return () => {\r\n unsubscribe();\r\n };\r\n }, [fullPath]);\r\n return value;\r\n};\r\nexport const useGetValidationErrors = (\r\n validationKey: string,\r\n path: string[],\r\n validIndices?: number[]\r\n) => {\r\n const fullPath =\r\n validationKey +\r\n \".\" +\r\n (path.length > 0 ? [path.join(\".\")] : []) +\r\n (validIndices && validIndices.length > 0 ? \".\" + validIndices : \"\");\r\n\r\n const returnresult = useStoreSubscription(\r\n fullPath,\r\n (store, path) => store.getValidationErrors(path) || []\r\n );\r\n\r\n return returnresult;\r\n};\r\n\r\nexport const useGetSyncInfo = (key: string, path: string[]) => {\r\n const syncKey = `${key}:${path.join(\".\")}`;\r\n return useStoreSubscription(syncKey, (store, path) =>\r\n store.getSyncInfo(path)\r\n );\r\n};\r\nexport const useGetKeyState = (key: string, path: string[]) => {\r\n return useStoreSubscription(`${key}:${path.join(\".\")}`, (store, fullPath) =>\r\n store.getNestedState(key, path)\r\n );\r\n};\r\ninterface FormControlComponentProps<TStateObject> {\r\n setState: EffectiveSetState<TStateObject>;\r\n\r\n path: string[];\r\n child: (obj: FormElementParams<TStateObject>) => JSX.Element;\r\n formOpts?: FormOptsType;\r\n stateKey: string;\r\n}\r\n\r\nexport const FormControlComponent = <TStateObject,>({\r\n setState,\r\n path,\r\n child,\r\n formOpts,\r\n stateKey,\r\n}: FormControlComponentProps<TStateObject>) => {\r\n const [_, forceUpdate] = useState({});\r\n const { registerFormRef, getFormRef } = formRefStore.getState();\r\n const refKey = stateKey + \".\" + path.join(\".\");\r\n\r\n // Create a local ref\r\n const localFormRef = useRef<HTMLInputElement>(null);\r\n\r\n // Get existing ref from the store (if any)\r\n const existingRef = getFormRef(refKey);\r\n if (!existingRef) {\r\n registerFormRef(stateKey + \".\" + path.join(\".\"), localFormRef);\r\n }\r\n // Use the existing ref if available, otherwise use the local one\r\n const formRef = existingRef || localFormRef;\r\n\r\n const {\r\n getValidationErrors,\r\n addValidationError,\r\n getInitialOptions,\r\n removeValidationError,\r\n } = getGlobalStore.getState();\r\n const stateValue = useGetKeyState(stateKey, path);\r\n const [inputValue, setInputValue] = useState<any>(\r\n getGlobalStore.getState().getNestedState(stateKey, path)\r\n );\r\n\r\n const initialOptions = getInitialOptions(stateKey);\r\n\r\n if (!initialOptions?.validation?.key) {\r\n throw new Error(\r\n \"Validation key not found. You need to set it in the options for the createCogsState function\"\r\n );\r\n }\r\n const validationKey = initialOptions.validation.key;\r\n const validateOnBlur = initialOptions.validation.onBlur === true;\r\n initialOptions;\r\n useEffect(() => {\r\n setInputValue(stateValue);\r\n }, [stateKey, path.join(\".\"), stateValue]);\r\n\r\n const timeoutRef = useRef<NodeJS.Timeout>();\r\n\r\n // Standard updater function (unchanged)\r\n let updater = (\r\n payload: UpdateArg<TStateObject>,\r\n opts?: UpdateOpts<TStateObject>\r\n ) => {\r\n setInputValue(payload);\r\n\r\n if (timeoutRef.current) {\r\n clearTimeout(timeoutRef.current);\r\n }\r\n\r\n timeoutRef.current = setTimeout(\r\n () => {\r\n updateFn(setState, payload, path, validationKey);\r\n },\r\n formOpts?.debounceTime ?? (typeof stateValue == \"boolean\" ? 20 : 200)\r\n );\r\n };\r\n\r\n // Handle blur event\r\n const handleBlur = async () => {\r\n if (!initialOptions.validation?.zodSchema) return;\r\n removeValidationError(validationKey + \".\" + path.join(\".\"));\r\n try {\r\n // Get the current field value\r\n const fieldValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Use your existing validateZodPathFunc\r\n await validateZodPathFunc(\r\n validationKey,\r\n initialOptions.validation.zodSchema,\r\n path,\r\n fieldValue\r\n );\r\n\r\n forceUpdate({});\r\n } catch (error) {\r\n console.error(\"Validation error:\", error);\r\n }\r\n };\r\n\r\n // Clear timeout on unmount\r\n useEffect(() => {\r\n return () => {\r\n if (timeoutRef.current) {\r\n clearTimeout(timeoutRef.current);\r\n }\r\n };\r\n }, []);\r\n\r\n const rawSyncStatus = useGetSyncInfo(stateKey, path);\r\n const syncStatus = rawSyncStatus\r\n ? {\r\n ...rawSyncStatus,\r\n date: new Date(rawSyncStatus.timeStamp),\r\n }\r\n : null;\r\n\r\n const childElement = child({\r\n get: () =>\r\n inputValue || getGlobalStore.getState().getNestedState(stateKey, path),\r\n set: updater,\r\n syncStatus,\r\n path: path,\r\n validationErrors: () =>\r\n getValidationErrors(validationKey + \".\" + path.join(\".\")),\r\n addValidationError: (message?: string) => {\r\n removeValidationError(validationKey + \".\" + path.join(\".\"));\r\n addValidationError(validationKey + \".\" + path.join(\".\"), message ?? \"\");\r\n },\r\n\r\n inputProps: {\r\n value:\r\n inputValue ||\r\n getGlobalStore.getState().getNestedState(stateKey, path) ||\r\n \"\",\r\n onChange: (e: any) => updater(e.target.value),\r\n onBlur: handleBlur,\r\n ref: formRef,\r\n },\r\n });\r\n\r\n return (\r\n <>\r\n <ValidationWrapper\r\n {...{\r\n formOpts,\r\n path,\r\n validationKey,\r\n stateKey,\r\n }}\r\n >\r\n {childElement}\r\n </ValidationWrapper>\r\n </>\r\n );\r\n};\r\nexport function ValidationWrapper({\r\n formOpts,\r\n path,\r\n validationKey,\r\n stateKey,\r\n children,\r\n validIndices,\r\n}: {\r\n formOpts?: FormOptsType;\r\n path: string[];\r\n validationKey: string;\r\n stateKey?: string;\r\n children: React.ReactNode;\r\n validIndices?: number[];\r\n}) {\r\n const { getInitialOptions } = getGlobalStore.getState();\r\n\r\n const validationErrors = useGetValidationErrors(\r\n validationKey,\r\n path,\r\n validIndices\r\n );\r\n // console.log(\r\n // \"validationErrors ValidationWrapper\",\r\n // stateKey,\r\n // validationKey,\r\n // path,\r\n // validationErrors\r\n // );\r\n const thesMessages: string[] = [];\r\n\r\n if (validationErrors) {\r\n const newMessage = validationErrors!.join(\", \");\r\n if (!thesMessages.includes(newMessage)) {\r\n thesMessages.push(newMessage);\r\n }\r\n }\r\n const thisStateOpts = getInitialOptions(stateKey!);\r\n\r\n return (\r\n <>\r\n {thisStateOpts?.formElements?.validation &&\r\n !formOpts?.validation?.disable ? (\r\n thisStateOpts.formElements!.validation!({\r\n children: (\r\n <React.Fragment key={path.toString()}>{children}</React.Fragment>\r\n ),\r\n active: validationErrors.length > 0 ? true : false,\r\n message: formOpts?.validation?.hideMessage\r\n ? \"\"\r\n : formOpts?.validation?.message\r\n ? formOpts?.validation?.message\r\n : thesMessages.map((m) => m).join(\", \"),\r\n path: path,\r\n\r\n ...(formOpts?.key && { key: formOpts?.key }),\r\n })\r\n ) : (\r\n <React.Fragment key={path.toString()}>{children}</React.Fragment>\r\n )}\r\n </>\r\n );\r\n}\r\n"],"names":["updateFn","setState","payload","path","validationKey","prevState","isFunction","nestedValue","getNestedValue","value","updateNestedProperty","pushFunc","stateKey","index","array","getGlobalStore","arrayToUpdate","returnedArray","cutFunc","indexToCut","updatedArray","useStoreSubscription","fullPath","selector","compare","a","b","setValue","useState","previousValueRef","useRef","fullPathRef","useEffect","callback","store","newValue","unsubscribe","useGetValidationErrors","validIndices","useGetSyncInfo","key","syncKey","useGetKeyState","FormControlComponent","child","formOpts","_","forceUpdate","registerFormRef","getFormRef","formRefStore","refKey","localFormRef","existingRef","formRef","getValidationErrors","addValidationError","getInitialOptions","removeValidationError","stateValue","inputValue","setInputValue","initialOptions","timeoutRef","updater","opts","handleBlur","fieldValue","validateZodPathFunc","error","rawSyncStatus","syncStatus","childElement","message","e","jsx","Fragment","ValidationWrapper","children","validationErrors","thesMessages","newMessage","thisStateOpts","React","m"],"mappings":";;;;;;AAeO,SAASA,EACdC,GACAC,GACAC,GACAC,GACM;AACN,EAAAH;AAAA,IACE,CAACI,MAAc;AACT,UAAAC,EAAcJ,CAAO,GAAG;AAC1B,cAAMK,IAAcL,EAAQM,EAAeH,GAAWF,CAAI,CAAC;AAC3D,YAAIM,IAAQC,EAAqBP,GAAME,GAAWE,CAAW;AACzD,eAAA,OAAOE,KAAS,aAClBA,IAAQA,EAAM,KAAK,IAEdA;AAAA,MAAA,OACF;AACD,YAAAA,IACF,CAACN,KAAQA,EAAK,UAAU,IACpBD,IACAQ,EAAqBP,GAAME,GAAWH,CAAO;AAC/C,eAAA,OAAOO,KAAS,aAClBA,IAAQA,EAAM,KAAK,IAEdA;AAAA,MAAA;AAAA,IAEX;AAAA,IACAN;AAAA,IACA,EAAE,YAAY,SAAS;AAAA,IACvBC;AAAA,EACF;AACF;AAEO,SAASO,GACdV,GACAC,GACAC,GACAS,GACAC,G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ClC,SAASlC,GAAU,YAAY,cAC3B,KACAA,GAAU,YAAY,UACpBA,GAAU,YAAY,UACtBmC,EAAa,IAAI,CAACI,MAAMA,CAAC,EAAE,KAAK,IAAI;AAAA,IAC1C,MAAAjF;AAAA,IAEA,GAAI0C,GAAU,OAAO,EAAE,KAAKA,GAAU,IAAI;AAAA,EAAA,CAC3C,IAED,gBAAA8B,EAACQ,EAAM,UAAN,EAAsC,UAAAL,EAAlB,GAAA3E,EAAK,SAAsB,CAAA,GAEpD;AAEJ;"}
1
+ {"version":3,"file":"Functions.jsx","sources":["../src/Functions.tsx"],"sourcesContent":["import {\r\n notifyComponent,\r\n type EffectiveSetState,\r\n type FormElementParams,\r\n type FormOptsType,\r\n type UpdateArg,\r\n type UpdateOpts,\r\n} from \"./CogsState\";\r\n\r\nimport { getNestedValue, isFunction, updateNestedProperty } from \"./utility\";\r\nimport { useEffect, useRef, useState } from \"react\";\r\nimport React from \"react\";\r\nimport { getGlobalStore, formRefStore } from \"./store\";\r\nimport { validateZodPathFunc } from \"./useValidateZodPath\";\r\n\r\nexport function updateFn<U>(\r\n setState: EffectiveSetState<U>,\r\n payload: UpdateArg<U>,\r\n path: string[],\r\n validationKey?: string\r\n): void {\r\n setState(\r\n (prevState) => {\r\n if (isFunction<U>(payload)) {\r\n const nestedValue = payload(getNestedValue(prevState, path));\r\n let value = updateNestedProperty(path, prevState, nestedValue);\r\n if (typeof value == \"string\") {\r\n value = value.trim();\r\n }\r\n return value;\r\n } else {\r\n let value =\r\n !path || path.length == 0\r\n ? payload\r\n : updateNestedProperty(path, prevState, payload);\r\n if (typeof value == \"string\") {\r\n value = value.trim();\r\n }\r\n return value;\r\n }\r\n },\r\n path,\r\n { updateType: \"update\" },\r\n validationKey\r\n );\r\n}\r\n\r\nexport function pushFunc<U>(\r\n setState: EffectiveSetState<U>,\r\n payload: UpdateArg<U>,\r\n path: string[],\r\n stateKey: string,\r\n index?: number\r\n): void {\r\n const array = getGlobalStore.getState().getNestedState(stateKey, path) as U[];\r\n setState(\r\n (prevState) => {\r\n let arrayToUpdate =\r\n !path || path.length == 0\r\n ? prevState\r\n : getNestedValue(prevState, [...path]);\r\n let returnedArray = [...arrayToUpdate];\r\n\r\n returnedArray.splice(\r\n index || Number(index) == 0 ? index : arrayToUpdate.length,\r\n 0,\r\n isFunction<U>(payload)\r\n ? payload(index == -1 ? undefined : arrayToUpdate)\r\n : payload\r\n );\r\n const value =\r\n path.length == 0\r\n ? returnedArray\r\n : updateNestedProperty([...path], prevState, returnedArray);\r\n\r\n return value as U;\r\n },\r\n [\r\n ...path,\r\n index || index === 0 ? index?.toString() : (array!.length - 1).toString(),\r\n ],\r\n {\r\n updateType: \"insert\",\r\n }\r\n );\r\n}\r\n\r\nexport function cutFunc<U>(\r\n setState: EffectiveSetState<U>,\r\n path: string[],\r\n stateKey: string,\r\n index: number\r\n): void {\r\n const array = getGlobalStore.getState().getNestedState(stateKey, path) as U[];\r\n setState(\r\n (prevState) => {\r\n const arrayToUpdate = getNestedValue(prevState, [...path]);\r\n if (index < 0 || index >= arrayToUpdate?.length) {\r\n throw new Error(`Index ${index} does not exist in the array.`);\r\n }\r\n const indexToCut =\r\n index || Number(index) == 0 ? index : arrayToUpdate.length - 1;\r\n\r\n const updatedArray = [\r\n ...arrayToUpdate.slice(0, indexToCut),\r\n ...arrayToUpdate.slice(indexToCut + 1),\r\n ] as U;\r\n\r\n return path.length == 0\r\n ? updatedArray\r\n : updateNestedProperty([...path], prevState, updatedArray);\r\n },\r\n [\r\n ...path,\r\n index || index === 0 ? index?.toString() : (array!.length - 1).toString(),\r\n ],\r\n { updateType: \"cut\" }\r\n );\r\n}\r\n\r\nexport const useStoreSubscription = <T,>(\r\n fullPath: string,\r\n selector: (\r\n store: ReturnType<typeof getGlobalStore.getState>,\r\n path: string\r\n ) => T,\r\n compare: (a: T, b: T) => boolean = (a, b) =>\r\n JSON.stringify(a) === JSON.stringify(b)\r\n) => {\r\n const [value, setValue] = useState<T>(() =>\r\n selector(getGlobalStore.getState(), fullPath)\r\n );\r\n const previousValueRef = useRef<T>(value);\r\n const fullPathRef = useRef(fullPath);\r\n useEffect(() => {\r\n fullPathRef.current = fullPath; // Ensure latest fullPath is always used\r\n\r\n setValue(selector(getGlobalStore.getState(), fullPath));\r\n\r\n const callback = (store: any) => {\r\n const newValue = selector(store, fullPathRef.current);\r\n\r\n if (!compare(previousValueRef.current, newValue)) {\r\n previousValueRef.current = newValue;\r\n setValue(newValue);\r\n }\r\n };\r\n const unsubscribe = getGlobalStore.subscribe(callback);\r\n return () => {\r\n unsubscribe();\r\n };\r\n }, [fullPath]);\r\n return value;\r\n};\r\nexport const useGetValidationErrors = (\r\n validationKey: string,\r\n path: string[],\r\n validIndices?: number[]\r\n) => {\r\n const fullPath =\r\n validationKey +\r\n \".\" +\r\n (path.length > 0 ? [path.join(\".\")] : []) +\r\n (validIndices && validIndices.length > 0 ? \".\" + validIndices : \"\");\r\n\r\n const returnresult = useStoreSubscription(\r\n fullPath,\r\n (store, path) => store.getValidationErrors(path) || []\r\n );\r\n\r\n return returnresult;\r\n};\r\n\r\nexport const useGetSyncInfo = (key: string, path: string[]) => {\r\n const syncKey = `${key}:${path.join(\".\")}`;\r\n return useStoreSubscription(syncKey, (store, path) =>\r\n store.getSyncInfo(path)\r\n );\r\n};\r\nexport const useGetKeyState = (key: string, path: string[]) => {\r\n return useStoreSubscription(`${key}:${path.join(\".\")}`, (store, fullPath) =>\r\n store.getNestedState(key, path)\r\n );\r\n};\r\ninterface FormControlComponentProps<TStateObject> {\r\n setState: EffectiveSetState<TStateObject>;\r\n\r\n path: string[];\r\n child: (obj: FormElementParams<TStateObject>) => JSX.Element;\r\n formOpts?: FormOptsType;\r\n stateKey: string;\r\n}\r\n// Find FormControlComponent in your Functions.ts or equivalent file\r\n\r\nexport const FormControlComponent = <TStateObject,>({\r\n setState, // This is the real effectiveSetState from the hook\r\n path,\r\n child,\r\n formOpts,\r\n stateKey,\r\n}: FormControlComponentProps<TStateObject>) => {\r\n const { registerFormRef, getFormRef } = formRefStore.getState();\r\n const {\r\n getValidationErrors,\r\n addValidationError,\r\n getInitialOptions,\r\n removeValidationError,\r\n } = getGlobalStore.getState();\r\n\r\n const refKey = stateKey + \".\" + path.join(\".\");\r\n const localFormRef = useRef<HTMLInputElement>(null);\r\n const existingRef = getFormRef(refKey);\r\n if (!existingRef) {\r\n registerFormRef(refKey, localFormRef);\r\n }\r\n const formRef = existingRef || localFormRef;\r\n\r\n // --- START CHANGES ---\r\n\r\n const globalStateValue = useGetKeyState(stateKey, path);\r\n const [localValue, setLocalValue] = useState<any>(globalStateValue);\r\n const isCurrentlyDebouncing = useRef(false);\r\n const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null);\r\n\r\n // Effect to sync local state if global state changes externally\r\n useEffect(() => {\r\n // Only update local if not actively debouncing a local change\r\n if (!isCurrentlyDebouncing.current && globalStateValue !== localValue) {\r\n setLocalValue(globalStateValue);\r\n }\r\n }, [globalStateValue]); // Removed localValue dependency\r\n\r\n // Effect for cleanup\r\n useEffect(() => {\r\n return () => {\r\n if (debounceTimeoutRef.current) {\r\n clearTimeout(debounceTimeoutRef.current);\r\n isCurrentlyDebouncing.current = false;\r\n }\r\n };\r\n }, []);\r\n\r\n const debouncedUpdater = (payload: UpdateArg<TStateObject>) => {\r\n setLocalValue(payload); // Update local state immediately\r\n isCurrentlyDebouncing.current = true; // Mark as debouncing\r\n\r\n if (debounceTimeoutRef.current) {\r\n clearTimeout(debounceTimeoutRef.current);\r\n }\r\n\r\n debounceTimeoutRef.current = setTimeout(\r\n () => {\r\n isCurrentlyDebouncing.current = false; // Debounce finished\r\n // Use the state value AT THE TIME OF THE SETTIMEOUT FIRING\r\n // which `payload` captured via closure is correct.\r\n updateFn(setState, payload, path, validationKey);\r\n },\r\n formOpts?.debounceTime ??\r\n (typeof globalStateValue == \"boolean\" ? 20 : 200)\r\n );\r\n };\r\n\r\n // --- END CHANGES ---\r\n\r\n const initialOptions = getInitialOptions(stateKey);\r\n if (!initialOptions?.validation?.key) {\r\n throw new Error(\"Validation key not found.\");\r\n }\r\n const validationKey = initialOptions.validation.key;\r\n const validateOnBlur = initialOptions.validation.onBlur === true;\r\n\r\n const handleBlur = async () => {\r\n // --- Ensure latest value is flushed if debouncing ---\r\n if (debounceTimeoutRef.current) {\r\n clearTimeout(debounceTimeoutRef.current);\r\n isCurrentlyDebouncing.current = false;\r\n updateFn(setState, localValue, path, validationKey); // Use current localValue\r\n }\r\n // --- End modification ---\r\n\r\n if (!initialOptions.validation?.zodSchema || !validateOnBlur) return;\r\n removeValidationError(validationKey + \".\" + path.join(\".\"));\r\n try {\r\n // Use the potentially just flushed value\r\n const fieldValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n await validateZodPathFunc(\r\n validationKey,\r\n initialOptions.validation.zodSchema,\r\n path,\r\n fieldValue\r\n );\r\n // forceUpdate might be needed if validation state update doesn't trigger render\r\n // Consider using useGetValidationErrors hook result directly for validation display\r\n } catch (error) {\r\n console.error(\"Validation error on blur:\", error);\r\n }\r\n };\r\n\r\n const rawSyncStatus = useGetSyncInfo(stateKey, path);\r\n const syncStatus = rawSyncStatus\r\n ? { ...rawSyncStatus, date: new Date(rawSyncStatus.timeStamp) }\r\n : null;\r\n\r\n const childElement = child({\r\n // --- START CHANGES ---\r\n get: () => localValue, // Get should return the immediate local value\r\n set: debouncedUpdater, // Use the new debounced updater\r\n // --- END CHANGES ---\r\n syncStatus,\r\n path: path,\r\n validationErrors: () =>\r\n getValidationErrors(validationKey + \".\" + path.join(\".\")),\r\n addValidationError: (message?: string) => {\r\n removeValidationError(validationKey + \".\" + path.join(\".\"));\r\n addValidationError(validationKey + \".\" + path.join(\".\"), message ?? \"\");\r\n },\r\n inputProps: {\r\n // --- START CHANGES ---\r\n value: localValue ?? \"\", // Input value is always the local state\r\n onChange: (e: any) => debouncedUpdater(e.target.value), // Use debounced updater\r\n // --- END CHANGES ---\r\n onBlur: handleBlur,\r\n ref: formRef,\r\n },\r\n });\r\n\r\n return (\r\n <>\r\n <ValidationWrapper {...{ formOpts, path, validationKey, stateKey }}>\r\n {childElement}\r\n </ValidationWrapper>\r\n </>\r\n );\r\n};\r\nexport function ValidationWrapper({\r\n formOpts,\r\n path,\r\n validationKey,\r\n stateKey,\r\n children,\r\n validIndices,\r\n}: {\r\n formOpts?: FormOptsType;\r\n path: string[];\r\n validationKey: string;\r\n stateKey?: string;\r\n children: React.ReactNode;\r\n validIndices?: number[];\r\n}) {\r\n const { getInitialOptions } = getGlobalStore.getState();\r\n\r\n const validationErrors = useGetValidationErrors(\r\n validationKey,\r\n path,\r\n validIndices\r\n );\r\n // console.log(\r\n // \"validationErrors ValidationWrapper\",\r\n // stateKey,\r\n // validationKey,\r\n // path,\r\n // validationErrors\r\n // );\r\n const thesMessages: string[] = [];\r\n\r\n if (validationErrors) {\r\n const newMessage = validationErrors!.join(\", \");\r\n if (!thesMessages.includes(newMessage)) {\r\n thesMessages.push(newMessage);\r\n }\r\n }\r\n const thisStateOpts = getInitialOptions(stateKey!);\r\n\r\n return (\r\n <>\r\n {thisStateOpts?.formElements?.validation &&\r\n !formOpts?.validation?.disable ? (\r\n thisStateOpts.formElements!.validation!({\r\n children: (\r\n <React.Fragment key={path.toString()}>{children}</React.Fragment>\r\n ),\r\n active: validationErrors.length > 0 ? true : false,\r\n message: formOpts?.validation?.hideMessage\r\n ? \"\"\r\n : formOpts?.validation?.message\r\n ? formOpts?.validation?.message\r\n : thesMessages.map((m) => m).join(\", \"),\r\n path: path,\r\n\r\n ...(formOpts?.key && { key: formOpts?.key }),\r\n })\r\n ) : (\r\n <React.Fragment key={path.toString()}>{children}</React.Fragment>\r\n )}\r\n </>\r\n );\r\n}\r\n"],"names":["updateFn","setState","payload","path","validationKey","prevState","isFunction","nestedValue","getNestedValue","value","updateNestedProperty","pushFunc","stateKey","index","array","getGlobalStore","arrayToUpdate","returnedArray","cutFunc","indexToCut","updatedArray","useStoreSubscription","fullPath","selector","compare","a","b","setValue","useState","previousValueRef","useRef","fullPathRef","useEffect","callback","store","newValue","unsubscribe","useGetValidationErrors","validIndices","useGetSyncInfo","key","syncKey","useGetKeyState","FormControlComponent","child","formOpts","registerFormRef","getFormRef","formRefStore","getValidationErrors","addValidationError","getInitialOptions","removeValidationError","refKey","localFormRef","existingRef","formRef","globalStateValue","localValue","setLocalValue","isCurrentlyDebouncing","debounceTimeoutRef","debouncedUpdater","initialOptions","validateOnBlur","handleBlur","fieldValue","validateZodPathFunc","error","rawSyncStatus","syncStatus","childElement","message","e","jsx","Fragment","ValidationWrapper","children","validationErrors","thesMessages","newMessage","thisStateOpts","React","m"],"mappings":";;;;;;AAeO,SAASA,EACdC,GACAC,GACAC,GACAC,GACM;AACN,EAAAH;AAAA,IACE,CAACI,MAAc;AACT,UAAAC,EAAcJ,CAAO,GAAG;AAC1B,cAAMK,IAAcL,EAAQM,EAAeH,GAAWF,CAAI,CAAC;AAC3D,YAAIM,IAAQC,EAAqBP,GAAME,GAAWE,CAAW;AACzD,eAAA,OAAOE,KAAS,aAClBA,IAAQA,EAAM,KAAK,IAEdA;AAAA,MAAA,OACF;AACD,YAAAA,IACF,CAACN,KAAQA,EAAK,UAAU,IACpBD,IACAQ,EAAqBP,GAAME,GAAWH,CAAO;AAC/C,eAAA,OAAOO,KAAS,aAClBA,IAAQA,EAAM,KAAK,IAEdA;AAAA,MAAA;AAAA,IAEX;AAAA,IACAN;AAAA,IACA,EAAE,YAAY,SAAS;AAAA,IACvBC;AAAA,EACF;AACF;AAEO,SAASO,EACdV,GACAC,GACAC,GACAS,GACAC,GACM;AACN,QAAMC,IAAQC,EAAe,SAAW,EAAA,eAAeH,GAAUT,CAAI;AACrE,EAAAF;AAAA,IACE,CAACI,MAAc;AACb,UAAIW,IACF,CAACb,KAAQA,EAAK,UAAU,IACpBE,IACAG,EAAeH,GAAW,CAAC,GAAGF,CAAI,CAAC,GACrCc,IAAgB,CAAC,GAAGD,CAAa;AAEvB,aAAAC,EAAA;AAAA,QAC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E,EAAK,SAAsB,CAAA,GAEpD;AAEJ;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cogsbox-state",
3
- "version": "0.5.126",
3
+ "version": "0.5.127",
4
4
  "description": "React state management library with form controls and server sync",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",