@surfaces-ui/state 0.0.0-stage → 0.3.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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Surfaces UI
2
+ Copyright 2026 Josh Schoen
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-readmes.mjs from package.json. Edit the script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @surfaces-ui/state
4
+
5
+ Reusable state services for Surfaces UI: stores, persistence, URL sync, undo, shared view state and query runs.
6
+
7
+ State services with no React or DOM dependency: stores, derived values, undo, persistence to any `StateStorage`, URL sync, the shared view state behind cross-filtering, and query runs. React hooks are in `@surfaces-ui/state/react`.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @surfaces-ui/state react
13
+ ```
14
+
15
+ `react` is a peer dependency: your app provides it.
16
+
17
+ ## Use
18
+
19
+ ```tsx
20
+ import { browserStorage, createViewState, parseViewState, persist } from "@surfaces-ui/state";
21
+ import { useStore } from "@surfaces-ui/state/react";
22
+
23
+ const view = createViewState();
24
+ persist(view, { key: "dashboard", storage: browserStorage(), parse: parseViewState });
25
+
26
+ // In a chart: view.toggle("region", "EU") on a click, and filters={view.filters("region")}
27
+ // so the chart never filters away the bars a person clicks.
28
+ ```
29
+
30
+ ## Part of Surfaces UI
31
+
32
+ Surfaces UI is a UI library for data and analytics: exploring schemas, querying, charting, tables at scale, chat, and pages an agent can build.
33
+
34
+ Every Surfaces UI package is released at the same version; install them all at that one version, since mixing releases is not supported.
35
+
36
+ - [The guides on surfaces-ui.com](https://surfaces-ui.com/#docs)
37
+ - [Getting started](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/getting-started.md)
38
+ - [Building with an agent](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/agent-integration.md)
39
+ - [Styling](https://github.com/teradata-labs/surfaces-ui/blob/main/docs/styling.md)
40
+ - [Source for this package](https://github.com/teradata-labs/surfaces-ui/tree/main/packages/state)
41
+
42
+ Licensed under Apache-2.0. See LICENSE and NOTICE.
@@ -0,0 +1,3 @@
1
+ export * from "./store.js";
2
+ export * from "./persist.js";
3
+ export * from "./services.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./store.js";
2
+ export * from "./persist.js";
3
+ export * from "./services.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC","sourcesContent":["export * from \"./store.js\";\nexport * from \"./persist.js\";\nexport * from \"./services.js\";\n"]}
@@ -0,0 +1,69 @@
1
+ import type { StateStorage } from "@surfaces-ui/data";
2
+ import type { Store } from "./store.js";
3
+ export { type StateStorage, browserStorage, memoryStorage } from "@surfaces-ui/data";
4
+ export interface PersistOptions<T> {
5
+ key: string;
6
+ storage: StateStorage;
7
+ /** Bump when the shape changes; older saved state then goes through `migrate`, or is dropped without it. */
8
+ version?: number;
9
+ migrate?(saved: unknown, fromVersion: number): T | undefined;
10
+ /**
11
+ * Checks saved state before it is used. Saved state can be edited by
12
+ * anyone with access to the storage, so it is not trusted: return
13
+ * undefined to ignore it.
14
+ */
15
+ parse?(saved: unknown): T | undefined;
16
+ /** Wait this long after the last change before saving. Defaults to 200 ms. */
17
+ debounceMs?: number;
18
+ /**
19
+ * What to save, when not all of the state should outlive the page. What
20
+ * comes back on load is only that part, so it is put back with `restore`.
21
+ */
22
+ select?(value: T): unknown;
23
+ /**
24
+ * Puts a saved part back into the whole state. Without it, a saved object
25
+ * is laid over the current value (its other fields kept), and anything
26
+ * else replaces the value. `parse` then checks the whole result.
27
+ */
28
+ restore?(saved: unknown, current: T): T | undefined;
29
+ }
30
+ /** Text for a state value. Large integers survive the round trip. */
31
+ export declare const encodeState: (value: unknown) => string;
32
+ export declare const decodeState: (text: string) => unknown;
33
+ /**
34
+ * Loads a store's saved value and saves it again after each change. Returns
35
+ * `ready` (resolved once the saved value has been applied, or found missing)
36
+ * and `stop`. A change made to the store before the saved value has loaded is
37
+ * newer than it, so the saved value is then not applied.
38
+ */
39
+ export declare function persist<T>(store: Store<T>, options: PersistOptions<T>): {
40
+ ready: Promise<void>;
41
+ stop(): void;
42
+ flush(): void;
43
+ };
44
+ export interface UrlSyncOptions<T> {
45
+ /** Query parameter that carries the state. */
46
+ param: string;
47
+ /** Turns state into a short string. Return "" to leave the parameter out. Never put personal data here. */
48
+ encode(value: T): string;
49
+ /** Reads state back. The address bar is untrusted input: return undefined for anything unexpected. */
50
+ decode(text: string): T | undefined;
51
+ /** Defaults to the page's own location and history. */
52
+ location?: {
53
+ href: string;
54
+ };
55
+ history?: {
56
+ replaceState(data: unknown, unused: string, url: string): void;
57
+ };
58
+ /** Listens for back and forward. Defaults to window. */
59
+ events?: {
60
+ addEventListener(type: "popstate", listener: () => void): void;
61
+ removeEventListener(type: "popstate", listener: () => void): void;
62
+ };
63
+ }
64
+ /**
65
+ * Keeps a store and a query parameter in step, so a view can be linked to
66
+ * and survives a reload. The address is replaced, not pushed, so filtering
67
+ * does not fill the back button.
68
+ */
69
+ export declare function syncUrl<T>(store: Store<T>, options: UrlSyncOptions<T>): () => void;
@@ -0,0 +1,109 @@
1
+ // One storage interface for the whole library, defined in @surfaces-ui/data and offered here too.
2
+ export { browserStorage, memoryStorage } from "@surfaces-ui/data";
3
+ const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
4
+ const replacer = (_, value) => (typeof value === "bigint" ? { $bigint: String(value) } : value);
5
+ const reviver = (_, value) => value !== null && typeof value === "object" && typeof value.$bigint === "string" ? BigInt(value.$bigint) : value;
6
+ /** Text for a state value. Large integers survive the round trip. */
7
+ export const encodeState = (value) => JSON.stringify(value, replacer);
8
+ export const decodeState = (text) => JSON.parse(text, reviver);
9
+ /**
10
+ * Loads a store's saved value and saves it again after each change. Returns
11
+ * `ready` (resolved once the saved value has been applied, or found missing)
12
+ * and `stop`. A change made to the store before the saved value has loaded is
13
+ * newer than it, so the saved value is then not applied.
14
+ */
15
+ export function persist(store, options) {
16
+ const { key, storage, version = 1, debounceMs = 200 } = options;
17
+ let timer;
18
+ let stopped = false;
19
+ let loading = true;
20
+ let changedWhileLoading = false;
21
+ const write = () => {
22
+ timer = undefined;
23
+ void storage.save(key, encodeState({ version, state: options.select ? options.select(store.get()) : store.get() }));
24
+ };
25
+ const ready = (async () => {
26
+ try {
27
+ const text = await storage.load(key);
28
+ if (stopped || changedWhileLoading || !text)
29
+ return;
30
+ const saved = decodeState(text);
31
+ const from = typeof saved?.version === "number" ? saved.version : 0;
32
+ const raw = from === version ? saved.state : options.migrate?.(saved?.state, from);
33
+ if (raw === undefined)
34
+ return;
35
+ const current = store.get();
36
+ const whole = options.restore ? options.restore(raw, current) : options.select && isPlainObject(raw) && isPlainObject(current) ? { ...current, ...raw } : raw;
37
+ const value = whole === undefined ? undefined : options.parse ? options.parse(whole) : whole;
38
+ if (value !== undefined)
39
+ store.set(value);
40
+ }
41
+ catch {
42
+ // Unreadable saved state is ignored; the store keeps its initial value.
43
+ }
44
+ finally {
45
+ loading = false;
46
+ }
47
+ })();
48
+ const unsubscribe = store.subscribe(() => {
49
+ if (loading)
50
+ changedWhileLoading = true;
51
+ if (timer)
52
+ clearTimeout(timer);
53
+ timer = setTimeout(write, debounceMs);
54
+ });
55
+ return {
56
+ ready,
57
+ flush() {
58
+ if (!timer)
59
+ return;
60
+ clearTimeout(timer);
61
+ write();
62
+ },
63
+ stop() {
64
+ stopped = true;
65
+ unsubscribe();
66
+ if (timer) {
67
+ clearTimeout(timer);
68
+ write();
69
+ }
70
+ },
71
+ };
72
+ }
73
+ /**
74
+ * Keeps a store and a query parameter in step, so a view can be linked to
75
+ * and survives a reload. The address is replaced, not pushed, so filtering
76
+ * does not fill the back button.
77
+ */
78
+ export function syncUrl(store, options) {
79
+ const location = options.location ?? globalThis.location;
80
+ const history = options.history ?? globalThis.history;
81
+ const events = options.events ?? (typeof window === "undefined" ? undefined : window);
82
+ if (!location || !history)
83
+ return () => { };
84
+ const read = () => {
85
+ const text = new URL(location.href).searchParams.get(options.param);
86
+ if (text === null)
87
+ return;
88
+ const value = options.decode(text);
89
+ if (value !== undefined)
90
+ store.set(value);
91
+ };
92
+ read();
93
+ const unsubscribe = store.subscribe((value) => {
94
+ const url = new URL(location.href);
95
+ const text = options.encode(value);
96
+ if (text === "")
97
+ url.searchParams.delete(options.param);
98
+ else
99
+ url.searchParams.set(options.param, text);
100
+ if (url.href !== location.href)
101
+ history.replaceState(null, "", url.href);
102
+ });
103
+ events?.addEventListener("popstate", read);
104
+ return () => {
105
+ unsubscribe();
106
+ events?.removeEventListener("popstate", read);
107
+ };
108
+ }
109
+ //# sourceMappingURL=persist.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persist.js","sourceRoot":"","sources":["../src/persist.ts"],"names":[],"mappings":"AAGA,kGAAkG;AAClG,OAAO,EAAqB,cAAc,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AA6BrF,MAAM,aAAa,GAAG,CAAC,KAAc,EAAoC,EAAE,CAAC,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAEjJ,MAAM,QAAQ,GAAG,CAAC,CAAS,EAAE,KAAc,EAAE,EAAE,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CA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AAO,CAAC,KAAK,CAAC,CAAC;QACpE,IAAI,IAAI,KAAK,IAAI;YAAE,OAAO;QAC1B,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,KAAK,KAAK,SAAS;YAAE,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC5C,CAAC,CAAC;IACF,IAAI,EAAE,CAAC;IACP,MAAM,WAAW,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE;QAC5C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACnC,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnC,IAAI,IAAI,KAAK,EAAE;YAAE,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;;YACnD,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QAC/C,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI;YAAE,OAAO,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IAC3E,CAAC,CAAC,CAAC;IACH,MAAM,EAAE,gBAAgB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAC3C,OAAO,GAAG,EAAE;QACV,WAAW,EAAE,CAAC;QACd,MAAM,EAAE,mBAAmB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IAChD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { StateStorage } from \"@surfaces-ui/data\";\nimport type { Store } from \"./store.js\";\n\n// One storage interface for the whole library, defined in @surfaces-ui/data and offered here too.\nexport { type StateStorage, browserStorage, memoryStorage } from \"@surfaces-ui/data\";\n\nexport interface PersistOptions<T> {\n key: string;\n storage: StateStorage;\n /** Bump when the shape changes; older saved state then goes through `migrate`, or is dropped without it. */\n version?: number;\n migrate?(saved: unknown, fromVersion: number): T | undefined;\n /**\n * Checks saved state before it is used. Saved state can be edited by\n * anyone with access to the storage, so it is not trusted: return\n * undefined to ignore it.\n */\n parse?(saved: unknown): T | undefined;\n /** Wait this long after the last change before saving. Defaults to 200 ms. */\n debounceMs?: number;\n /**\n * What to save, when not all of the state should outlive the page. What\n * comes back on load is only that part, so it is put back with `restore`.\n */\n select?(value: T): unknown;\n /**\n * Puts a saved part back into the whole state. Without it, a saved object\n * is laid over the current value (its other fields kept), and anything\n * else replaces the value. `parse` then checks the whole result.\n */\n restore?(saved: unknown, current: T): T | undefined;\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === \"object\" && !Array.isArray(value);\n\nconst replacer = (_: string, value: unknown) => (typeof value === \"bigint\" ? { $bigint: String(value) } : value);\nconst reviver = (_: string, value: unknown) =>\n value !== null && typeof value === \"object\" && typeof (value as { $bigint?: unknown }).$bigint === \"string\" ? BigInt((value as { $bigint: string }).$bigint) : value;\n\n/** Text for a state value. Large integers survive the round trip. */\nexport const encodeState = (value: unknown) => JSON.stringify(value, replacer);\nexport const decodeState = (text: string): unknown => JSON.parse(text, reviver);\n\n/**\n * Loads a store's saved value and saves it again after each change. Returns\n * `ready` (resolved once the saved value has been applied, or found missing)\n * and `stop`. A change made to the store before the saved value has loaded is\n * newer than it, so the saved value is then not applied.\n */\nexport function persist<T>(store: Store<T>, options: PersistOptions<T>): { ready: Promise<void>; stop(): void; flush(): void } {\n const { key, storage, version = 1, debounceMs = 200 } = options;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let stopped = false;\n let loading = true;\n let changedWhileLoading = false;\n const write = () => {\n timer = undefined;\n void storage.save(key, encodeState({ version, state: options.select ? options.select(store.get()) : store.get() }));\n };\n const ready = (async () => {\n try {\n const text = await storage.load(key);\n if (stopped || changedWhileLoading || !text) return;\n const saved = decodeState(text) as { version?: number; state?: unknown };\n const from = typeof saved?.version === \"number\" ? saved.version : 0;\n const raw = from === version ? saved.state : options.migrate?.(saved?.state, from);\n if (raw === undefined) return;\n const current = store.get();\n const whole = options.restore ? options.restore(raw, current) : options.select && isPlainObject(raw) && isPlainObject(current) ? ({ ...current, ...raw } as T) : (raw as T);\n const value = whole === undefined ? undefined : options.parse ? options.parse(whole) : whole;\n if (value !== undefined) store.set(value);\n } catch {\n // Unreadable saved state is ignored; the store keeps its initial value.\n } finally {\n loading = false;\n }\n })();\n const unsubscribe = store.subscribe(() => {\n if (loading) changedWhileLoading = true;\n if (timer) clearTimeout(timer);\n timer = setTimeout(write, debounceMs);\n });\n return {\n ready,\n flush() {\n if (!timer) return;\n clearTimeout(timer);\n write();\n },\n stop() {\n stopped = true;\n unsubscribe();\n if (timer) {\n clearTimeout(timer);\n write();\n }\n },\n };\n}\n\nexport interface UrlSyncOptions<T> {\n /** Query parameter that carries the state. */\n param: string;\n /** Turns state into a short string. Return \"\" to leave the parameter out. Never put personal data here. */\n encode(value: T): string;\n /** Reads state back. The address bar is untrusted input: return undefined for anything unexpected. */\n decode(text: string): T | undefined;\n /** Defaults to the page's own location and history. */\n location?: { href: string };\n history?: { replaceState(data: unknown, unused: string, url: string): void };\n /** Listens for back and forward. Defaults to window. */\n events?: { addEventListener(type: \"popstate\", listener: () => void): void; removeEventListener(type: \"popstate\", listener: () => void): void };\n}\n\n/**\n * Keeps a store and a query parameter in step, so a view can be linked to\n * and survives a reload. The address is replaced, not pushed, so filtering\n * does not fill the back button.\n */\nexport function syncUrl<T>(store: Store<T>, options: UrlSyncOptions<T>): () => void {\n const location = options.location ?? globalThis.location;\n const history = options.history ?? globalThis.history;\n const events = options.events ?? (typeof window === \"undefined\" ? undefined : window);\n if (!location || !history) return () => {};\n const read = () => {\n const text = new URL(location.href).searchParams.get(options.param);\n if (text === null) return;\n const value = options.decode(text);\n if (value !== undefined) store.set(value);\n };\n read();\n const unsubscribe = store.subscribe((value) => {\n const url = new URL(location.href);\n const text = options.encode(value);\n if (text === \"\") url.searchParams.delete(options.param);\n else url.searchParams.set(options.param, text);\n if (url.href !== location.href) history.replaceState(null, \"\", url.href);\n });\n events?.addEventListener(\"popstate\", read);\n return () => {\n unsubscribe();\n events?.removeEventListener(\"popstate\", read);\n };\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import { type HistoryControls, type ReadableStore, type Store } from "./store.js";
2
+ /**
3
+ * Reads a store in a component. With a selector the component re-renders
4
+ * only when the selected part changes; return a value that is stable for
5
+ * the same state (a field, not a new object).
6
+ */
7
+ export declare function useStore<T>(store: ReadableStore<T>): T;
8
+ export declare function useStore<T, U>(store: ReadableStore<T>, selector: (value: T) => U): U;
9
+ /** Undo and redo for a store, with flags that update as the history changes. */
10
+ export declare function useHistory<T>(store: Store<T>, limit?: number): HistoryControls;
package/dist/react.js ADDED
@@ -0,0 +1,19 @@
1
+ import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
2
+ import { withHistory } from "./store.js";
3
+ export function useStore(store, selector) {
4
+ const subscribe = useCallback((notify) => store.subscribe(notify), [store]);
5
+ const read = useCallback(() => (selector ? selector(store.get()) : store.get()), [store, selector]);
6
+ return useSyncExternalStore(subscribe, read, read);
7
+ }
8
+ /** Undo and redo for a store, with flags that update as the history changes. */
9
+ export function useHistory(store, limit) {
10
+ const history = useMemo(() => withHistory(store, limit), [store, limit]);
11
+ useEffect(() => {
12
+ history.start();
13
+ return history.stop;
14
+ }, [history]);
15
+ // Reading the store makes the flags fresh after every change.
16
+ useStore(store);
17
+ return history;
18
+ }
19
+ //# sourceMappingURL=react.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react.js","sourceRoot":"","sources":["../src/react.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC9E,OAAO,EAAwD,WAAW,EAAE,MAAM,YAAY,CAAC;AAS/F,MAAM,UAAU,QAAQ,CAAO,KAAuB,EAAE,QAA0B;IAChF,MAAM,SAAS,GAAG,WAAW,CAAC,CAAC,MAAkB,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;IACxF,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC;IACpG,OAAO,oBAAoB,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AACrD,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,UAAU,CAAI,KAAe,EAAE,KAAc;IAC3D,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;IACzE,SAAS,CAAC,GAAG,EAAE;QACb,OAAO,CAAC,KAAK,EAAE,CAAC;QAChB,OAAO,OAAO,CAAC,IAAI,CAAC;IACtB,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IACd,8DAA8D;IAC9D,QAAQ,CAAC,KAAK,CAAC,CAAC;IAChB,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { useCallback, useEffect, useMemo, useSyncExternalStore } from \"react\";\nimport { type HistoryControls, type ReadableStore, type Store, withHistory } from \"./store.js\";\n\n/**\n * Reads a store in a component. With a selector the component re-renders\n * only when the selected part changes; return a value that is stable for\n * the same state (a field, not a new object).\n */\nexport function useStore<T>(store: ReadableStore<T>): T;\nexport function useStore<T, U>(store: ReadableStore<T>, selector: (value: T) => U): U;\nexport function useStore<T, U>(store: ReadableStore<T>, selector?: (value: T) => U): T | U {\n const subscribe = useCallback((notify: () => void) => store.subscribe(notify), [store]);\n const read = useCallback(() => (selector ? selector(store.get()) : store.get()), [store, selector]);\n return useSyncExternalStore(subscribe, read, read);\n}\n\n/** Undo and redo for a store, with flags that update as the history changes. */\nexport function useHistory<T>(store: Store<T>, limit?: number): HistoryControls {\n const history = useMemo(() => withHistory(store, limit), [store, limit]);\n useEffect(() => {\n history.start();\n return history.stop;\n }, [history]);\n // Reading the store makes the flags fresh after every change.\n useStore(store);\n return history;\n}\n"]}
@@ -0,0 +1,89 @@
1
+ import type { MessageInitShape } from "@bufbuild/protobuf";
2
+ import { type FilterSpec, type SortSpec } from "@surfaces-ui/data";
3
+ import { type FilterSchema, type SortSchema } from "@surfaces-ui/proto";
4
+ import { type Store } from "./store.js";
5
+ type FilterInit = MessageInitShape<typeof FilterSchema>;
6
+ type SortInit = MessageInitShape<typeof SortSchema>;
7
+ /** A plain value a person picked: a category, a number, a date as ISO text. */
8
+ export type Picked = string | number | boolean;
9
+ /**
10
+ * What a set of views over the same data share, in the same plain form a
11
+ * page's filters, a component's props and an agent use (`FilterSpec`,
12
+ * `SortSpec` from `@surfaces-ui/data`), so the list can be saved, put in a
13
+ * link, handed to an agent or bound into a surface as it is.
14
+ */
15
+ export interface ViewState {
16
+ filters: FilterSpec[];
17
+ sorts: SortSpec[];
18
+ }
19
+ export declare const emptyViewState: ViewState;
20
+ /**
21
+ * The filters a view should send for this state. Pass `except` to leave out
22
+ * one column: a chart that picks regions must not filter itself down to the
23
+ * region just picked, or there would be nothing left to click. A relative
24
+ * date (`since`) is worked out now, so it never goes stale.
25
+ */
26
+ export declare function viewFilters(state: ViewState, except?: string, now?: Date): FilterInit[];
27
+ /** The sorts a view should send for this state. */
28
+ export declare function viewSorts(state: ViewState): SortInit[];
29
+ export interface ViewStateService extends Store<ViewState> {
30
+ /** Adds the value to a column's choice, or takes it out if it is already chosen (`toggleValueFilter`). */
31
+ toggle(column: string, value: Picked): void;
32
+ /** Replaces a column's choice of values. An empty list clears it. */
33
+ select(column: string, values: Picked[]): void;
34
+ /** Sets an inclusive range on a column; either end may be open, and neither clears it. */
35
+ setRange(column: string, range: {
36
+ from?: Picked;
37
+ to?: Picked;
38
+ } | undefined): void;
39
+ /** Replaces the whole filter list, as a `FilterBar` or an agent would. */
40
+ setFilters(filters: FilterSpec[]): void;
41
+ setSorts(sorts: SortSpec[]): void;
42
+ /** Clears every filter on one column, or every filter. Sorts are kept. */
43
+ clear(column?: string): void;
44
+ /** Filters for a view, leaving out the column that view itself controls. */
45
+ filters(except?: string): FilterInit[];
46
+ /** How many columns are filtered. */
47
+ activeCount(): number;
48
+ }
49
+ /**
50
+ * Shared filter and sort state for views over the same data. Charts, grids
51
+ * and pivots that read it stay in step, which is what makes cross-filtering
52
+ * work: one view writes a choice and the others query again. Filtering still
53
+ * happens in the engine; this only holds what was chosen.
54
+ */
55
+ export declare function createViewState(initial?: ViewState): ViewStateService;
56
+ /**
57
+ * Checks a view state from an untrusted place (storage, the address bar)
58
+ * before it is used: only filters that could be sent are kept. A view state
59
+ * saved in the older form (`selections`, `ranges`) is read and turned into
60
+ * the filter list it meant.
61
+ */
62
+ export declare function parseViewState(input: unknown): ViewState | undefined;
63
+ export interface QueryRun {
64
+ sql: string;
65
+ /** ISO 8601 time Run was pressed. Pass it to every view of the run as `notBefore`. */
66
+ ranAt: string;
67
+ }
68
+ export interface QueryRunsState {
69
+ /** What is on screen. */
70
+ current?: QueryRun;
71
+ /** Earlier runs, newest first, without repeats of the same SQL in a row. */
72
+ history: QueryRun[];
73
+ }
74
+ export interface QueryRunsService extends Store<QueryRunsState> {
75
+ /** Runs SQL: every view given the new `ranAt` runs the query again, once between them. */
76
+ run(sql: string): QueryRun;
77
+ /** Runs the current SQL again. */
78
+ rerun(): QueryRun | undefined;
79
+ }
80
+ /**
81
+ * Tracks what was run and when. The time of a run is the `notBefore` that
82
+ * grids, charts and pivots share, so one press of Run executes the query
83
+ * once however many views show it.
84
+ */
85
+ export declare function createQueryRuns(options?: {
86
+ limit?: number;
87
+ now?: () => Date;
88
+ }): QueryRunsService;
89
+ export {};
@@ -0,0 +1,103 @@
1
+ import { filtersExcept, filtersFromSpec, parseFilterSpecs, parseSortSpecs, selectValues, sortsFromSpec, toggleValueFilter } from "@surfaces-ui/data";
2
+ import { SortDirection } from "@surfaces-ui/proto";
3
+ import { createStore } from "./store.js";
4
+ export const emptyViewState = { filters: [], sorts: [] };
5
+ const RANGE_OPS = new Set(["between", "gte", "lte"]);
6
+ /**
7
+ * The filters a view should send for this state. Pass `except` to leave out
8
+ * one column: a chart that picks regions must not filter itself down to the
9
+ * region just picked, or there would be nothing left to click. A relative
10
+ * date (`since`) is worked out now, so it never goes stale.
11
+ */
12
+ export function viewFilters(state, except, now = new Date()) {
13
+ return filtersFromSpec(except === undefined ? state.filters : filtersExcept(state.filters, except), now);
14
+ }
15
+ /** The sorts a view should send for this state. */
16
+ export function viewSorts(state) {
17
+ return sortsFromSpec(state.sorts).map((s) => ({ column: s.column, direction: s.desc ? SortDirection.DESC : SortDirection.ASC }));
18
+ }
19
+ /**
20
+ * Shared filter and sort state for views over the same data. Charts, grids
21
+ * and pivots that read it stay in step, which is what makes cross-filtering
22
+ * work: one view writes a choice and the others query again. Filtering still
23
+ * happens in the engine; this only holds what was chosen.
24
+ */
25
+ export function createViewState(initial = emptyViewState) {
26
+ const store = createStore(initial);
27
+ const setList = (change) => store.set((state) => ({ ...state, filters: change(state.filters) }));
28
+ return {
29
+ ...store,
30
+ toggle: (column, value) => setList((filters) => toggleValueFilter(filters, column, value)),
31
+ select: (column, values) => setList((filters) => selectValues(filters, column, values)),
32
+ setRange(column, range) {
33
+ setList((filters) => {
34
+ const others = filters.filter((f) => !(f.column === column && RANGE_OPS.has(f.op)));
35
+ const { from, to } = range ?? {};
36
+ if (from !== undefined && to !== undefined)
37
+ return [...others, { column, op: "between", values: [from, to] }];
38
+ if (from !== undefined)
39
+ return [...others, { column, op: "gte", values: [from] }];
40
+ if (to !== undefined)
41
+ return [...others, { column, op: "lte", values: [to] }];
42
+ return others;
43
+ });
44
+ },
45
+ setFilters: (filters) => setList(() => [...filters]),
46
+ setSorts: (sorts) => store.set((state) => ({ ...state, sorts: [...sorts] })),
47
+ clear: (column) => setList((filters) => (column === undefined ? [] : filtersExcept(filters, column))),
48
+ filters: (except) => viewFilters(store.get(), except),
49
+ activeCount: () => new Set(store.get().filters.map((f) => f.column)).size,
50
+ };
51
+ }
52
+ /**
53
+ * Checks a view state from an untrusted place (storage, the address bar)
54
+ * before it is used: only filters that could be sent are kept. A view state
55
+ * saved in the older form (`selections`, `ranges`) is read and turned into
56
+ * the filter list it meant.
57
+ */
58
+ export function parseViewState(input) {
59
+ if (input === null || typeof input !== "object" || Array.isArray(input))
60
+ return undefined;
61
+ const raw = input;
62
+ const sorts = parseSortSpecs(raw.sorts);
63
+ if (raw.filters !== undefined || (raw.selections === undefined && raw.ranges === undefined))
64
+ return { filters: parseFilterSpecs(raw.filters), sorts };
65
+ // The older form: values chosen per column, and an inclusive range per column.
66
+ const entries = (value) => (value !== null && typeof value === "object" && !Array.isArray(value) ? Object.entries(value) : []);
67
+ const older = [];
68
+ for (const [column, values] of entries(raw.selections)) {
69
+ if (Array.isArray(values))
70
+ older.push(values.length === 1 ? { column, op: "eq", values } : { column, op: "in", values });
71
+ }
72
+ for (const [column, range] of entries(raw.ranges)) {
73
+ const { from, to } = (range ?? {});
74
+ const has = (v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
75
+ if (has(from) && has(to))
76
+ older.push({ column, op: "between", values: [from, to] });
77
+ else if (has(from))
78
+ older.push({ column, op: "gte", values: [from] });
79
+ else if (has(to))
80
+ older.push({ column, op: "lte", values: [to] });
81
+ }
82
+ return { filters: parseFilterSpecs(older), sorts };
83
+ }
84
+ /**
85
+ * Tracks what was run and when. The time of a run is the `notBefore` that
86
+ * grids, charts and pivots share, so one press of Run executes the query
87
+ * once however many views show it.
88
+ */
89
+ export function createQueryRuns(options = {}) {
90
+ const limit = options.limit ?? 50;
91
+ const now = options.now ?? (() => new Date());
92
+ const store = createStore({ history: [] });
93
+ const run = (sql) => {
94
+ const next = { sql, ranAt: now().toISOString() };
95
+ store.set((state) => ({
96
+ current: next,
97
+ history: state.current && state.current.sql.trim() !== sql.trim() ? [state.current, ...state.history].slice(0, limit) : state.history,
98
+ }));
99
+ return next;
100
+ };
101
+ return { ...store, run, rerun: () => (store.get().current ? run(store.get().current.sql) : undefined) };
102
+ }
103
+ //# sourceMappingURL=services.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services.js","sourceRoot":"","sources":["../src/services.ts"],"names":[],"mappings":"AACA,OAAO,EAAkC,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACrL,OAAO,EAAE,aAAa,EAAsC,MAAM,oBAAoB,CAAC;AACvF,OAAO,EAAc,WAAW,EAAE,MAAM,YAAY,CAAC;AAmBrD,MAAM,CAAC,MAAM,cAAc,GAAc,EAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;AAEpE,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;AAErD;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,KAAgB,EAAE,MAAe,EAAE,GAAG,GAAS,IAAI,IAAI,EAAE;IACnF,OAAO,eAAe,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,EAAE,GAAG,CAAC,CAAC;AAC3G,CAAC;AAED,mDAAmD;AACnD,MAAM,UAAU,SAAS,CAAC,KAAgB;IACxC,OAAO,aAAa,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,MAA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,CAAC,CAAC;IAC9C,MAAM,KAAK,GAAG,WAAW,CAAiB,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;IAC3D,MAAM,GAAG,GAAG,CAAC,GAAW,EAAY,EAAE;QACpC,MAAM,IAAI,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC;QACjD,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACpB,OAAO,EAAE,IAAI;YACb,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO;SACtI,CAAC,CAAC,CAAC;QACJ,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IACF,OAAO,EAAE,GAAG,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC;AAC3G,CAAC","sourcesContent":["import type { MessageInitShape } from \"@bufbuild/protobuf\";\nimport { type FilterSpec, type SortSpec, filtersExcept, filtersFromSpec, parseFilterSpecs, parseSortSpecs, selectValues, sortsFromSpec, toggleValueFilter } from \"@surfaces-ui/data\";\nimport { SortDirection, type FilterSchema, type SortSchema } from \"@surfaces-ui/proto\";\nimport { type Store, createStore } from \"./store.js\";\n\ntype FilterInit = MessageInitShape<typeof FilterSchema>;\ntype SortInit = MessageInitShape<typeof SortSchema>;\n\n/** A plain value a person picked: a category, a number, a date as ISO text. */\nexport type Picked = string | number | boolean;\n\n/**\n * What a set of views over the same data share, in the same plain form a\n * page's filters, a component's props and an agent use (`FilterSpec`,\n * `SortSpec` from `@surfaces-ui/data`), so the list can be saved, put in a\n * link, handed to an agent or bound into a surface as it is.\n */\nexport interface ViewState {\n filters: FilterSpec[];\n sorts: SortSpec[];\n}\n\nexport const emptyViewState: ViewState = { filters: [], sorts: [] };\n\nconst RANGE_OPS = new Set([\"between\", \"gte\", \"lte\"]);\n\n/**\n * The filters a view should send for this state. Pass `except` to leave out\n * one column: a chart that picks regions must not filter itself down to the\n * region just picked, or there would be nothing left to click. A relative\n * date (`since`) is worked out now, so it never goes stale.\n */\nexport function viewFilters(state: ViewState, except?: string, now: Date = new Date()): FilterInit[] {\n return filtersFromSpec(except === undefined ? state.filters : filtersExcept(state.filters, except), now);\n}\n\n/** The sorts a view should send for this state. */\nexport function viewSorts(state: ViewState): SortInit[] {\n return sortsFromSpec(state.sorts).map((s) => ({ column: s.column, direction: s.desc ? SortDirection.DESC : SortDirection.ASC }));\n}\n\nexport interface ViewStateService extends Store<ViewState> {\n /** Adds the value to a column's choice, or takes it out if it is already chosen (`toggleValueFilter`). */\n toggle(column: string, value: Picked): void;\n /** Replaces a column's choice of values. An empty list clears it. */\n select(column: string, values: Picked[]): void;\n /** Sets an inclusive range on a column; either end may be open, and neither clears it. */\n setRange(column: string, range: { from?: Picked; to?: Picked } | undefined): void;\n /** Replaces the whole filter list, as a `FilterBar` or an agent would. */\n setFilters(filters: FilterSpec[]): void;\n setSorts(sorts: SortSpec[]): void;\n /** Clears every filter on one column, or every filter. Sorts are kept. */\n clear(column?: string): void;\n /** Filters for a view, leaving out the column that view itself controls. */\n filters(except?: string): FilterInit[];\n /** How many columns are filtered. */\n activeCount(): number;\n}\n\n/**\n * Shared filter and sort state for views over the same data. Charts, grids\n * and pivots that read it stay in step, which is what makes cross-filtering\n * work: one view writes a choice and the others query again. Filtering still\n * happens in the engine; this only holds what was chosen.\n */\nexport function createViewState(initial: ViewState = emptyViewState): ViewStateService {\n const store = createStore<ViewState>(initial);\n const setList = (change: (filters: FilterSpec[]) => FilterSpec[]) => store.set((state) => ({ ...state, filters: change(state.filters) }));\n return {\n ...store,\n toggle: (column, value) => setList((filters) => toggleValueFilter(filters, column, value)),\n select: (column, values) => setList((filters) => selectValues(filters, column, values)),\n setRange(column, range) {\n setList((filters) => {\n const others = filters.filter((f) => !(f.column === column && RANGE_OPS.has(f.op)));\n const { from, to } = range ?? {};\n if (from !== undefined && to !== undefined) return [...others, { column, op: \"between\", values: [from, to] }];\n if (from !== undefined) return [...others, { column, op: \"gte\", values: [from] }];\n if (to !== undefined) return [...others, { column, op: \"lte\", values: [to] }];\n return others;\n });\n },\n setFilters: (filters) => setList(() => [...filters]),\n setSorts: (sorts) => store.set((state) => ({ ...state, sorts: [...sorts] })),\n clear: (column) => setList((filters) => (column === undefined ? [] : filtersExcept(filters, column))),\n filters: (except) => viewFilters(store.get(), except),\n activeCount: () => new Set(store.get().filters.map((f) => f.column)).size,\n };\n}\n\n/**\n * Checks a view state from an untrusted place (storage, the address bar)\n * before it is used: only filters that could be sent are kept. A view state\n * saved in the older form (`selections`, `ranges`) is read and turned into\n * the filter list it meant.\n */\nexport function parseViewState(input: unknown): ViewState | undefined {\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) return undefined;\n const raw = input as { filters?: unknown; sorts?: unknown; selections?: unknown; ranges?: unknown };\n const sorts = parseSortSpecs(raw.sorts);\n if (raw.filters !== undefined || (raw.selections === undefined && raw.ranges === undefined)) return { filters: parseFilterSpecs(raw.filters), sorts };\n // The older form: values chosen per column, and an inclusive range per column.\n const entries = (value: unknown) => (value !== null && typeof value === \"object\" && !Array.isArray(value) ? Object.entries(value as Record<string, unknown>) : []);\n const older: unknown[] = [];\n for (const [column, values] of entries(raw.selections)) {\n if (Array.isArray(values)) older.push(values.length === 1 ? { column, op: \"eq\", values } : { column, op: \"in\", values });\n }\n for (const [column, range] of entries(raw.ranges)) {\n const { from, to } = (range ?? {}) as { from?: unknown; to?: unknown };\n const has = (v: unknown) => typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\";\n if (has(from) && has(to)) older.push({ column, op: \"between\", values: [from, to] });\n else if (has(from)) older.push({ column, op: \"gte\", values: [from] });\n else if (has(to)) older.push({ column, op: \"lte\", values: [to] });\n }\n return { filters: parseFilterSpecs(older), sorts };\n}\n\nexport interface QueryRun {\n sql: string;\n /** ISO 8601 time Run was pressed. Pass it to every view of the run as `notBefore`. */\n ranAt: string;\n}\n\nexport interface QueryRunsState {\n /** What is on screen. */\n current?: QueryRun;\n /** Earlier runs, newest first, without repeats of the same SQL in a row. */\n history: QueryRun[];\n}\n\nexport interface QueryRunsService extends Store<QueryRunsState> {\n /** Runs SQL: every view given the new `ranAt` runs the query again, once between them. */\n run(sql: string): QueryRun;\n /** Runs the current SQL again. */\n rerun(): QueryRun | undefined;\n}\n\n/**\n * Tracks what was run and when. The time of a run is the `notBefore` that\n * grids, charts and pivots share, so one press of Run executes the query\n * once however many views show it.\n */\nexport function createQueryRuns(options: { limit?: number; now?: () => Date } = {}): QueryRunsService {\n const limit = options.limit ?? 50;\n const now = options.now ?? (() => new Date());\n const store = createStore<QueryRunsState>({ history: [] });\n const run = (sql: string): QueryRun => {\n const next = { sql, ranAt: now().toISOString() };\n store.set((state) => ({\n current: next,\n history: state.current && state.current.sql.trim() !== sql.trim() ? [state.current, ...state.history].slice(0, limit) : state.history,\n }));\n return next;\n };\n return { ...store, run, rerun: () => (store.get().current ? run(store.get().current!.sql) : undefined) };\n}\n"]}
@@ -0,0 +1,34 @@
1
+ /** A value that can be read and watched, but not set from outside: what `derive` gives, and what `useStore` reads. */
2
+ export interface ReadableStore<T> {
3
+ get(): T;
4
+ /** Calls `listener` after each change. Returns a function that stops it. */
5
+ subscribe(listener: (value: T, previous: T) => void): () => void;
6
+ }
7
+ /** A value that can be read, replaced and watched. The base of every state service here. */
8
+ export interface Store<T> extends ReadableStore<T> {
9
+ /** Replaces the value, or computes the next one from the current one. Setting an identical value notifies nobody. */
10
+ set(next: T | ((current: T) => T)): void;
11
+ }
12
+ /**
13
+ * Creates a store. It has no dependency on React or the DOM, so the same
14
+ * state can drive components, an MCP app page, a test, or code on a server.
15
+ */
16
+ export declare function createStore<T>(initial: T): Store<T>;
17
+ /** A read-only store computed from another (a store, or another derived one). It updates only when the computed value changes. */
18
+ export declare function derive<T, U>(source: ReadableStore<T>, compute: (value: T) => U, equal?: (a: U, b: U) => boolean): ReadableStore<U>;
19
+ export interface HistoryControls {
20
+ undo(): void;
21
+ redo(): void;
22
+ canUndo(): boolean;
23
+ canRedo(): boolean;
24
+ /** Forgets every earlier and later value. */
25
+ clear(): void;
26
+ }
27
+ /**
28
+ * Adds undo and redo to a store. Each change made through the store is one
29
+ * step; undoing and redoing are not recorded as new steps.
30
+ */
31
+ export declare function withHistory<T>(store: Store<T>, limit?: number): HistoryControls & {
32
+ stop(): void;
33
+ start(): void;
34
+ };
package/dist/store.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Creates a store. It has no dependency on React or the DOM, so the same
3
+ * state can drive components, an MCP app page, a test, or code on a server.
4
+ */
5
+ export function createStore(initial) {
6
+ let value = initial;
7
+ const listeners = new Set();
8
+ return {
9
+ get: () => value,
10
+ set(next) {
11
+ const resolved = typeof next === "function" ? next(value) : next;
12
+ if (Object.is(resolved, value))
13
+ return;
14
+ const previous = value;
15
+ value = resolved;
16
+ for (const listener of [...listeners])
17
+ listener(value, previous);
18
+ },
19
+ subscribe(listener) {
20
+ listeners.add(listener);
21
+ return () => void listeners.delete(listener);
22
+ },
23
+ };
24
+ }
25
+ /** A read-only store computed from another (a store, or another derived one). It updates only when the computed value changes. */
26
+ export function derive(source, compute, equal = Object.is) {
27
+ let current = compute(source.get());
28
+ const listeners = new Set();
29
+ let stop;
30
+ const refresh = () => {
31
+ const next = compute(source.get());
32
+ if (equal(next, current))
33
+ return;
34
+ const previous = current;
35
+ current = next;
36
+ for (const listener of [...listeners])
37
+ listener(current, previous);
38
+ };
39
+ return {
40
+ get() {
41
+ // With nobody subscribed there is nothing keeping it fresh, so it is computed on read.
42
+ if (!stop)
43
+ current = compute(source.get());
44
+ return current;
45
+ },
46
+ subscribe(listener) {
47
+ if (listeners.size === 0) {
48
+ current = compute(source.get());
49
+ stop = source.subscribe(refresh);
50
+ }
51
+ listeners.add(listener);
52
+ return () => {
53
+ listeners.delete(listener);
54
+ if (listeners.size === 0) {
55
+ stop?.();
56
+ stop = undefined;
57
+ }
58
+ };
59
+ },
60
+ };
61
+ }
62
+ /**
63
+ * Adds undo and redo to a store. Each change made through the store is one
64
+ * step; undoing and redoing are not recorded as new steps.
65
+ */
66
+ export function withHistory(store, limit = 100) {
67
+ let past = [];
68
+ let future = [];
69
+ let travelling = false;
70
+ let unsubscribe;
71
+ // Restartable, so a React effect that is cleaned up and run again (StrictMode) keeps recording.
72
+ const start = () => {
73
+ unsubscribe ??= store.subscribe((_, previous) => {
74
+ if (travelling)
75
+ return;
76
+ past.push(previous);
77
+ if (past.length > limit)
78
+ past = past.slice(-limit);
79
+ future = [];
80
+ });
81
+ };
82
+ const stop = () => {
83
+ unsubscribe?.();
84
+ unsubscribe = undefined;
85
+ };
86
+ start();
87
+ const travel = (from, to) => {
88
+ const target = from.pop();
89
+ to.push(store.get());
90
+ travelling = true;
91
+ try {
92
+ store.set(target);
93
+ }
94
+ finally {
95
+ travelling = false;
96
+ }
97
+ };
98
+ return {
99
+ undo: () => past.length > 0 && travel(past, future),
100
+ redo: () => future.length > 0 && travel(future, past),
101
+ canUndo: () => past.length > 0,
102
+ canRedo: () => future.length > 0,
103
+ clear() {
104
+ past = [];
105
+ future = [];
106
+ },
107
+ stop,
108
+ start,
109
+ };
110
+ }
111
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAaA;;;GAGG;A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AC,QAAQ,CAAC,CAAC;YACpB,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK;gBAAE,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;YACnD,MAAM,GAAG,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,MAAM,IAAI,GAAG,GAAG,EAAE;QAChB,WAAW,EAAE,EAAE,CAAC;QAChB,WAAW,GAAG,SAAS,CAAC;IAC1B,CAAC,CAAC;IACF,KAAK,EAAE,CAAC;IACR,MAAM,MAAM,GAAG,CAAC,IAAS,EAAE,EAAO,EAAE,EAAE;QACpC,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC1B,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;QACrB,UAAU,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC;YACH,KAAK,CAAC,GAAG,CAAC,MAAW,CAAC,CAAC;QACzB,CAAC;gBAAS,CAAC;YACT,UAAU,GAAG,KAAK,CAAC;QACrB,CAAC;IACH,CAAC,CAAC;IACF,OAAO;QACL,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC;QACnD,IAAI,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC;QACrD,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC;QAC9B,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;QAChC,KAAK;YACH,IAAI,GAAG,EAAE,CAAC;YACV,MAAM,GAAG,EAAE,CAAC;QACd,CAAC;QACD,IAAI;QACJ,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["/** A value that can be read and watched, but not set from outside: what `derive` gives, and what `useStore` reads. */\nexport interface ReadableStore<T> {\n get(): T;\n /** Calls `listener` after each change. Returns a function that stops it. */\n subscribe(listener: (value: T, previous: T) => void): () => void;\n}\n\n/** A value that can be read, replaced and watched. The base of every state service here. */\nexport interface Store<T> extends ReadableStore<T> {\n /** Replaces the value, or computes the next one from the current one. Setting an identical value notifies nobody. */\n set(next: T | ((current: T) => T)): void;\n}\n\n/**\n * Creates a store. It has no dependency on React or the DOM, so the same\n * state can drive components, an MCP app page, a test, or code on a server.\n */\nexport function createStore<T>(initial: T): Store<T> {\n let value = initial;\n const listeners = new Set<(value: T, previous: T) => void>();\n return {\n get: () => value,\n set(next) {\n const resolved = typeof next === \"function\" ? (next as (current: T) => T)(value) : next;\n if (Object.is(resolved, value)) return;\n const previous = value;\n value = resolved;\n for (const listener of [...listeners]) listener(value, previous);\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n };\n}\n\n/** A read-only store computed from another (a store, or another derived one). It updates only when the computed value changes. */\nexport function derive<T, U>(source: ReadableStore<T>, compute: (value: T) => U, equal: (a: U, b: U) => boolean = Object.is): ReadableStore<U> {\n let current = compute(source.get());\n const listeners = new Set<(value: U, previous: U) => void>();\n let stop: (() => void) | undefined;\n const refresh = () => {\n const next = compute(source.get());\n if (equal(next, current)) return;\n const previous = current;\n current = next;\n for (const listener of [...listeners]) listener(current, previous);\n };\n return {\n get() {\n // With nobody subscribed there is nothing keeping it fresh, so it is computed on read.\n if (!stop) current = compute(source.get());\n return current;\n },\n subscribe(listener) {\n if (listeners.size === 0) {\n current = compute(source.get());\n stop = source.subscribe(refresh);\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n stop?.();\n stop = undefined;\n }\n };\n },\n };\n}\n\nexport interface HistoryControls {\n undo(): void;\n redo(): void;\n canUndo(): boolean;\n canRedo(): boolean;\n /** Forgets every earlier and later value. */\n clear(): void;\n}\n\n/**\n * Adds undo and redo to a store. Each change made through the store is one\n * step; undoing and redoing are not recorded as new steps.\n */\nexport function withHistory<T>(store: Store<T>, limit = 100): HistoryControls & { stop(): void; start(): void } {\n let past: T[] = [];\n let future: T[] = [];\n let travelling = false;\n let unsubscribe: (() => void) | undefined;\n // Restartable, so a React effect that is cleaned up and run again (StrictMode) keeps recording.\n const start = () => {\n unsubscribe ??= store.subscribe((_, previous) => {\n if (travelling) return;\n past.push(previous);\n if (past.length > limit) past = past.slice(-limit);\n future = [];\n });\n };\n const stop = () => {\n unsubscribe?.();\n unsubscribe = undefined;\n };\n start();\n const travel = (from: T[], to: T[]) => {\n const target = from.pop();\n to.push(store.get());\n travelling = true;\n try {\n store.set(target as T);\n } finally {\n travelling = false;\n }\n };\n return {\n undo: () => past.length > 0 && travel(past, future),\n redo: () => future.length > 0 && travel(future, past),\n canUndo: () => past.length > 0,\n canRedo: () => future.length > 0,\n clear() {\n past = [];\n future = [];\n },\n stop,\n start,\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@surfaces-ui/state",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Reusable state services for Surfaces UI: stores, persistence, URL sync, undo, shared view state and query runs",
5
+ "keywords": [
6
+ "surfaces-ui",
7
+ "analytics",
8
+ "data",
9
+ "state",
10
+ "store",
11
+ "undo",
12
+ "persistence"
13
+ ],
14
+ "license": "Apache-2.0",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/teradata-labs/surfaces-ui.git",
18
+ "directory": "packages/state"
19
+ },
20
+ "homepage": "https://github.com/teradata-labs/surfaces-ui#readme",
21
+ "bugs": {
22
+ "url": "https://github.com/teradata-labs/surfaces-ui/issues"
23
+ },
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "./react": {
34
+ "types": "./dist/react.d.ts",
35
+ "default": "./dist/react.js"
36
+ }
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "NOTICE"
41
+ ],
42
+ "peerDependencies": {
43
+ "react": ">=18"
44
+ },
45
+ "dependencies": {
46
+ "@bufbuild/protobuf": "^2.17.0",
47
+ "@surfaces-ui/data": "0.3.0",
48
+ "@surfaces-ui/proto": "0.3.0"
49
+ },
50
+ "devDependencies": {
51
+ "@testing-library/react": "^16.3.3",
52
+ "@types/react": "^19.3.0",
53
+ "@types/react-dom": "^19.3.0",
54
+ "jsdom": "^31.0.0",
55
+ "react": "^19.3.1",
56
+ "react-dom": "^19.3.1"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "react": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "publishConfig": {
64
+ "access": "public",
65
+ "provenance": true
66
+ },
67
+ "scripts": {
68
+ "build": "tsc -p tsconfig.build.json",
69
+ "typecheck": "tsc -p tsconfig.json --noEmit",
70
+ "test": "vitest run --passWithNoTests"
71
+ }
6
72
  }