Client State
state.js is an in-memory key-value store. It's the reason the "no diffing" design works at all.
Storage model
- A single
Map<string, string>; values areJSON.stringify'd strings. - Memory only: never touches
sessionStorage/localStorage. - The real key is
<object name>:<key>; keys prefixed with@are global (@theme→theme).
How long it lives
- Other tabs can't see it.
- A reload always resets it. On purpose: this is not a draft-saving mechanism.
JS API
Only code inside the bundle (CGEvents) imports it. Templates should use declarative bindings.
js
import state from '../state.js';
const s = state.scope('customerPanel');
s.set('keyword', 'acme');
s.get('keyword', ''); // deep copy
s.merge('filters', { sort: 'id' });
s.update('tags', (t = []) => t.concat('vip'));
s.remove('keyword');
s.clear(); // clears this namespace only
const off = s.subscribe('keyword', (value, key, previous) => { /* ... */ });
off(); // hand-written subscriptions must be released| Method | Notifies subscribers | Notes |
|---|---|---|
get(key, fallback) | — | Returns a deep copy; mutating it doesn't affect the store |
set(key, value) | ✅ | undefined means remove; returns false if not serializable |
merge(key, patch) | ✅ | Shallow merge |
update(key, fn) | ✅ | Writes back fn(current) |
remove(key) | ✅ | Only notifies if a value existed |
clear() | ✅ one by one | Scoped version clears only its own keys |
subscribe(key, fn) | — | '*' receives everything; returns off() |
Value rules
| Case | Behavior |
|---|---|
Objects, arrays, strings, numbers, booleans, null | Normal |
undefined | Same as delete |
Functions, Map, Set, circular references | Warns and does not write |
Date | Comes back as an ISO string |
s.get('o').x = 1 | Does not reach the store; use merge |
No equality check
Writing the same value still notifies and re-renders. A subscriber that writes back to the same key loops forever.
What may go in
Yes: tabs, expand/collapse, filters, sort order, page numbers, scroll position, unsaved input, the current wizard step.
No: permissions, amounts, cart contents, anything the server must trust, passwords, File objects.
When to clear it yourself
| When | How |
|---|---|
| After a successful save | scope.clear(), otherwise old input overwrites the server's new values |
| Switching to a different record | scope.clear(), or use a different object name |
| Logout | Nothing to do; full navigation clears it on pagehide |
Linker can clear it too: ->then('state.clear', ['scope' => 'customerForm']).
Watching every change
js
document.addEventListener('cg:state', e => console.log('state', e.detail.key, '→', e.detail.value));