@20baht/store 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/dist/index.d.ts +27 -0
- package/dist/index.js +283 -0
- package/dist/react.d.ts +10 -0
- package/dist/react.js +20 -0
- package/package.json +66 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nattapong Promthong
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,92 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @20baht/store
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Tiny key-value state adapter for [bahtui](https://github.com/bank20baht/20baht) forms.
|
|
4
|
+
Bind once, then read and write form data from anywhere in your app with plain refs.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm i @20baht/store
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Quick start
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
import { createBahtStore } from '@20baht/store';
|
|
14
|
+
|
|
15
|
+
const store = createBahtStore();
|
|
16
|
+
store.bind(document.querySelector('baht-workflow')); // or a <baht-form>
|
|
17
|
+
|
|
18
|
+
// read — same ref shape the engine speaks
|
|
19
|
+
store.get('Form_1.age'); // 31
|
|
20
|
+
store.get('Form_1.items[0].qty'); // repeater rows too
|
|
21
|
+
store.get(); // the whole tree
|
|
22
|
+
|
|
23
|
+
// write — the UI updates in place (no step reset, no focus loss)
|
|
24
|
+
store.set('Form_1.age', 32);
|
|
25
|
+
store.set('Form_1.items[0].qty', 5);
|
|
26
|
+
|
|
27
|
+
// react to changes
|
|
28
|
+
const off = store.subscribe((data) => console.log(data));
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
- `bind()` pulls the element's current data immediately and keeps both sides in
|
|
32
|
+
sync: user edits land in the store, `set()` lands in the UI. Returns an
|
|
33
|
+
unbind function.
|
|
34
|
+
- `<baht-form>` stores flat data at the root (`store.get('age')`);
|
|
35
|
+
`<baht-workflow>` stores `{form_name: {key: value}}`.
|
|
36
|
+
- Also on the store: `patch(partial)` (root merge), `replace(data)`, `reset()`.
|
|
37
|
+
- Updates are immutable — untouched subtrees keep their identity, so snapshots
|
|
38
|
+
are cheap to diff/memoize.
|
|
39
|
+
|
|
40
|
+
## React
|
|
41
|
+
|
|
42
|
+
```jsx
|
|
43
|
+
import { useBahtStore, useBahtValue } from '@20baht/store/react';
|
|
44
|
+
|
|
45
|
+
function Sidebar({ store }) {
|
|
46
|
+
const [age, setAge] = useBahtValue(store, 'Form_1.age'); // re-renders only on that ref
|
|
47
|
+
const data = useBahtStore(store); // the whole tree
|
|
48
|
+
return <button onClick={() => setAge(Number(age) + 1)}>age {String(age)}</button>;
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
React is an optional peer dependency — the core store has no framework code.
|
|
53
|
+
|
|
54
|
+
## Angular (signals)
|
|
55
|
+
|
|
56
|
+
No adapter needed — a signal that re-reads the store on every change is a few lines:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { DestroyRef, inject, signal, type Signal } from '@angular/core';
|
|
60
|
+
import type { BahtStore } from '@20baht/store';
|
|
61
|
+
|
|
62
|
+
export function bahtSignal<T = unknown>(store: BahtStore, ref?: string): Signal<T> {
|
|
63
|
+
const read = () => (ref === undefined ? store.get() : store.get(ref)) as T;
|
|
64
|
+
const value = signal<T>(read());
|
|
65
|
+
inject(DestroyRef).onDestroy(store.subscribe(() => value.set(read())));
|
|
66
|
+
return value.asReadonly();
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Binding from a component wrapping `<baht-form>`:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
readonly store = createBahtStore();
|
|
74
|
+
readonly data = bahtSignal<Record<string, unknown>>(this.store);
|
|
75
|
+
|
|
76
|
+
constructor() {
|
|
77
|
+
afterNextRender(async () => {
|
|
78
|
+
await customElements.whenDefined('baht-form'); // never resolves in unit tests — fine
|
|
79
|
+
const el = this.el().nativeElement;
|
|
80
|
+
el.value = this.value(); // initial host values go on the element …
|
|
81
|
+
await el.updateComplete; // … and bind() only after its first render
|
|
82
|
+
this.unbind = this.store.bind(el);
|
|
83
|
+
});
|
|
84
|
+
// … later host values go through the store, or it goes stale
|
|
85
|
+
effect(() => { if (this.bound) this.store.replace(this.value()); });
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Two things worth knowing: `bind()` merges the element's current data *over* the store, so seed
|
|
90
|
+
the element (not the store) with initial values; and re-feeding the element's `value` prop
|
|
91
|
+
directly after binding leaves the store one edit behind — push through `store.replace()` /
|
|
92
|
+
`store.set()` instead. Autosave is then `store.subscribe((d) => localStorage.setItem(key, JSON.stringify(d)))`.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export type Seg = string | number;
|
|
2
|
+
/** 'Form_1.items[0].qty' -> ['Form_1', 'items', 0, 'qty'] */
|
|
3
|
+
export declare function parseRef(ref: string): Seg[];
|
|
4
|
+
export declare function getPath(obj: unknown, path: Seg[]): unknown;
|
|
5
|
+
/** Immutable write: clones only the spine, reuses every untouched sibling. */
|
|
6
|
+
export declare function setPath(obj: unknown, path: Seg[], value: unknown): unknown;
|
|
7
|
+
export interface BahtStore {
|
|
8
|
+
/** Whole tree (stable identity between changes) or one ref's value. */
|
|
9
|
+
get(): Record<string, unknown>;
|
|
10
|
+
get(ref: string): unknown;
|
|
11
|
+
/** Write one ref — subscribers fire, bound elements update in place. */
|
|
12
|
+
set(ref: string, value: unknown): void;
|
|
13
|
+
/** Shallow-merge at the root. */
|
|
14
|
+
patch(partial: Record<string, unknown>): void;
|
|
15
|
+
/** Swap the whole tree. */
|
|
16
|
+
replace(data: Record<string, unknown>): void;
|
|
17
|
+
/** Back to the initial data the store was created with. */
|
|
18
|
+
reset(): void;
|
|
19
|
+
subscribe: (listener: (data: Record<string, unknown>) => void) => () => void;
|
|
20
|
+
/**
|
|
21
|
+
* Two-way sync with a <baht-form> (flat data at the root) or
|
|
22
|
+
* <baht-workflow> ({form_name: {key: value}}). Pulls the element's current
|
|
23
|
+
* data immediately; returns an unbind function.
|
|
24
|
+
*/
|
|
25
|
+
bind(el: HTMLElement): () => void;
|
|
26
|
+
}
|
|
27
|
+
export declare function createBahtStore(initial?: Record<string, unknown>): BahtStore;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// @20baht/store — tiny key-value state adapter for bahtui forms.
|
|
3
|
+
//
|
|
4
|
+
// One store, refs in the same shape the engine already speaks:
|
|
5
|
+
//
|
|
6
|
+
// const store = createBahtStore();
|
|
7
|
+
// store.bind(document.querySelector('baht-workflow'));
|
|
8
|
+
// store.get('Form_1.age'); // read anywhere
|
|
9
|
+
// store.set('Form_1.age', 31); // write anywhere — UI updates, no step reset
|
|
10
|
+
// store.subscribe((data) => ...); // react to every change
|
|
11
|
+
//
|
|
12
|
+
// Framework-agnostic core; a React hook lives at '@20baht/store/react'.
|
|
13
|
+
// Types-only dependency on @20baht/ui — binding is duck-typed, so this
|
|
14
|
+
// module never registers custom elements or touches the DOM until bind().
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
/** Segments that would reach off the plain-data object graph onto Object.prototype. */
|
|
17
|
+
const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
18
|
+
/** 'Form_1.items[0].qty' -> ['Form_1', 'items', 0, 'qty'] */
|
|
19
|
+
export function parseRef(ref) {
|
|
20
|
+
const out = [];
|
|
21
|
+
for (const part of ref.split('.')) {
|
|
22
|
+
const m = /^([^[\]]+)((\[\d+\])*)$/.exec(part);
|
|
23
|
+
if (!m)
|
|
24
|
+
throw new Error(`bad ref segment ${JSON.stringify(part)} in ${JSON.stringify(ref)}`);
|
|
25
|
+
const key = m[1];
|
|
26
|
+
if (UNSAFE_KEYS.has(key)) {
|
|
27
|
+
throw new Error(`bad ref segment ${JSON.stringify(key)} in ${JSON.stringify(ref)}: "__proto__", "constructor" and "prototype" are not allowed`);
|
|
28
|
+
}
|
|
29
|
+
out.push(key);
|
|
30
|
+
for (const idx of m[2].matchAll(/\[(\d+)\]/g))
|
|
31
|
+
out.push(Number(idx[1]));
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
/** True when `seg` addresses an array element (a non-negative integer index). */
|
|
36
|
+
function isIndex(seg) {
|
|
37
|
+
return typeof seg === 'number' || /^\d+$/.test(seg);
|
|
38
|
+
}
|
|
39
|
+
export function getPath(obj, path) {
|
|
40
|
+
let cur = obj;
|
|
41
|
+
for (const seg of path) {
|
|
42
|
+
if (cur === null || typeof cur !== 'object')
|
|
43
|
+
return undefined;
|
|
44
|
+
// Own properties only — walking the prototype chain would leak things like
|
|
45
|
+
// `constructor` and let a ref read past the plain-data object graph.
|
|
46
|
+
if (!Object.hasOwn(cur, seg))
|
|
47
|
+
return undefined;
|
|
48
|
+
cur = cur[seg];
|
|
49
|
+
}
|
|
50
|
+
return cur;
|
|
51
|
+
}
|
|
52
|
+
const isArray = (v) => Array.isArray(v);
|
|
53
|
+
/** Immutable write: clones only the spine, reuses every untouched sibling. */
|
|
54
|
+
export function setPath(obj, path, value) {
|
|
55
|
+
if (path.length === 0)
|
|
56
|
+
return value;
|
|
57
|
+
const [head, ...rest] = path;
|
|
58
|
+
const headIsIndex = isIndex(head);
|
|
59
|
+
const container = obj !== null && typeof obj === 'object' ? obj : headIsIndex ? [] : {};
|
|
60
|
+
if (isArray(container) && headIsIndex) {
|
|
61
|
+
const idx = Number(head);
|
|
62
|
+
const copy = [...container];
|
|
63
|
+
copy[idx] = setPath(copy[idx], rest, value);
|
|
64
|
+
return copy;
|
|
65
|
+
}
|
|
66
|
+
// A non-index segment against an array container (e.g. 'tags.name' where tags is
|
|
67
|
+
// an array) can't address an element — fall back to a plain object instead of
|
|
68
|
+
// coercing Number(head) into a stray "NaN" property.
|
|
69
|
+
// eslint-disable-next-line @typescript-eslint/no-misused-spread -- intentional: the array's elements become index keys of the fallback object
|
|
70
|
+
const rec = (Array.isArray(container) ? { ...container } : container);
|
|
71
|
+
return { ...rec, [head]: setPath(rec[String(head)], rest, value) };
|
|
72
|
+
}
|
|
73
|
+
/** Shallow key/value comparison — good enough to catch a data object that's an echo of itself. */
|
|
74
|
+
function shallowEqual(a, b) {
|
|
75
|
+
const aKeys = Object.keys(a);
|
|
76
|
+
if (aKeys.length !== Object.keys(b).length)
|
|
77
|
+
return false;
|
|
78
|
+
return aKeys.every((k) => Object.is(a[k], b[k]));
|
|
79
|
+
}
|
|
80
|
+
export function createBahtStore(initial = {}) {
|
|
81
|
+
// Cloned once, up front — mutations the caller makes to `initial` afterwards
|
|
82
|
+
// (or that ripple through `data`'s untouched-sibling reuse) must never leak in.
|
|
83
|
+
const initialSnapshot = structuredClone(initial);
|
|
84
|
+
let data = structuredClone(initialSnapshot);
|
|
85
|
+
const listeners = new Set();
|
|
86
|
+
const bindings = new Set();
|
|
87
|
+
/** Set while an element pushes into the store — silences the echo back. */
|
|
88
|
+
let source = null;
|
|
89
|
+
// One throwing listener/binding must not starve the rest — or bubble the
|
|
90
|
+
// failure up into the set()/patch() caller that triggered the commit.
|
|
91
|
+
const notify = () => {
|
|
92
|
+
for (const fn of listeners) {
|
|
93
|
+
try {
|
|
94
|
+
fn(data);
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
console.error('[@20baht/store] subscriber threw', err);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
const fanOut = (push) => {
|
|
102
|
+
for (const b of bindings) {
|
|
103
|
+
if (b === source)
|
|
104
|
+
continue;
|
|
105
|
+
try {
|
|
106
|
+
push(b);
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
console.error('[@20baht/store] bound element update threw', err);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const commit = (next, pushed) => {
|
|
114
|
+
data = next;
|
|
115
|
+
notify();
|
|
116
|
+
fanOut((b) => {
|
|
117
|
+
if (pushed)
|
|
118
|
+
b.push(pushed);
|
|
119
|
+
else
|
|
120
|
+
b.pushAll();
|
|
121
|
+
});
|
|
122
|
+
};
|
|
123
|
+
const store = {
|
|
124
|
+
// object literals can't express overloads — the cast bridges to the interface
|
|
125
|
+
get: ((ref) => ref === undefined ? data : getPath(data, parseRef(ref))),
|
|
126
|
+
set(ref, value) {
|
|
127
|
+
const path = parseRef(ref);
|
|
128
|
+
commit(setPath(data, path, value), path);
|
|
129
|
+
},
|
|
130
|
+
patch(partial) {
|
|
131
|
+
commit({ ...data, ...partial });
|
|
132
|
+
},
|
|
133
|
+
replace(next) {
|
|
134
|
+
commit({ ...next });
|
|
135
|
+
},
|
|
136
|
+
reset() {
|
|
137
|
+
commit(structuredClone(initialSnapshot));
|
|
138
|
+
},
|
|
139
|
+
subscribe(listener) {
|
|
140
|
+
listeners.add(listener);
|
|
141
|
+
return () => listeners.delete(listener);
|
|
142
|
+
},
|
|
143
|
+
bind(el) {
|
|
144
|
+
const tag = el.tagName.toLowerCase();
|
|
145
|
+
if (tag !== 'baht-form' && tag !== 'baht-workflow') {
|
|
146
|
+
throw new Error(`bind() needs a <baht-form> or <baht-workflow>, got <${tag}>`);
|
|
147
|
+
}
|
|
148
|
+
const pusher = tag === 'baht-form'
|
|
149
|
+
? formBinding(el, () => data)
|
|
150
|
+
: workflowBinding(el, () => data);
|
|
151
|
+
const runAsSource = (b, fn) => {
|
|
152
|
+
const prev = source;
|
|
153
|
+
source = b;
|
|
154
|
+
try {
|
|
155
|
+
fn();
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
source = prev;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
const wrapped = {
|
|
162
|
+
push: (path) => {
|
|
163
|
+
runAsSource(wrapped, () => {
|
|
164
|
+
pusher.push(path);
|
|
165
|
+
});
|
|
166
|
+
},
|
|
167
|
+
pushAll: () => {
|
|
168
|
+
runAsSource(wrapped, () => {
|
|
169
|
+
pusher.pushAll();
|
|
170
|
+
});
|
|
171
|
+
},
|
|
172
|
+
unbind: () => {
|
|
173
|
+
el.removeEventListener(eventType, onEvent);
|
|
174
|
+
bindings.delete(wrapped);
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
// element -> store (guarded so our own pushes don't echo)
|
|
178
|
+
const eventType = tag === 'baht-form' ? 'baht-change' : 'baht-data-change';
|
|
179
|
+
const onEvent = (e) => {
|
|
180
|
+
if (source === wrapped)
|
|
181
|
+
return;
|
|
182
|
+
// baht-change bubbles+composed from any descendant — standalone primitives
|
|
183
|
+
// (e.g. baht-rating emitting `{ value }`) reuse the same event name with an
|
|
184
|
+
// unrelated payload shape. Only the bound element's own dispatch is ours.
|
|
185
|
+
if (e.target !== el)
|
|
186
|
+
return;
|
|
187
|
+
const detail = e.detail;
|
|
188
|
+
const next = detail?.data;
|
|
189
|
+
if (next === null || typeof next !== 'object' || Array.isArray(next))
|
|
190
|
+
return;
|
|
191
|
+
const merged = { ...data, ...next };
|
|
192
|
+
// Second echo guard: survives async/late dispatch that outlives the
|
|
193
|
+
// synchronous `source === wrapped` window above.
|
|
194
|
+
if (shallowEqual(merged, data))
|
|
195
|
+
return;
|
|
196
|
+
runAsSource(wrapped, () => {
|
|
197
|
+
commit(merged);
|
|
198
|
+
});
|
|
199
|
+
};
|
|
200
|
+
el.addEventListener(eventType, onEvent);
|
|
201
|
+
bindings.add(wrapped);
|
|
202
|
+
// pull the element's current truth into the store (no echo back), merged
|
|
203
|
+
// over whatever's already there so it never wipes another binding's keys
|
|
204
|
+
// or non-form keys seeded via createBahtStore(initial).
|
|
205
|
+
runAsSource(wrapped, () => {
|
|
206
|
+
commit({ ...data, ...el.getData() });
|
|
207
|
+
});
|
|
208
|
+
return wrapped.unbind;
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
return store;
|
|
212
|
+
}
|
|
213
|
+
// el.setValue() MERGES a patch into the element's own state — it never drops a key
|
|
214
|
+
// that's simply absent from the patch. reset()/replace() can shrink the store's key
|
|
215
|
+
// set, so pushAll() has to explicitly push `undefined` for any key it last pushed
|
|
216
|
+
// that's now gone, or the element keeps showing stale values. Each binding tracks
|
|
217
|
+
// what it last handed the element so it can diff against the new snapshot.
|
|
218
|
+
function formBinding(el, data) {
|
|
219
|
+
let lastSnapshot = { ...el.getData() };
|
|
220
|
+
return {
|
|
221
|
+
push(path) {
|
|
222
|
+
const key = String(path[0]);
|
|
223
|
+
const value = data()[key];
|
|
224
|
+
el.setValue({ [key]: value });
|
|
225
|
+
lastSnapshot = { ...lastSnapshot, [key]: value };
|
|
226
|
+
},
|
|
227
|
+
pushAll() {
|
|
228
|
+
const next = data();
|
|
229
|
+
const patch = { ...next };
|
|
230
|
+
for (const key of Object.keys(lastSnapshot)) {
|
|
231
|
+
if (!Object.hasOwn(next, key))
|
|
232
|
+
patch[key] = undefined;
|
|
233
|
+
}
|
|
234
|
+
el.setValue(patch);
|
|
235
|
+
lastSnapshot = { ...next };
|
|
236
|
+
},
|
|
237
|
+
unbind: () => undefined,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
function workflowBinding(el, data) {
|
|
241
|
+
let lastSnapshot = Object.fromEntries(Object.entries(el.getData()).map(([form_name, values]) => [form_name, { ...values }]));
|
|
242
|
+
return {
|
|
243
|
+
push(path) {
|
|
244
|
+
const form_name = String(path[0]);
|
|
245
|
+
const values = data()[form_name];
|
|
246
|
+
if (values === null || typeof values !== 'object')
|
|
247
|
+
return;
|
|
248
|
+
const rec = values;
|
|
249
|
+
if (path.length >= 2) {
|
|
250
|
+
const key = String(path[1]);
|
|
251
|
+
el.setValue(form_name, { [key]: rec[key] });
|
|
252
|
+
lastSnapshot = {
|
|
253
|
+
...lastSnapshot,
|
|
254
|
+
[form_name]: { ...(lastSnapshot[form_name] ?? {}), [key]: rec[key] },
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
el.setValue(form_name, rec);
|
|
259
|
+
lastSnapshot = { ...lastSnapshot, [form_name]: { ...rec } };
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
pushAll() {
|
|
263
|
+
const next = data();
|
|
264
|
+
const nextSnapshot = {};
|
|
265
|
+
const formNames = new Set([...Object.keys(lastSnapshot), ...Object.keys(next)]);
|
|
266
|
+
for (const form_name of formNames) {
|
|
267
|
+
const values = next[form_name];
|
|
268
|
+
const prev = lastSnapshot[form_name] ?? {};
|
|
269
|
+
const rec = values !== null && typeof values === 'object' ? values : {};
|
|
270
|
+
const patch = { ...rec };
|
|
271
|
+
for (const key of Object.keys(prev)) {
|
|
272
|
+
if (!Object.hasOwn(rec, key))
|
|
273
|
+
patch[key] = undefined;
|
|
274
|
+
}
|
|
275
|
+
if (Object.keys(patch).length > 0)
|
|
276
|
+
el.setValue(form_name, patch);
|
|
277
|
+
nextSnapshot[form_name] = { ...rec };
|
|
278
|
+
}
|
|
279
|
+
lastSnapshot = nextSnapshot;
|
|
280
|
+
},
|
|
281
|
+
unbind: () => undefined,
|
|
282
|
+
};
|
|
283
|
+
}
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { BahtStore } from './index.js';
|
|
2
|
+
/** The whole tree, re-rendering on every store change. */
|
|
3
|
+
export declare function useBahtStore(store: BahtStore): Record<string, unknown>;
|
|
4
|
+
/**
|
|
5
|
+
* One ref as [value, setValue] — re-renders only when THAT subtree changes
|
|
6
|
+
* (immutable updates keep untouched subtrees identity-stable).
|
|
7
|
+
*
|
|
8
|
+
* const [age, setAge] = useBahtValue(store, 'Form_1.age');
|
|
9
|
+
*/
|
|
10
|
+
export declare function useBahtValue(store: BahtStore, ref: string): [unknown, (value: unknown) => void];
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// @20baht/store/react — hooks over the framework-agnostic store.
|
|
2
|
+
// React is an optional peer dep; import this entry only from React apps.
|
|
3
|
+
import { useCallback, useSyncExternalStore } from 'react';
|
|
4
|
+
/** The whole tree, re-rendering on every store change. */
|
|
5
|
+
export function useBahtStore(store) {
|
|
6
|
+
return useSyncExternalStore(store.subscribe, () => store.get(), () => store.get());
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* One ref as [value, setValue] — re-renders only when THAT subtree changes
|
|
10
|
+
* (immutable updates keep untouched subtrees identity-stable).
|
|
11
|
+
*
|
|
12
|
+
* const [age, setAge] = useBahtValue(store, 'Form_1.age');
|
|
13
|
+
*/
|
|
14
|
+
export function useBahtValue(store, ref) {
|
|
15
|
+
const value = useSyncExternalStore(store.subscribe, () => store.get(ref), () => store.get(ref));
|
|
16
|
+
const set = useCallback((v) => {
|
|
17
|
+
store.set(ref, v);
|
|
18
|
+
}, [store, ref]);
|
|
19
|
+
return [value, set];
|
|
20
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@20baht/store",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Tiny key-value state adapter for bahtui forms — get/set by ref (Form_1.age), subscribe, and two-way bind to <baht-form>/<baht-workflow>.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Nattapong Promthong",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/bank20baht/20baht.git",
|
|
11
|
+
"directory": "packages/core/store"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/store#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/bank20baht/20baht/issues"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"forms",
|
|
19
|
+
"workflow",
|
|
20
|
+
"state",
|
|
21
|
+
"store",
|
|
22
|
+
"adapter"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"dist"
|
|
29
|
+
],
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"import": "./dist/index.js",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./react": {
|
|
37
|
+
"types": "./dist/react.d.ts",
|
|
38
|
+
"import": "./dist/react.js",
|
|
39
|
+
"default": "./dist/react.js"
|
|
40
|
+
},
|
|
41
|
+
"./package.json": "./package.json"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "rm -rf dist && tsc -p tsconfig.json",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"test:watch": "vitest",
|
|
47
|
+
"test:coverage": "vitest run --coverage"
|
|
48
|
+
},
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"react": ">=18"
|
|
51
|
+
},
|
|
52
|
+
"peerDependenciesMeta": {
|
|
53
|
+
"react": {
|
|
54
|
+
"optional": true
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"@20baht/ui": "workspace:*",
|
|
59
|
+
"@types/react": "^19.0.0",
|
|
60
|
+
"happy-dom": "^20.0.0",
|
|
61
|
+
"react": "^19.0.0",
|
|
62
|
+
"typescript": "^5.8.3",
|
|
63
|
+
"vitest": "^3.2.4"
|
|
64
|
+
},
|
|
65
|
+
"main": "./dist/index.js",
|
|
66
|
+
"types": "./dist/index.d.ts",
|
|
67
|
+
"sideEffects": false
|
|
68
|
+
}
|