@k8ordo/state 2.3.1 → 4.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.
@@ -2,23 +2,28 @@ 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
  /**
19
24
  * The URL's pathname as the router compares a tree's: a trailing slash is
20
25
  * not another page. `@k8ordo/router`'s `normalizePathname`, spelled again —
21
- * the router is a peer this package only reads types from.
26
+ * this package never imports the router.
22
27
  */
23
28
  const livePathname = () => {
24
29
  const { pathname } = location;
@@ -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 urlChanged = page.url?.keys.some((key) => !sameValue(live.url[key], target[key])) ?? false;
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") pendingPush = true;
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
  }
@@ -1,5 +1,5 @@
1
- import { StateValues } from "../schema/object.mjs";
2
1
  import { RowCodec } from "../row/codec.mjs";
2
+ import { StateValues } from "../schema/object.mjs";
3
3
  import { LocalState, SessionState } from "../storage-state.mjs";
4
4
  import { Store } from "./core.mjs";
5
5
  /** What a store reads off a local or a session definition. */
@@ -27,9 +27,17 @@ const createStorageStore = (def, codec, storage) => {
27
27
  } catch {
28
28
  row = void 0;
29
29
  }
30
- return codec.read(row);
30
+ return {
31
+ ...codec.read(row),
32
+ text
33
+ };
34
+ };
35
+ let reported;
36
+ const reportFailed = (text, error) => {
37
+ if (text === reported) return;
38
+ reported = text;
39
+ reportError(error);
31
40
  };
32
- const read = () => readRow().values;
33
41
  const upgrade = () => {
34
42
  queueMicrotask(() => {
35
43
  try {
@@ -42,10 +50,14 @@ const createStorageStore = (def, codec, storage) => {
42
50
  try {
43
51
  first = readRow();
44
52
  } catch {
45
- first = codec.read(void 0);
53
+ first = {
54
+ ...codec.read(void 0),
55
+ text: null
56
+ };
46
57
  }
47
58
  const core = createStoreCore(codec.keys, first.values);
48
59
  if (first.stale) upgrade();
60
+ if (first.failed) reportFailed(first.text, first.error);
49
61
  let pending = null;
50
62
  let handle = null;
51
63
  const onStorage = (event) => {
@@ -57,6 +69,10 @@ const createStorageStore = (def, codec, storage) => {
57
69
  } catch {
58
70
  return;
59
71
  }
72
+ if (row.failed) {
73
+ reportFailed(row.text, row.error);
74
+ return;
75
+ }
60
76
  const { values: fresh, stale } = row;
61
77
  if (stale) upgrade();
62
78
  core.applyNext(pending === null ? fresh : {
@@ -71,8 +87,13 @@ const createStorageStore = (def, codec, storage) => {
71
87
  pending = null;
72
88
  handle = null;
73
89
  try {
90
+ const row = readRow();
91
+ if (row.failed) {
92
+ current.fail(row.error);
93
+ return;
94
+ }
74
95
  const target = codec.salvage({
75
- ...read(),
96
+ ...row.values,
76
97
  ...patch
77
98
  });
78
99
  const values = {};
@@ -0,0 +1,20 @@
1
+ import { resetStateRegistry } from "./store/registry.mjs";
2
+ export type PageUrl = {
3
+ /** Params to add to the search the page already has, as written. */
4
+ search?: string;
5
+ /** The fragment, without its `#`. */
6
+ hash?: string;
7
+ };
8
+ /**
9
+ * Stands in for a router while a test runs, and gives the page the URL the
10
+ * test starts from: without something intercepting, the first `update()`
11
+ * that changes the URL loads a document and takes the test runner with it.
12
+ *
13
+ * The search is added to what the page already has — a test runner and
14
+ * Storybook keep params of their own there — and in the spelling given.
15
+ * Returns the cleanup: the stores are emptied, which drops any write still
16
+ * waiting, and the URL and entry state found are put back. Unmount what was
17
+ * rendered first, as for `resetStateRegistry()`.
18
+ */
19
+ export declare const mountPageUrl: ({ search, hash }?: PageUrl) => (() => void);
20
+ export { resetStateRegistry };
@@ -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, resetStateRegistry };
@@ -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;
@@ -90,4 +90,4 @@ const createUrlCodec = (schema) => {
90
90
  salvage
91
91
  };
92
92
  };
93
- export { createUrlCodec };
93
+ export { createUrlCodec, refuseBoolean, serializeValue };
@@ -1,13 +1,13 @@
1
- import { StateSchema } from "./schema/object.mjs";
2
1
  import { CookieState } from "./cookie-state.mjs";
3
- import { OutputOf, PageState } from "./page-state.mjs";
4
- import { LocalState, SessionState } from "./storage-state.mjs";
5
2
  import { MemoryState } from "./memory-state.mjs";
3
+ import { HashOf, OutputOf, PageState } from "./page-state.mjs";
4
+ import { StateSchema } from "./schema/object.mjs";
5
+ import { LocalState, SessionState } from "./storage-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 {
@@ -19,16 +19,17 @@ type OptionsFor<Def> = Def extends {
19
19
  * the hydration render; without it those two renders see the defaults,
20
20
  * which flashes once the live URL takes over. The entry slot has no
21
21
  * server-side source, so it always starts from defaults there.
22
+ * `undefined` is the same as leaving it out.
22
23
  */
23
- initialUrl?: Readonly<UrlStateOf<Def>>;
24
+ initialUrl?: Readonly<UrlStateOf<Def>> | undefined;
24
25
  } : Def extends CookieState<infer Schema> ? {
25
26
  /**
26
27
  * What `parseCookies(request.cookies)` returned on the server, passed
27
28
  * down as a prop. It seeds SSR and the hydration render; without it
28
29
  * those two renders see the defaults, which flashes once the cookie
29
- * is read in the browser.
30
+ * is read in the browser. `undefined` is the same as leaving it out.
30
31
  */
31
- initialCookie?: Readonly<output<Schema>>;
32
+ initialCookie?: Readonly<output<Schema>> | undefined;
32
33
  } : never;
33
34
  export declare function useAppState<Def extends AnyState>(def: Def, options?: OptionsFor<Def>): [StateOf<Def>, UpdateFn<Def>];
34
35
  export declare function useAppState<Def extends AnyState, const Key extends Extract<keyof StateOf<Def>, string>>(def: Def, keys: readonly Key[], options?: OptionsFor<Def>): [Pick<StateOf<Def>, Key>, UpdateFn<Def>];