@k8ordo/state 2.3.1 → 3.0.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/README.md +1 -1
- package/dist/hash/codec.d.mts +16 -0
- package/dist/hash/codec.mjs +35 -0
- package/dist/page-state.d.mts +27 -18
- package/dist/page-state.mjs +15 -4
- package/dist/store/page-store.mjs +54 -9
- package/dist/testing.d.mts +18 -0
- package/dist/testing.mjs +46 -0
- package/dist/url/codec.d.mts +3 -0
- package/dist/url/codec.mjs +1 -1
- package/dist/use-app-state.d.mts +2 -2
- package/docs/GUIDE.md +78 -5
- package/docs/llms.txt +6 -3
- package/package.json +11 -7
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ pnpm add @k8ordo/state zod
|
|
|
32
32
|
| ---------------- | ------- | -------- | ------------------------------------------------------- |
|
|
33
33
|
| `react` | ≥19.3.0 | yes | `useAppState` |
|
|
34
34
|
| `zod` | ^4.6.6 | yes | the schemas (`zod/mini` works, and is the lighter pick) |
|
|
35
|
-
| `@k8ordo/router` | ^
|
|
35
|
+
| `@k8ordo/router` | ^3.0.0 | optional | typed `href` paths from the app's route table |
|
|
36
36
|
| `typescript` | ≥7.0.0 | optional | the shipped type declarations |
|
|
37
37
|
| `@types/react` | ≥19.3.0 | optional | the shipped type declarations |
|
|
38
38
|
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { $ZodType } from "zod/v4/core";
|
|
2
|
+
export type HashCodec = {
|
|
3
|
+
fallback: unknown;
|
|
4
|
+
/** Reads `location.hash`: `''`, or the fragment with its `#`. */
|
|
5
|
+
parse: (hash: string) => unknown;
|
|
6
|
+
/** The fragment a value is written as, without `#`; `''` at the default. */
|
|
7
|
+
fragment: (value: unknown) => string;
|
|
8
|
+
/** The value as it will come back: written to a fragment and read again. */
|
|
9
|
+
salvage: (value: unknown) => unknown;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The fragment is one string, so the hash slot is one value under one schema
|
|
13
|
+
* rather than an object of fields. A fragment the schema rejects is not this
|
|
14
|
+
* state's — an anchor, most likely — and reads as the default.
|
|
15
|
+
*/
|
|
16
|
+
export declare const createHashCodec: (schema: $ZodType) => HashCodec;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { sameValue } from "../schema/object.mjs";
|
|
2
|
+
import { refuseBoolean, serializeValue } from "../url/codec.mjs";
|
|
3
|
+
import { safeParse } from "zod/v4/core";
|
|
4
|
+
// src/hash/codec.ts
|
|
5
|
+
const decodeOrKeep = (text) => {
|
|
6
|
+
try {
|
|
7
|
+
return decodeURIComponent(text);
|
|
8
|
+
} catch {
|
|
9
|
+
return text;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* The fragment is one string, so the hash slot is one value under one schema
|
|
14
|
+
* rather than an object of fields. A fragment the schema rejects is not this
|
|
15
|
+
* state's — an anchor, most likely — and reads as the default.
|
|
16
|
+
*/
|
|
17
|
+
const createHashCodec = (schema) => {
|
|
18
|
+
const absent = safeParse(schema, void 0);
|
|
19
|
+
if (!absent.success) throw new TypeError("hash must tolerate absence — add .default() or .optional()");
|
|
20
|
+
refuseBoolean(schema, "hash");
|
|
21
|
+
const fallback = absent.data;
|
|
22
|
+
const parse = (hash) => {
|
|
23
|
+
if (hash.length <= 1) return fallback;
|
|
24
|
+
const read = safeParse(schema, decodeOrKeep(hash.slice(1)));
|
|
25
|
+
return read.success ? read.data : fallback;
|
|
26
|
+
};
|
|
27
|
+
const fragment = (value) => value === void 0 || sameValue(fallback, value) ? "" : encodeURIComponent(serializeValue(schema, "hash", value));
|
|
28
|
+
return {
|
|
29
|
+
fallback,
|
|
30
|
+
parse,
|
|
31
|
+
fragment,
|
|
32
|
+
salvage: (value) => parse(`#${fragment(value)}`)
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
export { createHashCodec };
|
package/dist/page-state.d.mts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { StateSchema } from "./schema/object.mjs";
|
|
2
2
|
import { StoredCodec } from "./entry/codec.mjs";
|
|
3
|
+
import { HashCodec } from "./hash/codec.mjs";
|
|
3
4
|
import { RegisteredPath } from "./register.mjs";
|
|
4
5
|
import { UrlCodec, UrlInput } from "./url/codec.mjs";
|
|
5
|
-
import { output } from "zod/v4/core";
|
|
6
|
+
import { $ZodType, output } from "zod/v4/core";
|
|
6
7
|
export type OutputOf<Schema> = Schema extends StateSchema ? output<Schema> : Record<never, never>;
|
|
7
|
-
|
|
8
|
+
/** The one field the hash slot adds to the flat state. */
|
|
9
|
+
export type HashOf<Hash> = Hash extends $ZodType ? {
|
|
10
|
+
hash: output<Hash>;
|
|
11
|
+
} : Record<never, never>;
|
|
12
|
+
export type PageState<Url extends StateSchema | undefined = StateSchema | undefined, Entry extends StateSchema | undefined = StateSchema | undefined, Hash extends $ZodType | undefined = $ZodType | undefined> = {
|
|
8
13
|
kind: 'page';
|
|
9
14
|
/** Identity of this state: store registry slot, entry-state namespace. */
|
|
10
15
|
key: string;
|
|
@@ -12,42 +17,46 @@ export type PageState<Url extends StateSchema | undefined = StateSchema | undefi
|
|
|
12
17
|
url: Url;
|
|
13
18
|
/** The entry schema as passed. */
|
|
14
19
|
entry: Entry;
|
|
20
|
+
/** The hash schema as passed. */
|
|
21
|
+
hash: Hash;
|
|
15
22
|
/** Reads the url slot on the server. Absent params get their defaults. */
|
|
16
23
|
parseUrl: (input: UrlInput) => OutputOf<Url>;
|
|
17
24
|
/**
|
|
18
25
|
* Builds a link. Unspecified fields mean their default and defaults are
|
|
19
|
-
* omitted from the query, so canonical URLs stay short.
|
|
20
|
-
* table's terms and the URL carries Vite's `base` in
|
|
21
|
-
* literal survives in the type, which is what lets
|
|
26
|
+
* omitted from the query and the fragment, so canonical URLs stay short.
|
|
27
|
+
* The path is in the table's terms and the URL carries Vite's `base` in
|
|
28
|
+
* front of it; the path literal survives in the type, which is what lets
|
|
29
|
+
* typed-route checks pass.
|
|
22
30
|
*/
|
|
23
|
-
href: <Path extends string>(path: RegisteredPath<Path>, values?: Readonly<Partial<OutputOf<Url>>>) => Path | `${Path}?${string}
|
|
31
|
+
href: <Path extends string>(path: RegisteredPath<Path>, values?: Readonly<Partial<OutputOf<Url> & HashOf<Hash>>>) => Path | `${Path}?${string}` | (Hash extends $ZodType ? `${Path}#${string}` : never);
|
|
24
32
|
/** The query string alone (no `?`), for handrolled URL composition. */
|
|
25
33
|
search: (values?: Readonly<Partial<OutputOf<Url>>>) => string;
|
|
26
34
|
};
|
|
27
35
|
type SharedKeys<Url, Entry> = Extract<keyof OutputOf<Url>, keyof OutputOf<Entry>> & string;
|
|
36
|
+
type NamedHash<Url, Entry> = Extract<keyof OutputOf<Url> | keyof OutputOf<Entry>, 'hash'>;
|
|
28
37
|
/**
|
|
29
38
|
* The flat merged state cannot host one name twice; when it would, the error
|
|
30
39
|
* carries the offending field name instead of a bare "not assignable".
|
|
31
40
|
*/
|
|
32
|
-
type DisjointGuard<Url, Entry> =
|
|
41
|
+
type DisjointGuard<Url, Entry, Hash> = [Url, Entry, Hash] extends [undefined, undefined, undefined] ? {
|
|
42
|
+
url: 'declare at least one of url, entry and hash';
|
|
43
|
+
} : [SharedKeys<Url, Entry>] extends [never] ? [Hash] extends [undefined] ? unknown : [NamedHash<Url, Entry>] extends [never] ? unknown : {
|
|
44
|
+
hash: 'a url or entry field is named hash, the name the hash value takes in the state';
|
|
45
|
+
} : {
|
|
33
46
|
entry: `field declared in both url and entry: ${SharedKeys<Url, Entry>}`;
|
|
34
47
|
};
|
|
35
48
|
export type PageInternals = {
|
|
36
49
|
url: UrlCodec | null;
|
|
37
50
|
entry: StoredCodec | null;
|
|
38
|
-
|
|
51
|
+
hash: HashCodec | null;
|
|
52
|
+
/** url keys first, then entry keys, then `hash` — the flat snapshot's full key set. */
|
|
39
53
|
keys: readonly string[];
|
|
40
54
|
};
|
|
41
|
-
export declare function definePageState<Url extends StateSchema>(key: string, config: {
|
|
42
|
-
url
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}): PageState<undefined, Entry>;
|
|
47
|
-
export declare function definePageState<Url extends StateSchema, Entry extends StateSchema>(key: string, config: {
|
|
48
|
-
url: Url;
|
|
49
|
-
entry: Entry;
|
|
50
|
-
} & DisjointGuard<Url, Entry>): PageState<Url, Entry>;
|
|
55
|
+
export declare function definePageState<Url extends StateSchema | undefined = undefined, Entry extends StateSchema | undefined = undefined, Hash extends $ZodType | undefined = undefined>(key: string, config: {
|
|
56
|
+
url?: Url;
|
|
57
|
+
entry?: Entry;
|
|
58
|
+
hash?: Hash;
|
|
59
|
+
} & DisjointGuard<Url, Entry, Hash>): PageState<Url, Entry, Hash>;
|
|
51
60
|
/**
|
|
52
61
|
* Reads the url slot a schema describes out of a URL's search, the way
|
|
53
62
|
* `parseUrl` reads it for the definition the schema came from — defaults
|
package/dist/page-state.mjs
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { withBase } from "./base.mjs";
|
|
2
2
|
import { createStoredCodec } from "./entry/codec.mjs";
|
|
3
3
|
import { setKind } from "./store/kind.mjs";
|
|
4
|
-
import { pageInitialSnapshot, pageStoreOf } from "./store/page-store.mjs";
|
|
5
4
|
import { createUrlCodec } from "./url/codec.mjs";
|
|
5
|
+
import { createHashCodec } from "./hash/codec.mjs";
|
|
6
|
+
import { pageInitialSnapshot, pageStoreOf } from "./store/page-store.mjs";
|
|
6
7
|
// src/page-state.ts
|
|
7
8
|
function definePageState(key, config) {
|
|
8
9
|
const url = config.url === void 0 ? null : createUrlCodec(config.url);
|
|
9
10
|
const entry = config.entry === void 0 ? null : createStoredCodec(config.entry, "entry");
|
|
10
|
-
|
|
11
|
+
const hash = config.hash === void 0 ? null : createHashCodec(config.hash);
|
|
12
|
+
if (url === null && entry === null && hash === null) throw new TypeError(`"${key}" declares neither url, entry nor hash`);
|
|
13
|
+
if (hash !== null && (url?.keys.includes("hash") === true || entry?.keys.includes("hash") === true)) throw new TypeError(`"${key}" declares hash beside a url or entry field named hash — the hash value takes that name in the state`);
|
|
11
14
|
const shared = url === null || entry === null ? [] : url.keys.filter((field) => entry.keys.includes(field));
|
|
12
15
|
if (shared.length > 0) throw new TypeError(`"${key}" declares in both url and entry: ${shared.join(", ")}`);
|
|
13
16
|
const search = (values) => url === null ? "" : url.search(values ?? {});
|
|
@@ -16,18 +19,26 @@ function definePageState(key, config) {
|
|
|
16
19
|
key,
|
|
17
20
|
url: config.url,
|
|
18
21
|
entry: config.entry,
|
|
22
|
+
hash: config.hash,
|
|
19
23
|
parseUrl: (input) => url === null ? {} : url.parse(input),
|
|
20
24
|
search,
|
|
21
25
|
href: (path, values) => {
|
|
22
26
|
const query = search(values);
|
|
23
27
|
const link = withBase(path);
|
|
24
|
-
|
|
28
|
+
const located = query === "" ? link : `${link}?${query}`;
|
|
29
|
+
const fragment = hash === null ? "" : hash.fragment(values?.hash);
|
|
30
|
+
return fragment === "" ? located : `${located}#${fragment}`;
|
|
25
31
|
}
|
|
26
32
|
};
|
|
27
33
|
const page = {
|
|
28
34
|
url,
|
|
29
35
|
entry,
|
|
30
|
-
|
|
36
|
+
hash,
|
|
37
|
+
keys: [
|
|
38
|
+
...url?.keys ?? [],
|
|
39
|
+
...entry?.keys ?? [],
|
|
40
|
+
...hash === null ? [] : ["hash"]
|
|
41
|
+
]
|
|
31
42
|
};
|
|
32
43
|
setKind(def, {
|
|
33
44
|
store: () => pageStoreOf(def, page),
|
|
@@ -2,17 +2,22 @@ import { isRecord, sameValue } from "../schema/object.mjs";
|
|
|
2
2
|
import { createHandle, createStoreCore, resolvePatch, settledHandle } from "./core.mjs";
|
|
3
3
|
import { getOrCreateStore } from "./registry.mjs";
|
|
4
4
|
// src/store/page-store.ts
|
|
5
|
+
const URL_WRITE_INTERVAL = 100;
|
|
6
|
+
let lastUrlWrite = Number.NEGATIVE_INFINITY;
|
|
5
7
|
const storedEntryState = () => navigation.currentEntry?.getState();
|
|
6
8
|
const readLive = (def, page) => {
|
|
7
9
|
const url = page.url === null ? {} : page.url.parse(new URL(location.href).searchParams);
|
|
10
|
+
const hash = page.hash === null ? {} : { hash: page.hash.parse(location.hash) };
|
|
8
11
|
if (page.entry === null) return {
|
|
9
12
|
url,
|
|
10
|
-
entry: {}
|
|
13
|
+
entry: {},
|
|
14
|
+
hash
|
|
11
15
|
};
|
|
12
16
|
const stored = storedEntryState();
|
|
13
17
|
return {
|
|
14
18
|
url,
|
|
15
|
-
entry: page.entry.parse(isRecord(stored) ? stored[def.key] : void 0)
|
|
19
|
+
entry: page.entry.parse(isRecord(stored) ? stored[def.key] : void 0),
|
|
20
|
+
hash
|
|
16
21
|
};
|
|
17
22
|
};
|
|
18
23
|
/**
|
|
@@ -30,7 +35,8 @@ const createPageStore = (def, page) => {
|
|
|
30
35
|
const initial = readLive(def, page);
|
|
31
36
|
const core = createStoreCore(page.keys, {
|
|
32
37
|
...initial.url,
|
|
33
|
-
...initial.entry
|
|
38
|
+
...initial.entry,
|
|
39
|
+
...initial.hash
|
|
34
40
|
});
|
|
35
41
|
let at = livePathname();
|
|
36
42
|
const left = /* @__PURE__ */ new Map();
|
|
@@ -38,10 +44,23 @@ const createPageStore = (def, page) => {
|
|
|
38
44
|
let pending = null;
|
|
39
45
|
let pendingPush = false;
|
|
40
46
|
let handle = null;
|
|
47
|
+
let waiting;
|
|
48
|
+
const takeBatch = () => {
|
|
49
|
+
clearTimeout(waiting);
|
|
50
|
+
waiting = void 0;
|
|
51
|
+
pending = null;
|
|
52
|
+
pendingPush = false;
|
|
53
|
+
handle = null;
|
|
54
|
+
};
|
|
41
55
|
const sync = () => {
|
|
42
56
|
const pathname = livePathname();
|
|
43
57
|
let returned = false;
|
|
44
58
|
if (pathname !== at) {
|
|
59
|
+
if (handle !== null) {
|
|
60
|
+
const dropped = handle;
|
|
61
|
+
takeBatch();
|
|
62
|
+
dropped.fail(new DOMException("The page was left before the update was written", "AbortError"));
|
|
63
|
+
}
|
|
45
64
|
if ((bound.get(at) ?? 0) > 0) left.set(at, core.freeze());
|
|
46
65
|
returned = left.delete(pathname);
|
|
47
66
|
at = pathname;
|
|
@@ -51,6 +70,7 @@ const createPageStore = (def, page) => {
|
|
|
51
70
|
core.applyNext({
|
|
52
71
|
...live.url,
|
|
53
72
|
...live.entry,
|
|
73
|
+
...live.hash,
|
|
54
74
|
...pending
|
|
55
75
|
});
|
|
56
76
|
if (returned) core.touch();
|
|
@@ -64,7 +84,8 @@ const createPageStore = (def, page) => {
|
|
|
64
84
|
*/
|
|
65
85
|
const canonical = (values) => ({
|
|
66
86
|
...page.url === null ? {} : page.url.salvage(values),
|
|
67
|
-
...page.entry === null ? {} : page.entry.salvage(values)
|
|
87
|
+
...page.entry === null ? {} : page.entry.salvage(values),
|
|
88
|
+
...page.hash === null ? {} : { hash: page.hash.salvage(values.hash) }
|
|
68
89
|
});
|
|
69
90
|
const carryState = (stored, target) => {
|
|
70
91
|
if (page.entry === null) return stored;
|
|
@@ -75,21 +96,32 @@ const createPageStore = (def, page) => {
|
|
|
75
96
|
return base;
|
|
76
97
|
};
|
|
77
98
|
const flush = () => {
|
|
99
|
+
if (pending === null) return;
|
|
78
100
|
const patch = pending;
|
|
79
101
|
const push = pendingPush;
|
|
80
102
|
const current = handle;
|
|
81
|
-
pending = null;
|
|
82
|
-
pendingPush = false;
|
|
83
|
-
handle = null;
|
|
84
103
|
try {
|
|
85
104
|
const live = readLive(def, page);
|
|
86
105
|
const target = canonical({
|
|
87
106
|
...live.url,
|
|
88
107
|
...live.entry,
|
|
108
|
+
...live.hash,
|
|
89
109
|
...patch
|
|
90
110
|
});
|
|
91
|
-
const
|
|
111
|
+
const hashChanged = page.hash !== null && !sameValue(live.hash.hash, target.hash);
|
|
112
|
+
const urlChanged = hashChanged || (page.url?.keys.some((key) => !sameValue(live.url[key], target[key])) ?? false);
|
|
92
113
|
const entryChanged = page.entry?.keys.some((key) => !sameValue(live.entry[key], target[key])) ?? false;
|
|
114
|
+
if (urlChanged && !push) {
|
|
115
|
+
const wait = lastUrlWrite + URL_WRITE_INTERVAL - performance.now();
|
|
116
|
+
if (wait > 0) {
|
|
117
|
+
waiting ??= setTimeout(() => {
|
|
118
|
+
waiting = void 0;
|
|
119
|
+
flush();
|
|
120
|
+
}, wait);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
takeBatch();
|
|
93
125
|
if (!urlChanged && !entryChanged) {
|
|
94
126
|
core.applyNext(target);
|
|
95
127
|
current.settle();
|
|
@@ -106,11 +138,14 @@ const createPageStore = (def, page) => {
|
|
|
106
138
|
for (const key of page.url.keys) url.searchParams.delete(key);
|
|
107
139
|
for (const [key, value] of new URLSearchParams(page.url.search(target))) url.searchParams.append(key, value);
|
|
108
140
|
}
|
|
141
|
+
if (page.hash !== null && hashChanged) url.hash = page.hash.fragment(target.hash);
|
|
142
|
+
lastUrlWrite = performance.now();
|
|
109
143
|
current.adopt(navigation.navigate(url.href, {
|
|
110
144
|
history: push ? "push" : "replace",
|
|
111
145
|
state
|
|
112
146
|
}));
|
|
113
147
|
} catch (error) {
|
|
148
|
+
if (handle === current) takeBatch();
|
|
114
149
|
current.fail(error);
|
|
115
150
|
}
|
|
116
151
|
};
|
|
@@ -128,7 +163,14 @@ const createPageStore = (def, page) => {
|
|
|
128
163
|
queueMicrotask(flush);
|
|
129
164
|
}
|
|
130
165
|
Object.assign(pending, resolved);
|
|
131
|
-
if (options?.history === "push")
|
|
166
|
+
if (options?.history === "push") {
|
|
167
|
+
pendingPush = true;
|
|
168
|
+
if (waiting !== void 0) {
|
|
169
|
+
clearTimeout(waiting);
|
|
170
|
+
waiting = void 0;
|
|
171
|
+
queueMicrotask(flush);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
132
174
|
for (const key of Object.keys(pending)) pending[key] = echoed[key];
|
|
133
175
|
core.applyNext(echoed);
|
|
134
176
|
return handle.external;
|
|
@@ -163,6 +205,8 @@ const createPageStore = (def, page) => {
|
|
|
163
205
|
dispose: () => {
|
|
164
206
|
navigation.removeEventListener("currententrychange", sync);
|
|
165
207
|
window.removeEventListener("popstate", sync);
|
|
208
|
+
takeBatch();
|
|
209
|
+
lastUrlWrite = Number.NEGATIVE_INFINITY;
|
|
166
210
|
left.clear();
|
|
167
211
|
bound.clear();
|
|
168
212
|
core.clear();
|
|
@@ -179,6 +223,7 @@ const pageStoreOf = (def, page) => getOrCreateStore("page", def.key, () => creat
|
|
|
179
223
|
const pageInitialSnapshot = (page, initialUrl) => {
|
|
180
224
|
const base = {};
|
|
181
225
|
for (const codec of [page.url, page.entry]) if (codec !== null) for (const key of codec.keys) base[key] = codec.defaults[key];
|
|
226
|
+
if (page.hash !== null) base.hash = page.hash.fallback;
|
|
182
227
|
if (page.url !== null && initialUrl !== void 0) {
|
|
183
228
|
for (const key of page.url.keys) if (key in initialUrl) base[key] = initialUrl[key];
|
|
184
229
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type PageUrl = {
|
|
2
|
+
/** Params to add to the search the page already has, as written. */
|
|
3
|
+
search?: string;
|
|
4
|
+
/** The fragment, without its `#`. */
|
|
5
|
+
hash?: string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Stands in for a router while a test runs, and gives the page the URL the
|
|
9
|
+
* test starts from: without something intercepting, the first `update()`
|
|
10
|
+
* that changes the URL loads a document and takes the test runner with it.
|
|
11
|
+
*
|
|
12
|
+
* The search is added to what the page already has — a test runner and
|
|
13
|
+
* Storybook keep params of their own there — and in the spelling given.
|
|
14
|
+
* Returns the cleanup: the stores are emptied, which drops any write still
|
|
15
|
+
* waiting, and the URL and entry state found are put back. Unmount what was
|
|
16
|
+
* rendered first, as for `resetStateRegistry()`.
|
|
17
|
+
*/
|
|
18
|
+
export declare const mountPageUrl: ({ search, hash }?: PageUrl) => (() => void);
|
package/dist/testing.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { resetStateRegistry } from "./store/registry.mjs";
|
|
2
|
+
// src/testing.ts
|
|
3
|
+
const interceptAsRouter = (event) => {
|
|
4
|
+
if (!event.canIntercept) return;
|
|
5
|
+
if (event.hashChange && event.destination.sameDocument) return;
|
|
6
|
+
event.intercept({
|
|
7
|
+
scroll: "manual",
|
|
8
|
+
focusReset: "manual"
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
const replace = (url, state) => {
|
|
12
|
+
const moved = navigation.navigate(url, {
|
|
13
|
+
history: "replace",
|
|
14
|
+
state
|
|
15
|
+
});
|
|
16
|
+
moved.committed?.catch(() => void 0);
|
|
17
|
+
moved.finished?.catch(() => void 0);
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Stands in for a router while a test runs, and gives the page the URL the
|
|
21
|
+
* test starts from: without something intercepting, the first `update()`
|
|
22
|
+
* that changes the URL loads a document and takes the test runner with it.
|
|
23
|
+
*
|
|
24
|
+
* The search is added to what the page already has — a test runner and
|
|
25
|
+
* Storybook keep params of their own there — and in the spelling given.
|
|
26
|
+
* Returns the cleanup: the stores are emptied, which drops any write still
|
|
27
|
+
* waiting, and the URL and entry state found are put back. Unmount what was
|
|
28
|
+
* rendered first, as for `resetStateRegistry()`.
|
|
29
|
+
*/
|
|
30
|
+
const mountPageUrl = ({ search, hash } = {}) => {
|
|
31
|
+
const found = {
|
|
32
|
+
url: location.href,
|
|
33
|
+
state: navigation.currentEntry?.getState()
|
|
34
|
+
};
|
|
35
|
+
const url = new URL(found.url);
|
|
36
|
+
if (search !== void 0 && search !== "") url.search = [url.search.slice(1), search.replace(/^\?/u, "")].filter((part) => part !== "").join("&");
|
|
37
|
+
if (hash !== void 0) url.hash = hash;
|
|
38
|
+
navigation.addEventListener("navigate", interceptAsRouter);
|
|
39
|
+
if (url.href !== found.url) replace(url.href, found.state);
|
|
40
|
+
return () => {
|
|
41
|
+
resetStateRegistry();
|
|
42
|
+
replace(found.url, found.state);
|
|
43
|
+
navigation.removeEventListener("navigate", interceptAsRouter);
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
export { mountPageUrl };
|
package/dist/url/codec.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { StateSchema, StateValues } from "../schema/object.mjs";
|
|
2
|
+
import { $ZodType } from "zod/v4/core";
|
|
2
3
|
/** `URLSearchParams`, or the object shape frameworks hand to a page. */
|
|
3
4
|
export type UrlInput = URLSearchParams | Readonly<Record<string, string | readonly string[] | undefined>>;
|
|
4
5
|
export type UrlCodec = {
|
|
@@ -9,4 +10,6 @@ export type UrlCodec = {
|
|
|
9
10
|
/** Runs already-typed values through the schema, salvage included. */
|
|
10
11
|
salvage: (values: Readonly<StateValues>) => StateValues;
|
|
11
12
|
};
|
|
13
|
+
export declare const serializeValue: (schema: $ZodType, key: string, value: unknown) => string;
|
|
14
|
+
export declare const refuseBoolean: (schema: $ZodType, name: string) => void;
|
|
12
15
|
export declare const createUrlCodec: (schema: StateSchema) => UrlCodec;
|
package/dist/url/codec.mjs
CHANGED
package/dist/use-app-state.d.mts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { StateSchema } from "./schema/object.mjs";
|
|
2
2
|
import { CookieState } from "./cookie-state.mjs";
|
|
3
|
-
import { OutputOf, PageState } from "./page-state.mjs";
|
|
3
|
+
import { HashOf, OutputOf, PageState } from "./page-state.mjs";
|
|
4
4
|
import { LocalState, SessionState } from "./storage-state.mjs";
|
|
5
5
|
import { MemoryState } from "./memory-state.mjs";
|
|
6
6
|
import { UpdateHandle } from "./store/core.mjs";
|
|
7
7
|
import { UpdateOptions } from "./store/page-store.mjs";
|
|
8
8
|
import { output } from "zod/v4/core";
|
|
9
9
|
export type AnyState = PageState | LocalState | SessionState | CookieState | MemoryState;
|
|
10
|
-
type StateOf<Def> = Def extends PageState<infer Url, infer Entry> ? OutputOf<Url> & OutputOf<Entry> : Def extends LocalState<infer Schema> ? output<Schema> : Def extends SessionState<infer Schema> ? output<Schema> : Def extends CookieState<infer Schema> ? output<Schema> : Def extends MemoryState<infer Values> ? Values : never;
|
|
10
|
+
type StateOf<Def> = Def extends PageState<infer Url, infer Entry, infer Hash> ? OutputOf<Url> & OutputOf<Entry> & HashOf<Hash> : Def extends LocalState<infer Schema> ? output<Schema> : Def extends SessionState<infer Schema> ? output<Schema> : Def extends CookieState<infer Schema> ? output<Schema> : Def extends MemoryState<infer Values> ? Values : never;
|
|
11
11
|
type UrlStateOf<Def> = Def extends PageState<infer Url> ? OutputOf<Url> : never;
|
|
12
12
|
type UpdateFn<Def> = (patch: Readonly<Partial<StateOf<Def>>> | ((current: StateOf<Def>) => Partial<StateOf<Def>>), ...rest: Def extends PageState ? [options?: UpdateOptions] : []) => UpdateHandle;
|
|
13
13
|
type OptionsFor<Def> = Def extends {
|
package/docs/GUIDE.md
CHANGED
|
@@ -18,6 +18,7 @@ treats it as simply present.
|
|
|
18
18
|
| --------------------------- | ------------------- | ------------------------ | --------------------- | ---------------------------------------------- |
|
|
19
19
|
| `definePageState` — `url` | searchParams | back/forward, sharing | anyone given the URL | reads, where the router passes the search |
|
|
20
20
|
| `definePageState` — `entry` | history entry state | back/forward, reload | that tab's entry | — |
|
|
21
|
+
| `definePageState` — `hash` | the URL's fragment | back/forward, sharing | anyone given the URL | — |
|
|
21
22
|
| `defineLocalState` | localStorage | until deleted | every tab, one device | — |
|
|
22
23
|
| `defineSessionState` | sessionStorage | reload, until tab closes | that tab | — |
|
|
23
24
|
| `defineCookieState` | a cookie | 400 days from last write | every tab, one device | reads, where the page receives request cookies |
|
|
@@ -25,7 +26,7 @@ treats it as simply present.
|
|
|
25
26
|
|
|
26
27
|
`url` and `entry` are the two faces of one history entry — one visible and
|
|
27
28
|
shareable, one hidden — which is why they share a definition and update
|
|
28
|
-
atomically. Web Storage, cookies and memory are app-scope, not page-scope,
|
|
29
|
+
atomically. `hash` is the rest of that entry's URL, and travels with them. Web Storage, cookies and memory are app-scope, not page-scope,
|
|
29
30
|
which is why they are their own kinds: the grouping difference is real, so
|
|
30
31
|
the API makes it visible. sessionStorage is localStorage's per-tab twin,
|
|
31
32
|
built the same way: it survives a reload of the tab — unlike memory — and
|
|
@@ -130,6 +131,47 @@ Web Storage and the cookie hold, so keep those fields to what JSON
|
|
|
130
131
|
represents: a `z.date()` shows its `Date` after the write and falls back to
|
|
131
132
|
its default on the next load.
|
|
132
133
|
|
|
134
|
+
## The fragment — one value
|
|
135
|
+
|
|
136
|
+
A fragment is one string, so `hash` takes one schema for one value, not an
|
|
137
|
+
object of fields, and that value is the field `hash` of the state:
|
|
138
|
+
|
|
139
|
+
```tsx
|
|
140
|
+
export const deckState = definePageState('deck', {
|
|
141
|
+
url: z.object({ mode: z._default(z.enum(['view', 'present']), 'view') }),
|
|
142
|
+
hash: z._default(z.coerce.number().check(z.int(), z.gte(1)), 1),
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const [{ hash, mode }, update] = useAppState(deckState);
|
|
146
|
+
// /slides/intro#3 → hash === 3
|
|
147
|
+
update({ hash: 4 }); // → /slides/intro#4
|
|
148
|
+
deckState.href('/slides/intro', { hash: 4 }); // '/slides/intro#4'
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
It follows the url slot's rules: the schema must tolerate absence, a boolean
|
|
152
|
+
is `z.stringbool()`, the default is written as no fragment at all, `replace`
|
|
153
|
+
is the default and `{ history: 'push' }` adds an entry, and a run of writes is
|
|
154
|
+
thinned out. The value is percent-encoded on the way out, so any string is one
|
|
155
|
+
value. What differs:
|
|
156
|
+
|
|
157
|
+
- **A fragment the schema rejects is not this state's.** The browser gives a
|
|
158
|
+
fragment a meaning of its own — the element with that id — so `#main`
|
|
159
|
+
under the schema above reads as the default, `1`, and stays in the URL:
|
|
160
|
+
writing the default changes nothing, and a write to `url` or `entry` keeps
|
|
161
|
+
it. A visitor following an in-page link moves the value back to its
|
|
162
|
+
default the same way. Only a value other than the default replaces it.
|
|
163
|
+
- **The name is taken.** A `url` or `entry` field named `hash` beside a
|
|
164
|
+
`hash` slot is refused when the definition is made, and by the types.
|
|
165
|
+
- **The server never sees it.** A fragment is not sent, so the server render
|
|
166
|
+
and the hydration render show the default, in every mode; there is no
|
|
167
|
+
`parseHash`.
|
|
168
|
+
- **Setting a fragment needs no router.** It is a move within the document,
|
|
169
|
+
which the browser makes on its own, without scrolling unless an element
|
|
170
|
+
has that id. Going back to the default drops the fragment, and that is a
|
|
171
|
+
navigation the platform loads a document for unless something intercepts
|
|
172
|
+
it — `@k8ordo/router` does. A router that leaves every `hashChange` to the
|
|
173
|
+
browser reloads the page there in WebKit, which flags that move too.
|
|
174
|
+
|
|
133
175
|
## When a stored shape changes
|
|
134
176
|
|
|
135
177
|
A localStorage row or a cookie outlives the code that wrote it. On its own, a
|
|
@@ -499,7 +541,7 @@ with that error while the rendered value stays.
|
|
|
499
541
|
- **`replace` by default.** An update refines the current entry. Pass
|
|
500
542
|
`{ history: 'push' }` only for updates the back button should undo — the
|
|
501
543
|
option exists only on page state, the one kind with a navigation behind it,
|
|
502
|
-
and takes effect only when a url value changes: an entry-only write
|
|
544
|
+
and takes effect only when a url or hash value changes: an entry-only write
|
|
503
545
|
rewrites the current entry in place.
|
|
504
546
|
- **One handler, one write.** Several `update()` calls on a page, local,
|
|
505
547
|
session or cookie state made synchronously in one event handler collapse
|
|
@@ -510,6 +552,20 @@ with that error while the rendered value stays.
|
|
|
510
552
|
cookie state still write their row (creating one if none was stored).
|
|
511
553
|
Memory has nothing to batch: each call applies on the spot and returns its
|
|
512
554
|
own settled handle.
|
|
555
|
+
- **A run of url writes is thinned out.** A slider that updates a url field
|
|
556
|
+
on every input would navigate on every input, and WebKit refuses a
|
|
557
|
+
document's navigations past 200 in ten seconds, rejecting the rest with a
|
|
558
|
+
`QuotaExceededError`. So a `replace` that changes a url value within 100 ms
|
|
559
|
+
of the last url write waits for the rest of that time, and the updates made
|
|
560
|
+
meanwhile join it: one navigation carries the latest values, and they all
|
|
561
|
+
share its handle, whose `committed` settles when that navigation is in the
|
|
562
|
+
URL. The value on screen never waits — every `update()` still applies
|
|
563
|
+
synchronously. A `push` is an entry of its own and is never held back; it
|
|
564
|
+
takes what was waiting with it. An update still waiting when the page is
|
|
565
|
+
left — the URL's pathname moves — is not written, since it would land on
|
|
566
|
+
the next page's URL, and its handle rejects with an `AbortError`. Entry,
|
|
567
|
+
local, session, cookie and memory writes are not thinned; a hash write is a
|
|
568
|
+
navigation and is.
|
|
513
569
|
- **Functional form.** `update((current) => ({ page: current.page + 1 }))`
|
|
514
570
|
reads the batched state, not the committed one.
|
|
515
571
|
- **Shared ground stays shared.** A page state rewrites only its own params
|
|
@@ -749,6 +805,23 @@ Clear stored rows by the definition's `storageKey` (in its own storage area)
|
|
|
749
805
|
or `cookieName` (`await cookieStore.delete(def.cookieName)`); the Cookie
|
|
750
806
|
Store API's `change` event fires in the same tab too, so a test that writes
|
|
751
807
|
the cookie itself stands in for another tab.
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
808
|
+
A test of url or hash updates needs a router: an unintercepted
|
|
809
|
+
`navigation.navigate()` is a cross-document load that takes the test runner
|
|
810
|
+
with it. `mountPageUrl()` from `@k8ordo/state/testing` stands in for one and
|
|
811
|
+
gives the page the URL the test starts from:
|
|
812
|
+
|
|
813
|
+
```ts
|
|
814
|
+
import { mountPageUrl } from '@k8ordo/state/testing';
|
|
815
|
+
|
|
816
|
+
// Vitest runs what beforeEach returns after the test; so does Storybook
|
|
817
|
+
beforeEach(() => mountPageUrl({ search: 'q=css', hash: '3' }));
|
|
818
|
+
```
|
|
819
|
+
|
|
820
|
+
It intercepts as `@k8ordo/router` does — a move to a fragment within the
|
|
821
|
+
document is left to the browser, and neither the viewport nor the focus is
|
|
822
|
+
moved — and adds `search` to the params the page already has, in the spelling
|
|
823
|
+
given (a test runner and Storybook keep params of their own there). The
|
|
824
|
+
function it returns is the cleanup: it calls `resetStateRegistry()`, which
|
|
825
|
+
also drops a thinned write still waiting, then puts back the URL and the
|
|
826
|
+
entry state it found. It is not part of the main entry, so nothing of it
|
|
827
|
+
reaches an application's bundle.
|
package/docs/llms.txt
CHANGED
|
@@ -34,8 +34,10 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
|
|
|
34
34
|
|
|
35
35
|
## Entry point
|
|
36
36
|
|
|
37
|
-
- `@k8ordo/state` — `definePageState(key, { url?, entry? })` returns a pure
|
|
38
|
-
definition usable from server and client
|
|
37
|
+
- `@k8ordo/state` — `definePageState(key, { url?, entry?, hash? })` returns a pure
|
|
38
|
+
definition usable from server and client (`hash` is one schema for one
|
|
39
|
+
value, the URL's fragment, read as the field `hash`; a fragment it rejects
|
|
40
|
+
is an anchor and is left alone): `parseUrl(searchParams)` reads
|
|
39
41
|
the url slot typed with defaults applied and invalid values salvaged
|
|
40
42
|
(wherever the router hands a page its search — in `@k8ordo/framework`'s
|
|
41
43
|
server mode a page that exports `search = listState.url` receives the slot parsed as
|
|
@@ -87,7 +89,8 @@ When installed via npm, these docs live under `node_modules/@k8ordo/state/docs/`
|
|
|
87
89
|
it — rejects them with its error;
|
|
88
90
|
`{ history: 'push' }` exists only on page state and takes effect only when
|
|
89
91
|
a url value changes).
|
|
90
|
-
`resetStateRegistry()` clears stores between tests
|
|
92
|
+
`resetStateRegistry()` clears stores between tests, and `mountPageUrl()`
|
|
93
|
+
from `@k8ordo/state/testing` stands in for a router there. Augment
|
|
91
94
|
`interface Register { routes: typeof routes }` — the same line as for
|
|
92
95
|
`@k8ordo/router` — to check each `href` path against the route table's
|
|
93
96
|
linkable patterns segment by segment (`NavigablePath`, so a `/:locale`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@k8ordo/state",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "Declare state by where it lives — URL search params, history-entry state, localStorage, sessionStorage, a cookie, or memory. One zod schema per boundary place and a typed box for memory, over the Navigation API.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cookie",
|
|
@@ -35,6 +35,10 @@
|
|
|
35
35
|
"types": "./dist/index.d.mts",
|
|
36
36
|
"default": "./dist/index.mjs"
|
|
37
37
|
},
|
|
38
|
+
"./testing": {
|
|
39
|
+
"types": "./dist/testing.d.mts",
|
|
40
|
+
"default": "./dist/testing.mjs"
|
|
41
|
+
},
|
|
38
42
|
"./package.json": "./package.json"
|
|
39
43
|
},
|
|
40
44
|
"publishConfig": {
|
|
@@ -43,25 +47,25 @@
|
|
|
43
47
|
},
|
|
44
48
|
"devDependencies": {
|
|
45
49
|
"@arethetypeswrong/cli": "0.18.5",
|
|
46
|
-
"@k8ordo/router": "^
|
|
50
|
+
"@k8ordo/router": "^3.0.0",
|
|
47
51
|
"@types/react": "19.3.0",
|
|
48
52
|
"@types/react-dom": "19.3.0",
|
|
49
53
|
"@vitejs/plugin-basic-ssl": "2.3.0",
|
|
50
|
-
"@vitejs/plugin-react": "6.1
|
|
51
|
-
"@vitest/browser-playwright": "5.0
|
|
52
|
-
"playwright": "1.
|
|
54
|
+
"@vitejs/plugin-react": "6.2.1",
|
|
55
|
+
"@vitest/browser-playwright": "5.1.0",
|
|
56
|
+
"playwright": "1.65.0",
|
|
53
57
|
"publint": "0.3.25",
|
|
54
58
|
"react": "19.3.1",
|
|
55
59
|
"react-dom": "19.3.1",
|
|
56
60
|
"typescript": "7.0.2",
|
|
57
61
|
"vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
|
|
58
62
|
"vite-plus": "1.4.0",
|
|
59
|
-
"vitest": "5.0
|
|
63
|
+
"vitest": "5.1.0",
|
|
60
64
|
"vitest-browser-react": "2.3.0",
|
|
61
65
|
"zod": "4.6.7"
|
|
62
66
|
},
|
|
63
67
|
"peerDependencies": {
|
|
64
|
-
"@k8ordo/router": "^
|
|
68
|
+
"@k8ordo/router": "^3.0.0",
|
|
65
69
|
"@types/react": ">=19.3.0",
|
|
66
70
|
"react": ">=19.3.0",
|
|
67
71
|
"typescript": ">=7.0.0",
|