@k8ordo/state 1.2.1 → 1.4.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 +4 -2
- package/dist/cookie-state.d.mts +1 -3
- package/dist/cookie-state.mjs +7 -16
- package/dist/index.mjs +1 -1
- package/dist/memory-state.mjs +14 -5
- package/dist/page-state.d.mts +0 -1
- package/dist/page-state.mjs +8 -8
- package/dist/storage-state.d.mts +1 -2
- package/dist/storage-state.mjs +7 -8
- package/dist/store/cookie-store.d.mts +4 -2
- package/dist/store/cookie-store.mjs +12 -7
- package/dist/store/core.d.mts +16 -3
- package/dist/store/core.mjs +11 -0
- package/dist/store/kind.d.mts +27 -0
- package/dist/store/kind.mjs +19 -0
- package/dist/store/page-store.d.mts +3 -3
- package/dist/store/page-store.mjs +59 -9
- package/dist/store/storage-store.d.mts +7 -4
- package/dist/store/storage-store.mjs +4 -7
- package/dist/tree-pathname.d.mts +4 -0
- package/dist/tree-pathname.mjs +14 -0
- package/dist/use-app-state.mjs +15 -11
- package/docs/GUIDE.md +16 -2
- package/package.json +3 -3
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` | ^1.
|
|
35
|
+
| `@k8ordo/router` | ^1.4.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
|
|
|
@@ -40,7 +40,9 @@ pnpm add @k8ordo/state zod
|
|
|
40
40
|
|
|
41
41
|
The schema ships to the browser here — the client parses and serializes with
|
|
42
42
|
it — so reach for `zod/mini` unless the app already pays for classic `zod`.
|
|
43
|
-
`@k8ordo/router` is a type-only peer: it is never loaded at runtime.
|
|
43
|
+
`@k8ordo/router` is a type-only peer: it is never loaded at runtime. Under
|
|
44
|
+
it, `@k8ordo/framework` included, a page state keeps the values of the page
|
|
45
|
+
on screen while the next one loads.
|
|
44
46
|
|
|
45
47
|
## Quick Start
|
|
46
48
|
|
package/dist/cookie-state.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StateSchema } from "./schema/object.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { Versioning } from "./row/codec.mjs";
|
|
3
3
|
import { output } from "zod/v4/core";
|
|
4
4
|
//#region src/cookie-state.d.ts
|
|
5
5
|
/**
|
|
@@ -32,7 +32,5 @@ export type CookieState<Schema extends StateSchema = StateSchema> = {
|
|
|
32
32
|
*/
|
|
33
33
|
cookieValue: (values?: Readonly<Partial<output<Schema>>>) => string;
|
|
34
34
|
};
|
|
35
|
-
export declare const parseCookieText: (text: string | undefined) => unknown;
|
|
36
|
-
export declare const cookieCodecOf: (def: CookieState) => RowCodec;
|
|
37
35
|
export declare const defineCookieState: <Schema extends StateSchema>(key: string, schema: Schema, versioning?: Versioning<Schema>) => CookieState<Schema>;
|
|
38
36
|
//#endregion
|
package/dist/cookie-state.mjs
CHANGED
|
@@ -1,21 +1,9 @@
|
|
|
1
1
|
import { createRowCodec } from "./row/codec.mjs";
|
|
2
|
+
import { cookieInitialSnapshot, cookieStoreOf, parseCookieText } from "./store/cookie-store.mjs";
|
|
3
|
+
import { setKind } from "./store/kind.mjs";
|
|
2
4
|
//#region src/cookie-state.ts
|
|
3
5
|
const COOKIE_NAME_PREFIX = "k8ordo-state.";
|
|
4
6
|
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u;
|
|
5
|
-
const parseCookieText = (text) => {
|
|
6
|
-
if (text === void 0) return void 0;
|
|
7
|
-
try {
|
|
8
|
-
return JSON.parse(text);
|
|
9
|
-
} catch {
|
|
10
|
-
return;
|
|
11
|
-
}
|
|
12
|
-
};
|
|
13
|
-
const codecs = /* @__PURE__ */ new WeakMap();
|
|
14
|
-
const cookieCodecOf = (def) => {
|
|
15
|
-
const codec = codecs.get(def);
|
|
16
|
-
if (codec === void 0) throw new TypeError(`"${def.key}" was not created by defineCookieState of this module instance`);
|
|
17
|
-
return codec;
|
|
18
|
-
};
|
|
19
7
|
const defineCookieState = (key, schema, versioning) => {
|
|
20
8
|
const cookieName = `${COOKIE_NAME_PREFIX}${key}`;
|
|
21
9
|
if (!TOKEN.test(cookieName)) throw new TypeError(`"${key}" cannot name a cookie — use letters, digits and !#$%&'*+-.^_\`|~`);
|
|
@@ -28,8 +16,11 @@ const defineCookieState = (key, schema, versioning) => {
|
|
|
28
16
|
parseCookies: (cookies) => codec.read(parseCookieText(cookies.get(cookieName))).values,
|
|
29
17
|
cookieValue: (values) => JSON.stringify(codec.row(codec.salvage(values ?? {})))
|
|
30
18
|
};
|
|
31
|
-
|
|
19
|
+
setKind(def, {
|
|
20
|
+
store: () => cookieStoreOf(def, codec),
|
|
21
|
+
initial: ({ initialCookie }) => cookieInitialSnapshot(codec, initialCookie)
|
|
22
|
+
});
|
|
32
23
|
return def;
|
|
33
24
|
};
|
|
34
25
|
//#endregion
|
|
35
|
-
export {
|
|
26
|
+
export { defineCookieState };
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { resetStateRegistry } from "./store/registry.mjs";
|
|
1
2
|
import { defineCookieState } from "./cookie-state.mjs";
|
|
2
3
|
import { definePageState, urlReader } from "./page-state.mjs";
|
|
3
4
|
import { defineLocalState, defineSessionState } from "./storage-state.mjs";
|
|
4
5
|
import { defineMemoryState } from "./memory-state.mjs";
|
|
5
|
-
import { resetStateRegistry } from "./store/registry.mjs";
|
|
6
6
|
import { useAppState } from "./use-app-state.mjs";
|
|
7
7
|
export { defineCookieState, defineLocalState, defineMemoryState, definePageState, defineSessionState, resetStateRegistry, urlReader, useAppState };
|
package/dist/memory-state.mjs
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
|
+
import { setKind } from "./store/kind.mjs";
|
|
2
|
+
import { memoryInitialSnapshot, memoryStoreOf } from "./store/memory-store.mjs";
|
|
1
3
|
//#region src/memory-state.ts
|
|
2
|
-
const defineMemoryState = (key, initial) =>
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}
|
|
4
|
+
const defineMemoryState = (key, initial) => {
|
|
5
|
+
const def = {
|
|
6
|
+
kind: "memory",
|
|
7
|
+
key,
|
|
8
|
+
initial: { ...initial }
|
|
9
|
+
};
|
|
10
|
+
setKind(def, {
|
|
11
|
+
store: () => memoryStoreOf(def),
|
|
12
|
+
initial: () => memoryInitialSnapshot(def)
|
|
13
|
+
});
|
|
14
|
+
return def;
|
|
15
|
+
};
|
|
7
16
|
//#endregion
|
|
8
17
|
export { defineMemoryState };
|
package/dist/page-state.d.mts
CHANGED
|
@@ -39,7 +39,6 @@ export type PageInternals = {
|
|
|
39
39
|
/** url keys first, then entry keys — the flat snapshot's full key set. */
|
|
40
40
|
keys: readonly string[];
|
|
41
41
|
};
|
|
42
|
-
export declare const internalsOf: (def: PageState) => PageInternals;
|
|
43
42
|
export declare function definePageState<Url extends StateSchema>(key: string, config: {
|
|
44
43
|
url: Url;
|
|
45
44
|
}): PageState<Url, undefined>;
|
package/dist/page-state.mjs
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
import { withBase } from "./base.mjs";
|
|
2
2
|
import { createStoredCodec } from "./entry/codec.mjs";
|
|
3
|
+
import { setKind } from "./store/kind.mjs";
|
|
4
|
+
import { pageInitialSnapshot, pageStoreOf } from "./store/page-store.mjs";
|
|
3
5
|
import { createUrlCodec } from "./url/codec.mjs";
|
|
4
6
|
//#region src/page-state.ts
|
|
5
|
-
const internals = /* @__PURE__ */ new WeakMap();
|
|
6
|
-
const internalsOf = (def) => {
|
|
7
|
-
const found = internals.get(def);
|
|
8
|
-
if (found === void 0) throw new TypeError(`"${def.key}" was not created by definePageState of this module instance`);
|
|
9
|
-
return found;
|
|
10
|
-
};
|
|
11
7
|
function definePageState(key, config) {
|
|
12
8
|
const url = config.url === void 0 ? null : createUrlCodec(config.url);
|
|
13
9
|
const entry = config.entry === void 0 ? null : createStoredCodec(config.entry, "entry");
|
|
@@ -28,10 +24,14 @@ function definePageState(key, config) {
|
|
|
28
24
|
return query === "" ? link : `${link}?${query}`;
|
|
29
25
|
}
|
|
30
26
|
};
|
|
31
|
-
|
|
27
|
+
const page = {
|
|
32
28
|
url,
|
|
33
29
|
entry,
|
|
34
30
|
keys: [...url?.keys ?? [], ...entry?.keys ?? []]
|
|
31
|
+
};
|
|
32
|
+
setKind(def, {
|
|
33
|
+
store: () => pageStoreOf(def, page),
|
|
34
|
+
initial: ({ initialUrl }) => pageInitialSnapshot(page, initialUrl)
|
|
35
35
|
});
|
|
36
36
|
return def;
|
|
37
37
|
}
|
|
@@ -48,4 +48,4 @@ const urlReader = (schema) => {
|
|
|
48
48
|
return (input) => codec.parse(input);
|
|
49
49
|
};
|
|
50
50
|
//#endregion
|
|
51
|
-
export { definePageState,
|
|
51
|
+
export { definePageState, urlReader };
|
package/dist/storage-state.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StateSchema } from "./schema/object.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { Versioning } from "./row/codec.mjs";
|
|
3
3
|
//#region src/storage-state.d.ts
|
|
4
4
|
type StorageState<Kind extends 'local' | 'session', Schema extends StateSchema> = {
|
|
5
5
|
kind: Kind;
|
|
@@ -31,7 +31,6 @@ export type LocalState<Schema extends StateSchema = StateSchema> = StorageState<
|
|
|
31
31
|
* local state is, over the other Web Storage area.
|
|
32
32
|
*/
|
|
33
33
|
export type SessionState<Schema extends StateSchema = StateSchema> = StorageState<'session', Schema>;
|
|
34
|
-
export declare const storageCodecOf: (def: LocalState | SessionState) => RowCodec;
|
|
35
34
|
export declare const defineLocalState: <Schema extends StateSchema>(key: string, schema: Schema, versioning?: Versioning<Schema>) => LocalState<Schema>;
|
|
36
35
|
export declare const defineSessionState: <Schema extends StateSchema>(key: string, schema: Schema) => SessionState<Schema>;
|
|
37
36
|
//#endregion
|
package/dist/storage-state.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { createRowCodec } from "./row/codec.mjs";
|
|
2
|
+
import { setKind } from "./store/kind.mjs";
|
|
3
|
+
import { storageInitialSnapshot, storageStoreOf } from "./store/storage-store.mjs";
|
|
2
4
|
//#region src/storage-state.ts
|
|
3
5
|
const STORAGE_KEY_PREFIX = "k8ordo-state:";
|
|
4
6
|
/**
|
|
@@ -12,12 +14,6 @@ const inlineReadOf = (area, storageKey, version) => {
|
|
|
12
14
|
const row = `JSON.parse(${area}.getItem(${literalOf(storageKey)}))`;
|
|
13
15
|
return version === void 0 ? `(()=>{try{const v=${row};return ${isObjectExpression("v")}?v:null}catch{return null}})()` : `(()=>{try{const r=${row};const v=Array.isArray(r)&&r.length===2&&r[0]===${String(version)}?r[1]:null;return ${isObjectExpression("v")}?v:null}catch{return null}})()`;
|
|
14
16
|
};
|
|
15
|
-
const codecs = /* @__PURE__ */ new WeakMap();
|
|
16
|
-
const storageCodecOf = (def) => {
|
|
17
|
-
const codec = codecs.get(def);
|
|
18
|
-
if (codec === void 0) throw new TypeError(`"${def.key}" was not created by ${def.kind === "local" ? "defineLocalState" : "defineSessionState"} of this module instance`);
|
|
19
|
-
return codec;
|
|
20
|
-
};
|
|
21
17
|
const defineStorageState = (kind, area, key, schema, versioning) => {
|
|
22
18
|
const storageKey = `${STORAGE_KEY_PREFIX}${key}`;
|
|
23
19
|
const codec = createRowCodec(schema, kind, key, versioning);
|
|
@@ -28,10 +24,13 @@ const defineStorageState = (kind, area, key, schema, versioning) => {
|
|
|
28
24
|
storageKey,
|
|
29
25
|
inlineRead: () => inlineReadOf(area, storageKey, codec.version)
|
|
30
26
|
};
|
|
31
|
-
|
|
27
|
+
setKind(def, {
|
|
28
|
+
store: () => storageStoreOf(def, codec),
|
|
29
|
+
initial: () => storageInitialSnapshot(codec)
|
|
30
|
+
});
|
|
32
31
|
return def;
|
|
33
32
|
};
|
|
34
33
|
const defineLocalState = (key, schema, versioning) => defineStorageState("local", "localStorage", key, schema, versioning);
|
|
35
34
|
const defineSessionState = (key, schema) => defineStorageState("session", "sessionStorage", key, schema, void 0);
|
|
36
35
|
//#endregion
|
|
37
|
-
export { defineLocalState, defineSessionState
|
|
36
|
+
export { defineLocalState, defineSessionState };
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { StateValues } from "../schema/object.mjs";
|
|
2
|
+
import { RowCodec } from "../row/codec.mjs";
|
|
2
3
|
import { CookieState } from "../cookie-state.mjs";
|
|
3
4
|
import { Store } from "./core.mjs";
|
|
4
5
|
//#region src/store/cookie-store.d.ts
|
|
5
|
-
export declare const
|
|
6
|
+
export declare const parseCookieText: (text: string | undefined) => unknown;
|
|
7
|
+
export declare const cookieStoreOf: (def: CookieState, codec: RowCodec) => Store;
|
|
6
8
|
/**
|
|
7
9
|
* What SSR and the hydration render see: the values the server read from the
|
|
8
10
|
* request's cookies when the caller passed them down; the defaults otherwise.
|
|
9
11
|
* Pure on purpose: the server must never touch `document` or create a store.
|
|
10
12
|
*/
|
|
11
|
-
export declare const cookieInitialSnapshot: (
|
|
13
|
+
export declare const cookieInitialSnapshot: (codec: RowCodec, initialCookie: Readonly<StateValues> | undefined) => StateValues;
|
|
12
14
|
//#endregion
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { cookieCodecOf, parseCookieText } from "../cookie-state.mjs";
|
|
2
1
|
import { createHandle, createStoreCore, resolvePatch } from "./core.mjs";
|
|
3
2
|
import { getOrCreateStore } from "./registry.mjs";
|
|
4
3
|
//#region src/store/cookie-store.ts
|
|
@@ -9,6 +8,14 @@ const rawCookie = (name) => {
|
|
|
9
8
|
if (at !== -1 && part.slice(0, at).trim() === name) return part.slice(at + 1).trim();
|
|
10
9
|
}
|
|
11
10
|
};
|
|
11
|
+
const parseCookieText = (text) => {
|
|
12
|
+
if (text === void 0) return void 0;
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(text);
|
|
15
|
+
} catch {
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
12
19
|
const decoded = (raw) => {
|
|
13
20
|
if (raw === void 0) return void 0;
|
|
14
21
|
try {
|
|
@@ -17,8 +24,7 @@ const decoded = (raw) => {
|
|
|
17
24
|
return;
|
|
18
25
|
}
|
|
19
26
|
};
|
|
20
|
-
const createCookieStore = (def) => {
|
|
21
|
-
const codec = cookieCodecOf(def);
|
|
27
|
+
const createCookieStore = (def, codec) => {
|
|
22
28
|
const { cookieName } = def;
|
|
23
29
|
const readRow = () => codec.read(parseCookieText(decoded(rawCookie(cookieName))));
|
|
24
30
|
const read = () => readRow().values;
|
|
@@ -111,14 +117,13 @@ const createCookieStore = (def) => {
|
|
|
111
117
|
}
|
|
112
118
|
};
|
|
113
119
|
};
|
|
114
|
-
const cookieStoreOf = (def) => getOrCreateStore("cookie", def.key, () => createCookieStore(def));
|
|
120
|
+
const cookieStoreOf = (def, codec) => getOrCreateStore("cookie", def.key, () => createCookieStore(def, codec));
|
|
115
121
|
/**
|
|
116
122
|
* What SSR and the hydration render see: the values the server read from the
|
|
117
123
|
* request's cookies when the caller passed them down; the defaults otherwise.
|
|
118
124
|
* Pure on purpose: the server must never touch `document` or create a store.
|
|
119
125
|
*/
|
|
120
|
-
const cookieInitialSnapshot = (
|
|
121
|
-
const codec = cookieCodecOf(def);
|
|
126
|
+
const cookieInitialSnapshot = (codec, initialCookie) => {
|
|
122
127
|
const base = { ...codec.defaults };
|
|
123
128
|
if (initialCookie !== void 0) {
|
|
124
129
|
for (const key of codec.keys) if (key in initialCookie) base[key] = initialCookie[key];
|
|
@@ -126,4 +131,4 @@ const cookieInitialSnapshot = (def, initialCookie) => {
|
|
|
126
131
|
return base;
|
|
127
132
|
};
|
|
128
133
|
//#endregion
|
|
129
|
-
export { cookieInitialSnapshot, cookieStoreOf };
|
|
134
|
+
export { cookieInitialSnapshot, cookieStoreOf, parseCookieText };
|
package/dist/store/core.d.mts
CHANGED
|
@@ -15,12 +15,17 @@ export type UpdateHandle = {
|
|
|
15
15
|
finished: Promise<void>;
|
|
16
16
|
};
|
|
17
17
|
export type Patch = StateValues | ((current: StateValues) => StateValues);
|
|
18
|
+
/**
|
|
19
|
+
* `tree` is the pathname the tree a caller renders in was applied for, which
|
|
20
|
+
* an intercepting router provides (`tree-pathname.ts`) — only a page store
|
|
21
|
+
* reads it.
|
|
22
|
+
*/
|
|
18
23
|
export type Store = {
|
|
19
|
-
subscribe: (keys: readonly string[] | null, notify: () => void) => () => void;
|
|
20
|
-
getSnapshot: (sig: string, keys: readonly string[] | null) => StateValues;
|
|
24
|
+
subscribe: (keys: readonly string[] | null, notify: () => void, tree?: string | null) => () => void;
|
|
25
|
+
getSnapshot: (sig: string, keys: readonly string[] | null, tree?: string | null) => StateValues;
|
|
21
26
|
update: (patch: Patch, options?: {
|
|
22
27
|
history?: 'push' | 'replace';
|
|
23
|
-
}) => UpdateHandle;
|
|
28
|
+
}, tree?: string | null) => UpdateHandle;
|
|
24
29
|
dispose: () => void;
|
|
25
30
|
};
|
|
26
31
|
export type Handle = {
|
|
@@ -33,8 +38,16 @@ export type Handle = {
|
|
|
33
38
|
}) => void;
|
|
34
39
|
};
|
|
35
40
|
export declare const createHandle: () => Handle;
|
|
41
|
+
/** A snapshot held still, with the picks already handed out for it. */
|
|
42
|
+
export type Frozen = {
|
|
43
|
+
readonly values: StateValues;
|
|
44
|
+
readonly picks: Map<string, StateValues>;
|
|
45
|
+
};
|
|
36
46
|
export type StoreCore = {
|
|
37
47
|
snapshot: () => StateValues;
|
|
48
|
+
freeze: () => Frozen;
|
|
49
|
+
/** Notifies every listener, whatever moved. */
|
|
50
|
+
touch: () => void;
|
|
38
51
|
applyNext: (next: StateValues) => void;
|
|
39
52
|
subscribe: Store['subscribe'];
|
|
40
53
|
getSnapshot: Store['getSnapshot'];
|
package/dist/store/core.mjs
CHANGED
|
@@ -47,6 +47,17 @@ const createStoreCore = (keys, initial) => {
|
|
|
47
47
|
let snapshot = initial;
|
|
48
48
|
return {
|
|
49
49
|
snapshot: () => snapshot,
|
|
50
|
+
freeze: () => {
|
|
51
|
+
const held = /* @__PURE__ */ new Map();
|
|
52
|
+
for (const [sig, pick] of picks) held.set(sig, pick.value);
|
|
53
|
+
return {
|
|
54
|
+
values: snapshot,
|
|
55
|
+
picks: held
|
|
56
|
+
};
|
|
57
|
+
},
|
|
58
|
+
touch: () => {
|
|
59
|
+
for (const listener of listeners) listener.notify();
|
|
60
|
+
},
|
|
50
61
|
applyNext: (next) => {
|
|
51
62
|
const changed = [];
|
|
52
63
|
const merged = {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { StateValues } from "../schema/object.mjs";
|
|
2
|
+
import { Store } from "./core.mjs";
|
|
3
|
+
//#region src/store/kind.d.ts
|
|
4
|
+
/** What `useAppState` needs of a definition beyond its public shape. */
|
|
5
|
+
export type Kind = {
|
|
6
|
+
/** The definition's store in the browser, made the first time it is read. */
|
|
7
|
+
readonly store: () => Store;
|
|
8
|
+
/** What the server render and the hydration render show. */
|
|
9
|
+
readonly initial: (options: {
|
|
10
|
+
readonly initialUrl?: Readonly<StateValues> | undefined;
|
|
11
|
+
readonly initialCookie?: Readonly<StateValues> | undefined;
|
|
12
|
+
}) => StateValues;
|
|
13
|
+
};
|
|
14
|
+
declare const DEFINERS: {
|
|
15
|
+
readonly page: 'definePageState';
|
|
16
|
+
readonly local: 'defineLocalState';
|
|
17
|
+
readonly session: 'defineSessionState';
|
|
18
|
+
readonly cookie: 'defineCookieState';
|
|
19
|
+
readonly memory: 'defineMemoryState';
|
|
20
|
+
};
|
|
21
|
+
export declare const setKind: (def: object, kind: Kind) => void;
|
|
22
|
+
export declare const kindOf: (def: {
|
|
23
|
+
readonly kind: keyof typeof DEFINERS;
|
|
24
|
+
readonly key: string;
|
|
25
|
+
}) => Kind;
|
|
26
|
+
//#endregion
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/store/kind.ts
|
|
2
|
+
const DEFINERS = {
|
|
3
|
+
page: "definePageState",
|
|
4
|
+
local: "defineLocalState",
|
|
5
|
+
session: "defineSessionState",
|
|
6
|
+
cookie: "defineCookieState",
|
|
7
|
+
memory: "defineMemoryState"
|
|
8
|
+
};
|
|
9
|
+
const kinds = /* @__PURE__ */ new WeakMap();
|
|
10
|
+
const setKind = (def, kind) => {
|
|
11
|
+
kinds.set(def, kind);
|
|
12
|
+
};
|
|
13
|
+
const kindOf = (def) => {
|
|
14
|
+
const found = kinds.get(def);
|
|
15
|
+
if (found === void 0) throw new TypeError(`"${def.key}" was not created by ${DEFINERS[def.kind]} of this module instance`);
|
|
16
|
+
return found;
|
|
17
|
+
};
|
|
18
|
+
//#endregion
|
|
19
|
+
export { kindOf, setKind };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { StateValues } from "../schema/object.mjs";
|
|
2
|
-
import { PageState } from "../page-state.mjs";
|
|
2
|
+
import { PageInternals, PageState } from "../page-state.mjs";
|
|
3
3
|
import { Store } from "./core.mjs";
|
|
4
4
|
//#region src/store/page-store.d.ts
|
|
5
5
|
export type UpdateOptions = {
|
|
@@ -11,12 +11,12 @@ export type UpdateOptions = {
|
|
|
11
11
|
*/
|
|
12
12
|
history?: 'push' | 'replace';
|
|
13
13
|
};
|
|
14
|
-
export declare const pageStoreOf: (def: PageState) => Store;
|
|
14
|
+
export declare const pageStoreOf: (def: PageState, page: PageInternals) => Store;
|
|
15
15
|
/**
|
|
16
16
|
* What SSR and the hydration render see: the RSC-parsed url when the caller
|
|
17
17
|
* passed one down; defaults for everything else — the entry slot never
|
|
18
18
|
* reaches the server. Pure on purpose: the server must never touch
|
|
19
19
|
* `navigation` or create a store.
|
|
20
20
|
*/
|
|
21
|
-
export declare const pageInitialSnapshot: (
|
|
21
|
+
export declare const pageInitialSnapshot: (page: PageInternals, initialUrl: Readonly<StateValues> | undefined) => StateValues;
|
|
22
22
|
//#endregion
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { isRecord, sameValue } from "../schema/object.mjs";
|
|
2
|
-
import { internalsOf } from "../page-state.mjs";
|
|
3
2
|
import { createHandle, createStoreCore, resolvePatch } from "./core.mjs";
|
|
4
3
|
import { getOrCreateStore } from "./registry.mjs";
|
|
5
4
|
//#region src/store/page-store.ts
|
|
@@ -13,18 +12,40 @@ const readLive = (def, page) => {
|
|
|
13
12
|
}
|
|
14
13
|
return live;
|
|
15
14
|
};
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
/**
|
|
16
|
+
* The URL's pathname as the router compares a tree's: a trailing slash is
|
|
17
|
+
* not another page. `@k8ordo/router`'s `normalizePathname`, spelled again —
|
|
18
|
+
* the router is a peer this package only reads types from.
|
|
19
|
+
*/
|
|
20
|
+
const livePathname = () => {
|
|
21
|
+
const { pathname } = location;
|
|
22
|
+
let end = pathname.length;
|
|
23
|
+
while (end > 1 && pathname.charAt(end - 1) === "/") end -= 1;
|
|
24
|
+
return pathname.slice(0, end);
|
|
25
|
+
};
|
|
26
|
+
const createPageStore = (def, page) => {
|
|
18
27
|
const core = createStoreCore(page.keys, readLive(def, page));
|
|
28
|
+
let at = livePathname();
|
|
29
|
+
const left = /* @__PURE__ */ new Map();
|
|
30
|
+
const bound = /* @__PURE__ */ new Map();
|
|
19
31
|
let pending = null;
|
|
20
32
|
let pendingPush = false;
|
|
21
33
|
let handle = null;
|
|
22
34
|
const sync = () => {
|
|
35
|
+
const pathname = livePathname();
|
|
36
|
+
let returned = false;
|
|
37
|
+
if (pathname !== at) {
|
|
38
|
+
if ((bound.get(at) ?? 0) > 0) left.set(at, core.freeze());
|
|
39
|
+
returned = left.delete(pathname);
|
|
40
|
+
at = pathname;
|
|
41
|
+
for (const tree of left.keys()) if (!bound.has(tree)) left.delete(tree);
|
|
42
|
+
}
|
|
23
43
|
const live = readLive(def, page);
|
|
24
44
|
core.applyNext(pending === null ? live : {
|
|
25
45
|
...live,
|
|
26
46
|
...pending
|
|
27
47
|
});
|
|
48
|
+
if (returned) core.touch();
|
|
28
49
|
};
|
|
29
50
|
navigation.addEventListener("currententrychange", sync);
|
|
30
51
|
/**
|
|
@@ -86,7 +107,12 @@ const createPageStore = (def) => {
|
|
|
86
107
|
current.fail(error);
|
|
87
108
|
}
|
|
88
109
|
};
|
|
89
|
-
const update = (patch, options) => {
|
|
110
|
+
const update = (patch, options, tree) => {
|
|
111
|
+
if (tree !== void 0 && tree !== null && tree !== at) {
|
|
112
|
+
const dropped = createHandle();
|
|
113
|
+
dropped.settle();
|
|
114
|
+
return dropped.external;
|
|
115
|
+
}
|
|
90
116
|
const resolved = resolvePatch(patch, core.snapshot(), page.keys, def.key);
|
|
91
117
|
const echoed = canonical({
|
|
92
118
|
...core.snapshot(),
|
|
@@ -104,25 +130,49 @@ const createPageStore = (def) => {
|
|
|
104
130
|
core.applyNext(echoed);
|
|
105
131
|
return handle.external;
|
|
106
132
|
};
|
|
133
|
+
const subscribe = (keys, notify, tree) => {
|
|
134
|
+
const unsubscribe = core.subscribe(keys, notify);
|
|
135
|
+
if (tree === void 0 || tree === null) return unsubscribe;
|
|
136
|
+
bound.set(tree, (bound.get(tree) ?? 0) + 1);
|
|
137
|
+
return () => {
|
|
138
|
+
unsubscribe();
|
|
139
|
+
const rest = (bound.get(tree) ?? 1) - 1;
|
|
140
|
+
if (rest > 0) bound.set(tree, rest);
|
|
141
|
+
else bound.delete(tree);
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
const getSnapshot = (sig, keys, tree) => {
|
|
145
|
+
const held = tree === void 0 || tree === null || tree === at ? void 0 : left.get(tree);
|
|
146
|
+
if (held === void 0) return core.getSnapshot(sig, keys);
|
|
147
|
+
if (keys === null) return held.values;
|
|
148
|
+
let pick = held.picks.get(sig);
|
|
149
|
+
if (pick === void 0) {
|
|
150
|
+
pick = {};
|
|
151
|
+
for (const key of keys) pick[key] = held.values[key];
|
|
152
|
+
held.picks.set(sig, pick);
|
|
153
|
+
}
|
|
154
|
+
return pick;
|
|
155
|
+
};
|
|
107
156
|
return {
|
|
108
|
-
subscribe
|
|
109
|
-
getSnapshot
|
|
157
|
+
subscribe,
|
|
158
|
+
getSnapshot,
|
|
110
159
|
update,
|
|
111
160
|
dispose: () => {
|
|
112
161
|
navigation.removeEventListener("currententrychange", sync);
|
|
162
|
+
left.clear();
|
|
163
|
+
bound.clear();
|
|
113
164
|
core.clear();
|
|
114
165
|
}
|
|
115
166
|
};
|
|
116
167
|
};
|
|
117
|
-
const pageStoreOf = (def) => getOrCreateStore("page", def.key, () => createPageStore(def));
|
|
168
|
+
const pageStoreOf = (def, page) => getOrCreateStore("page", def.key, () => createPageStore(def, page));
|
|
118
169
|
/**
|
|
119
170
|
* What SSR and the hydration render see: the RSC-parsed url when the caller
|
|
120
171
|
* passed one down; defaults for everything else — the entry slot never
|
|
121
172
|
* reaches the server. Pure on purpose: the server must never touch
|
|
122
173
|
* `navigation` or create a store.
|
|
123
174
|
*/
|
|
124
|
-
const pageInitialSnapshot = (
|
|
125
|
-
const page = internalsOf(def);
|
|
175
|
+
const pageInitialSnapshot = (page, initialUrl) => {
|
|
126
176
|
const base = {};
|
|
127
177
|
for (const codec of [page.url, page.entry]) if (codec !== null) for (const key of codec.keys) base[key] = codec.defaults[key];
|
|
128
178
|
if (page.url !== null && initialUrl !== void 0) {
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { StateValues } from "../schema/object.mjs";
|
|
2
|
+
import { RowCodec } from "../row/codec.mjs";
|
|
2
3
|
import { LocalState, SessionState } from "../storage-state.mjs";
|
|
3
4
|
import { Store } from "./core.mjs";
|
|
4
5
|
//#region src/store/storage-store.d.ts
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
/** What a store reads off a local or a session definition. */
|
|
7
|
+
type Stored = Pick<LocalState | SessionState, 'kind' | 'key' | 'storageKey'>;
|
|
8
|
+
export declare const storageStoreOf: (def: Stored, codec: RowCodec) => Store;
|
|
7
9
|
/** SSR and hydration see the defaults — the server has no Web Storage. */
|
|
8
|
-
export declare const storageInitialSnapshot: (
|
|
9
|
-
//#endregion
|
|
10
|
+
export declare const storageInitialSnapshot: (codec: RowCodec) => StateValues;
|
|
11
|
+
//#endregion
|
|
12
|
+
export {};
|
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
import { storageCodecOf } from "../storage-state.mjs";
|
|
2
1
|
import { createHandle, createStoreCore, resolvePatch } from "./core.mjs";
|
|
3
2
|
import { getOrCreateStore } from "./registry.mjs";
|
|
4
3
|
//#region src/store/storage-store.ts
|
|
5
|
-
const createStorageStore = (def, storage) => {
|
|
6
|
-
const codec = storageCodecOf(def);
|
|
4
|
+
const createStorageStore = (def, codec, storage) => {
|
|
7
5
|
const { storageKey } = def;
|
|
8
6
|
const write = (values) => {
|
|
9
7
|
storage.setItem(storageKey, JSON.stringify(codec.row(values)));
|
|
@@ -89,9 +87,8 @@ const createStorageStore = (def, storage) => {
|
|
|
89
87
|
}
|
|
90
88
|
};
|
|
91
89
|
};
|
|
92
|
-
const
|
|
93
|
-
const sessionStoreOf = (def) => getOrCreateStore("session", def.key, () => createStorageStore(def, sessionStorage));
|
|
90
|
+
const storageStoreOf = (def, codec) => getOrCreateStore(def.kind, def.key, () => createStorageStore(def, codec, def.kind === "local" ? localStorage : sessionStorage));
|
|
94
91
|
/** SSR and hydration see the defaults — the server has no Web Storage. */
|
|
95
|
-
const storageInitialSnapshot = (
|
|
92
|
+
const storageInitialSnapshot = (codec) => ({ ...codec.defaults });
|
|
96
93
|
//#endregion
|
|
97
|
-
export {
|
|
94
|
+
export { storageInitialSnapshot, storageStoreOf };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { createContext } from "react";
|
|
3
|
+
//#region src/tree-pathname.ts
|
|
4
|
+
/**
|
|
5
|
+
* The pathname the tree a component renders in was applied for, in the URL's
|
|
6
|
+
* terms, or `null` where no router says. Under interception the URL commits
|
|
7
|
+
* before the next tree arrives, so the two differ exactly while the tree on
|
|
8
|
+
* screen is being left. `@k8ordo/router`'s `<Router>` and
|
|
9
|
+
* `@k8ordo/framework`'s runtime provide it.
|
|
10
|
+
*/
|
|
11
|
+
const KEY = Symbol.for("@k8ordo/router/tree-pathname");
|
|
12
|
+
const TreePathname = globalThis[KEY] ??= createContext(null);
|
|
13
|
+
//#endregion
|
|
14
|
+
export { TreePathname };
|
package/dist/use-app-state.mjs
CHANGED
|
@@ -1,23 +1,27 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { localStoreOf, sessionStoreOf, storageInitialSnapshot } from "./store/storage-store.mjs";
|
|
6
|
-
import { useCallback, useMemo, useSyncExternalStore } from "react";
|
|
2
|
+
import { kindOf } from "./store/kind.mjs";
|
|
3
|
+
import { TreePathname } from "./tree-pathname.mjs";
|
|
4
|
+
import { use, useCallback, useMemo, useSyncExternalStore } from "react";
|
|
7
5
|
//#region src/use-app-state.ts
|
|
8
|
-
const storeOf = (def) =>
|
|
9
|
-
const initialOf = (def, options) =>
|
|
6
|
+
const storeOf = (def) => kindOf(def).store();
|
|
7
|
+
const initialOf = (def, options) => kindOf(def).initial(options ?? {});
|
|
10
8
|
const FULL = "*";
|
|
11
9
|
function useAppState(def, keysOrOptions, maybeOptions) {
|
|
12
10
|
const gotKeys = Array.isArray(keysOrOptions);
|
|
13
11
|
const options = gotKeys ? maybeOptions : keysOrOptions;
|
|
14
12
|
const sig = gotKeys ? JSON.stringify(keysOrOptions.toSorted()) : FULL;
|
|
15
13
|
const keys = useMemo(() => sig === FULL ? null : JSON.parse(sig), [sig]);
|
|
16
|
-
const
|
|
17
|
-
const
|
|
14
|
+
const tree = def.kind === "page" ? use(TreePathname) : null;
|
|
15
|
+
const subscribe = useCallback((notify) => storeOf(def).subscribe(keys, notify, tree), [
|
|
16
|
+
def,
|
|
17
|
+
keys,
|
|
18
|
+
tree
|
|
19
|
+
]);
|
|
20
|
+
const getSnapshot = useCallback(() => storeOf(def).getSnapshot(sig, keys, tree), [
|
|
18
21
|
def,
|
|
19
22
|
sig,
|
|
20
|
-
keys
|
|
23
|
+
keys,
|
|
24
|
+
tree
|
|
21
25
|
]);
|
|
22
26
|
const initialUrl = options?.initialUrl;
|
|
23
27
|
const initialCookie = options?.initialCookie;
|
|
@@ -37,7 +41,7 @@ function useAppState(def, keysOrOptions, maybeOptions) {
|
|
|
37
41
|
keys
|
|
38
42
|
]);
|
|
39
43
|
const getServerSnapshot = useCallback(() => serverSnapshot, [serverSnapshot]);
|
|
40
|
-
return [useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot), useCallback((patch, updateOptions) => storeOf(def).update(patch, updateOptions), [def])];
|
|
44
|
+
return [useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot), useCallback((patch, updateOptions) => storeOf(def).update(patch, updateOptions, tree), [def, tree])];
|
|
41
45
|
}
|
|
42
46
|
//#endregion
|
|
43
47
|
export { useAppState };
|
package/docs/GUIDE.md
CHANGED
|
@@ -263,7 +263,9 @@ rejected field salvaged — and, because the page is rendered for the search it
|
|
|
263
263
|
was given, a navigation that moves the search loads that page again: a GET
|
|
264
264
|
form, a link, or a url `update()`. That load is a state change otherwise — no
|
|
265
265
|
scroll, no focus reset, nothing remounts — and `update().finished` settles
|
|
266
|
-
once the page is on screen with the new search.
|
|
266
|
+
once the page is on screen with the new search. Going back or forward to
|
|
267
|
+
another search of the page loads it again too, and once it is on screen the
|
|
268
|
+
viewport returns to where that entry was left. The router's usual shortcut,
|
|
267
269
|
a same-pathname navigation that loads nothing, still holds for every page
|
|
268
270
|
that did not declare `search`, and for a search that did not move.
|
|
269
271
|
|
|
@@ -547,13 +549,25 @@ navigation that keeps the pathname is a state change and not a page change:
|
|
|
547
549
|
the router intercepts it without a load, nothing remounts, and scroll and
|
|
548
550
|
focus stay where they are. `finished` therefore resolves once that navigation
|
|
549
551
|
settles, with no fetch or render behind it, since `update()` already rendered
|
|
550
|
-
the new values
|
|
552
|
+
the new values. Back and forward to such an entry restore the position it
|
|
553
|
+
was left at, once the page has rendered that entry's values — unless the page showing exports `search` in
|
|
551
554
|
server mode and the search moved: then the page loads again, in place,
|
|
552
555
|
and `finished` waits for it to be on screen. On a router that does not intercept the Navigation API
|
|
553
556
|
(Next.js today), the same call is a full document load: use links and GET
|
|
554
557
|
forms for url changes there, which is this package's preferred grain anyway.
|
|
555
558
|
There is deliberately no history-API fallback.
|
|
556
559
|
|
|
560
|
+
A page state reads the URL of the page it renders in. Under
|
|
561
|
+
`@k8ordo/router` the URL commits before the next page arrives, and the page
|
|
562
|
+
being left stays on screen until it does: that page keeps the values its
|
|
563
|
+
URL had as it was left, and the next page renders with its own URL's from
|
|
564
|
+
its first render. A move that keeps the pathname is followed at once, and so
|
|
565
|
+
is the URL coming back to the page on screen. An `update()` called from the
|
|
566
|
+
page being left writes nothing — what it shows is no longer the URL's — and
|
|
567
|
+
its `finished` resolves at once. Under a router that does not say which page
|
|
568
|
+
a component renders in (Next.js, or a host of your own built on
|
|
569
|
+
`useInterceptedNavigation`), a page state follows the URL.
|
|
570
|
+
|
|
557
571
|
Keystrokes do not belong in the URL. Let the DOM or local React state hold
|
|
558
572
|
the draft and call `update()` at commit points — submit, blur, pagination —
|
|
559
573
|
the same division `@k8ordo/form` draws.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@k8ordo/state",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.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",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@arethetypeswrong/cli": "0.18.5",
|
|
46
|
-
"@k8ordo/router": "^1.
|
|
46
|
+
"@k8ordo/router": "^1.4.0",
|
|
47
47
|
"@types/react": "19.3.0",
|
|
48
48
|
"@types/react-dom": "19.3.0",
|
|
49
49
|
"@vitejs/plugin-basic-ssl": "2.3.0",
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"zod": "4.6.7"
|
|
62
62
|
},
|
|
63
63
|
"peerDependencies": {
|
|
64
|
-
"@k8ordo/router": "^1.
|
|
64
|
+
"@k8ordo/router": "^1.4.0",
|
|
65
65
|
"@types/react": ">=19.3.0",
|
|
66
66
|
"react": ">=19.3.0",
|
|
67
67
|
"typescript": ">=7.0.0",
|