@molecule/app-svelte 3.5.1 → 3.7.1

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.
Files changed (62) hide show
  1. package/README.md +287 -76
  2. package/dist/hooks/index.d.ts +2 -0
  3. package/dist/hooks/index.d.ts.map +1 -1
  4. package/dist/hooks/index.js +2 -0
  5. package/dist/hooks/live-store.d.ts +0 -8
  6. package/dist/hooks/live-store.d.ts.map +1 -1
  7. package/dist/hooks/live-store.js +0 -13
  8. package/dist/hooks/maybe-readable.d.ts +36 -0
  9. package/dist/hooks/maybe-readable.d.ts.map +1 -0
  10. package/dist/hooks/maybe-readable.js +36 -0
  11. package/dist/hooks/useAIModels.d.ts +8 -2
  12. package/dist/hooks/useAIModels.d.ts.map +1 -1
  13. package/dist/hooks/useAIModels.js +44 -17
  14. package/dist/hooks/useAuth.d.ts +10 -4
  15. package/dist/hooks/useAuth.d.ts.map +1 -1
  16. package/dist/hooks/useAuth.js +39 -13
  17. package/dist/hooks/useForm.d.ts +13 -5
  18. package/dist/hooks/useForm.d.ts.map +1 -1
  19. package/dist/hooks/useForm.js +90 -58
  20. package/dist/hooks/useHttp.d.ts +28 -22
  21. package/dist/hooks/useHttp.d.ts.map +1 -1
  22. package/dist/hooks/useHttp.js +67 -96
  23. package/dist/hooks/useOAuth.d.ts +23 -7
  24. package/dist/hooks/useOAuth.d.ts.map +1 -1
  25. package/dist/hooks/useOAuth.js +51 -18
  26. package/dist/hooks/useOptimisticToggle.d.ts +67 -0
  27. package/dist/hooks/useOptimisticToggle.d.ts.map +1 -0
  28. package/dist/hooks/useOptimisticToggle.js +52 -0
  29. package/dist/hooks/useOptimisticValue.d.ts +11 -4
  30. package/dist/hooks/useOptimisticValue.d.ts.map +1 -1
  31. package/dist/hooks/useOptimisticValue.js +40 -49
  32. package/dist/hooks/usePush.d.ts +7 -3
  33. package/dist/hooks/usePush.d.ts.map +1 -1
  34. package/dist/hooks/usePush.js +26 -6
  35. package/dist/hooks/useRouter.d.ts +13 -7
  36. package/dist/hooks/useRouter.d.ts.map +1 -1
  37. package/dist/hooks/useRouter.js +39 -18
  38. package/dist/hooks/useStorage.d.ts +22 -9
  39. package/dist/hooks/useStorage.d.ts.map +1 -1
  40. package/dist/hooks/useStorage.js +146 -69
  41. package/dist/hooks/useStore.d.ts +14 -7
  42. package/dist/hooks/useStore.d.ts.map +1 -1
  43. package/dist/hooks/useStore.js +46 -9
  44. package/dist/hooks/useTranslation.d.ts +6 -2
  45. package/dist/hooks/useTranslation.d.ts.map +1 -1
  46. package/dist/hooks/useTranslation.js +11 -6
  47. package/dist/index.d.ts +4 -0
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -0
  50. package/dist/link/Link.svelte +33 -0
  51. package/dist/link/Link.svelte.d.ts +12 -0
  52. package/dist/link/Link.svelte.d.ts.map +1 -0
  53. package/dist/link/index.d.ts +23 -0
  54. package/dist/link/index.d.ts.map +1 -0
  55. package/dist/link/index.js +22 -0
  56. package/dist/link/types.d.ts +26 -0
  57. package/dist/link/types.d.ts.map +1 -0
  58. package/dist/link/types.js +6 -0
  59. package/dist/stores/chat.d.ts +4 -3
  60. package/dist/stores/chat.d.ts.map +1 -1
  61. package/dist/stores/chat.js +14 -15
  62. package/package.json +5 -5
@@ -7,7 +7,8 @@ import { onDestroy, onMount } from 'svelte';
7
7
  import { get, writable } from 'svelte/store';
8
8
  import { createConsumedSearchParam, listRouteRedirect, resolveListRoute, } from '@molecule/app-routing';
9
9
  import { useRouterInstance } from '../context.js';
10
- import { fieldStore, isReadableStore, liveStore } from './live-store.js';
10
+ import { fieldStore, liveStore } from './live-store.js';
11
+ import { toReadable } from './maybe-readable.js';
11
12
  /**
12
13
  * Routing state and navigation, React's `useRouter` in Svelte's idiom: call it
13
14
  * during component init under `setMoleculeContext({ router })`.
@@ -84,13 +85,32 @@ export function useNavigate() {
84
85
  * Whether a path is active, React's `useIsActive` in Svelte's idiom: a
85
86
  * readable store that re-evaluates on every route change.
86
87
  *
87
- * @param path - The path to check.
88
- * @param exact - Whether to match exactly (default: false).
88
+ * Both arguments may be a plain value or a readable store of one: the store
89
+ * re-evaluates when one changes (the way React's re-render re-reads its
90
+ * snapshot), so a navigation-driven nav link can take its path from a store.
91
+ *
92
+ * @param path - The path to check (or a store of it).
93
+ * @param exact - Whether to match exactly (default: false; or a store of it).
89
94
  * @returns A readable store of whether the path is active.
90
95
  */
91
96
  export function useIsActive(path, exact = false) {
92
97
  const router = useRouterInstance();
93
- return liveStore(() => router.isActive(path, exact), (notify) => router.subscribe(notify));
98
+ const pathStore = toReadable(path);
99
+ const exactStore = toReadable(exact);
100
+ const active = writable(router.isActive(get(pathStore), get(exactStore)));
101
+ /** Re-reads the router with the arguments' current values. */
102
+ const evaluate = () => {
103
+ active.set(router.isActive(get(pathStore), get(exactStore)));
104
+ };
105
+ const stopRouter = router.subscribe(evaluate);
106
+ const stopPath = pathStore.subscribe(evaluate);
107
+ const stopExact = exactStore.subscribe(evaluate);
108
+ onDestroy(() => {
109
+ stopRouter();
110
+ stopPath();
111
+ stopExact();
112
+ });
113
+ return { subscribe: active.subscribe };
94
114
  }
95
115
  /**
96
116
  * URL-backed pagination, filters and selected views, React's `useListRoute` in
@@ -105,9 +125,10 @@ export function useIsActive(path, exact = false) {
105
125
  * `options.auth.redirectTo`, carrying `state.returnTo`; until auth is confirmed
106
126
  * `canLoad` is `false`.
107
127
  *
108
- * The options may be a readable store: an auth status moving from `loading` to
109
- * `unauthenticated` re-resolves the list — and performs the sign-in redirect —
110
- * on the same component, the way React re-renders `useListRoute`.
128
+ * The options may be a plain value or a readable store of one (a store holding
129
+ * `undefined` means the default options): an auth status moving from `loading`
130
+ * to `unauthenticated` re-resolves the list — and performs the sign-in
131
+ * redirect — on the same component, the way React re-renders `useListRoute`.
111
132
  *
112
133
  * @param options - Filter sources, view paths, pagination and optional auth readiness (or a store of them).
113
134
  * @returns Each list field as a readable store, and its link builder and navigation actions.
@@ -126,7 +147,8 @@ export function useIsActive(path, exact = false) {
126
147
  */
127
148
  export function useListRoute(options = {}) {
128
149
  const router = useRouterInstance();
129
- let currentOptions = isReadableStore(options) ? get(options) : options;
150
+ const optionsStore = toReadable(options);
151
+ let currentOptions = get(optionsStore) ?? {};
130
152
  const resolve = () => resolveListRoute({ location: router.getLocation(), routeParams: router.getParams() }, currentOptions, (path, navigateOptions) => router.navigate(path, navigateOptions));
131
153
  let latest = resolve();
132
154
  const state = writable(latest);
@@ -141,21 +163,20 @@ export function useListRoute(options = {}) {
141
163
  router.navigate(redirect.to, redirect.options);
142
164
  };
143
165
  const stopRouter = router.subscribe(() => update());
144
- let stopOptions = null;
145
- if (isReadableStore(options)) {
146
- stopOptions = options.subscribe((next) => {
147
- if (next === currentOptions)
148
- return;
149
- currentOptions = next;
150
- update();
151
- });
152
- }
166
+ // The options store calls back at once with the options already read, which
167
+ // changes nothing; a later set re-resolves the list.
168
+ const stopOptions = optionsStore.subscribe((next) => {
169
+ if (next === currentOptions)
170
+ return;
171
+ currentOptions = next ?? {};
172
+ update();
173
+ });
153
174
  // React's redirect effect also runs once mounted, for a list that opens
154
175
  // directly on a signed-out protected view.
155
176
  onMount(update);
156
177
  onDestroy(() => {
157
178
  stopRouter();
158
- stopOptions?.();
179
+ stopOptions();
159
180
  });
160
181
  return {
161
182
  page: fieldStore(state, 'page'),
@@ -4,6 +4,7 @@
4
4
  * @module
5
5
  */
6
6
  import { type Readable } from 'svelte/store';
7
+ import { type MaybeReadable } from './maybe-readable.js';
7
8
  /**
8
9
  * Options for {@link useStorageValue}.
9
10
  */
@@ -36,14 +37,21 @@ export interface UseStorageValueResult<T> {
36
37
  * One storage key as Svelte stores, React's `useStorageValue` in Svelte's
37
38
  * idiom: call it during component init under `setMoleculeContext({ storage })`.
38
39
  *
40
+ * Both arguments may be a plain value or a readable store of one (a store
41
+ * holding `undefined` means the argument was omitted): setting the `key` store
42
+ * starts the new key over — its value is unknown until its read lands, so the
43
+ * default shows and `loading` is true, exactly as a fresh mount — while writes
44
+ * go to the key the hook holds at the moment they run. The latest
45
+ * `defaultValue` and `sync` always apply.
46
+ *
39
47
  * A read that started before a newer local write keeps that write's value (it
40
48
  * still ends `loading`), and with `sync` an outside write reaches the hook
41
49
  * through the provider's own subscription — so a non-browser backend
42
50
  * (native, encrypted, memory) propagates the same way, not just the browser
43
51
  * `storage` event.
44
52
  *
45
- * @param key - Storage key
46
- * @param options - Hook options
53
+ * @param key - Storage key (or a store of it).
54
+ * @param options - Hook options (or a store of them).
47
55
  * @returns Storage value state (value, loading, error) and mutators (setValue, removeValue).
48
56
  * @example
49
57
  * ```svelte
@@ -58,7 +66,7 @@ export interface UseStorageValueResult<T> {
58
66
  * {:else}<select onchange={(e) => setTheme(e.currentTarget.value)}>…</select>{/if}
59
67
  * ```
60
68
  */
61
- export declare function useStorageValue<T>(key: string, options?: UseStorageValueOptions<T>): UseStorageValueResult<T>;
69
+ export declare function useStorageValue<T>(key: MaybeReadable<string>, options?: MaybeReadable<UseStorageValueOptions<T> | undefined>): UseStorageValueResult<T>;
62
70
  /**
63
71
  * Options for {@link useStoragePreference}.
64
72
  */
@@ -99,12 +107,17 @@ export interface UseStoragePreferenceResult<T> {
99
107
  * started before a newer write, remove or external change is discarded, so a
100
108
  * slow hydration never overwrites an edit the user already made.
101
109
  *
102
- * Pass `null` for `key` while the real key is unknown (no project selected
103
- * yet): the hook then behaves as local state around `defaultValue` and
104
- * persists nothing.
110
+ * Both arguments may be a plain value or a readable store of one (a store
111
+ * holding `undefined` means the argument was omitted): setting the `key` store
112
+ * re-reads, re-subscribes and re-hydrates the new key on the same component
113
+ * (a `null`/`undefined` key is local state around the default and persists
114
+ * nothing), and writes go to the key the hook holds at the moment they run.
115
+ * The latest `defaultValue` always applies.
105
116
  *
106
- * @param key - The storage key, or `null` when there is nothing to persist.
107
- * @param options - `defaultValue`, reported until the provider supplies one.
117
+ * @param key - The storage key, or `null` when there is nothing to persist
118
+ * (or a store of either).
119
+ * @param options - `defaultValue`, reported until the provider supplies one
120
+ * (or a store of them).
108
121
  * @returns The current value, its mutators, and whether it is definite yet.
109
122
  * @example
110
123
  * ```svelte
@@ -116,7 +129,7 @@ export interface UseStoragePreferenceResult<T> {
116
129
  * </script>
117
130
  * ```
118
131
  */
119
- export declare function useStoragePreference<T = unknown>(key: string | null | undefined, options?: UseStoragePreferenceOptions<T>): UseStoragePreferenceResult<T>;
132
+ export declare function useStoragePreference<T = unknown>(key: MaybeReadable<string | null | undefined>, options?: MaybeReadable<UseStoragePreferenceOptions<T> | undefined>): UseStoragePreferenceResult<T>;
120
133
  /**
121
134
  * Storage operations without local state sync, React's `useStorage` in
122
135
  * Svelte's idiom: plain passthroughs of the context provider.
@@ -1 +1 @@
1
- {"version":3,"file":"useStorage.d.ts","sourceRoot":"","sources":["../../src/hooks/useStorage.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,KAAK,QAAQ,EAAY,MAAM,cAAc,CAAA;AAMtD;;GAEG;AACH,MAAM,WAAW,sBAAsB,CAAC,CAAC;IACvC;;OAEG;IACH,YAAY,CAAC,EAAE,CAAC,CAAA;IAChB;;OAEG;IACH,IAAI,CAAC,EAAE,OAAO,CAAA;CACf;AAED;;GAEG;AACH,MAAM,WAAW,qBAAqB,CAAC,CAAC;IACtC,6DAA6D;IAC7D,KAAK,EAAE,QAAQ,CAAC,CAAC,GAAG,SAAS,CAAC,CAAA;IAC9B,uEAAuE;IACvE,QAAQ,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IACrC,yEAAyE;IACzE,WAAW,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAChC,iDAAiD;IACjD,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAA;IAC1B,2CAA2C;IAC3C,KAAK,EAAE,QAAQ,CAAC,KAAK,GAAG,IAAI,CAAC,CAAA;CAC9B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;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'svelte';
7
- import { writable } from 'svelte/store';
7
+ import { get, writable } from 'svelte/store';
8
8
  import { getPreferenceStore } from '@molecule/app-storage';
9
9
  import { useStorageProvider } from '../context.js';
10
+ import { toReadable } from './maybe-readable.js';
10
11
  /**
11
12
  * One storage key as Svelte stores, React's `useStorageValue` in Svelte's
12
13
  * idiom: call it during component init under `setMoleculeContext({ storage })`.
13
14
  *
15
+ * Both arguments may be a plain value or a readable store of one (a store
16
+ * holding `undefined` means the argument was omitted): setting the `key` store
17
+ * starts the new key over — its value is unknown until its read lands, so the
18
+ * default shows and `loading` is true, exactly as a fresh mount — while writes
19
+ * go to the key the hook holds at the moment they run. The latest
20
+ * `defaultValue` and `sync` always apply.
21
+ *
14
22
  * A read that started before a newer local write keeps that write's value (it
15
23
  * still ends `loading`), and with `sync` an outside write reaches the hook
16
24
  * through the provider's own subscription — so a non-browser backend
17
25
  * (native, encrypted, memory) propagates the same way, not just the browser
18
26
  * `storage` event.
19
27
  *
20
- * @param key - Storage key
21
- * @param options - Hook options
28
+ * @param key - Storage key (or a store of it).
29
+ * @param options - Hook options (or a store of them).
22
30
  * @returns Storage value state (value, loading, error) and mutators (setValue, removeValue).
23
31
  * @example
24
32
  * ```svelte
@@ -35,61 +43,95 @@ import { useStorageProvider } from '../context.js';
35
43
  */
36
44
  export function useStorageValue(key, options) {
37
45
  const storage = useStorageProvider();
38
- const { defaultValue, sync = false } = options ?? {};
39
- const value = writable(defaultValue);
46
+ const keyStore = toReadable(key);
47
+ const optionsStore = toReadable(options);
48
+ const defaultOf = () => get(optionsStore)?.defaultValue;
49
+ const syncEnabled = () => get(optionsStore)?.sync ?? false;
50
+ const value = writable(defaultOf());
40
51
  const loading = writable(true);
41
52
  const error = writable(null);
42
53
  // Incremented by every local write. A read that started before it must not
43
54
  // replace the newer value — the user editing before the first read lands is
44
55
  // the common case on a slow (native, encrypted) backend.
45
56
  let writeVersion = 0;
46
- // The latest `defaultValue`, held like React's ref so a later options object
47
- // (an inline default) keeps working without re-reading storage.
48
- const currentDefault = defaultValue;
57
+ // The key whose read is current: a key change kills the old read (React's
58
+ // per-effect `mounted` flag), so a late landing does nothing at all.
59
+ let readEpoch = 0;
49
60
  let mounted = true;
50
61
  onDestroy(() => {
51
62
  mounted = false;
52
63
  });
53
- // Load the key's value (React's mount effect).
54
- const loadValue = async () => {
64
+ // Load one key's value (React's load effect, keyed on the key).
65
+ const loadKey = (keyToLoad) => {
66
+ // A new key's value is unknown until its read lands: show what a fresh
67
+ // mount shows (React's render-time reset for a changed key).
68
+ value.set(defaultOf());
69
+ loading.set(true);
70
+ error.set(null);
71
+ const epoch = ++readEpoch;
55
72
  const version = writeVersion;
56
- try {
57
- const stored = await storage.get(key);
58
- if (!mounted)
73
+ void storage
74
+ .get(keyToLoad)
75
+ .then((stored) => {
76
+ if (!mounted || epoch !== readEpoch)
59
77
  return;
60
78
  // A write made after this read started holds the newer value; the read still ends loading.
61
79
  if (writeVersion === version)
62
- value.set((stored ?? currentDefault));
80
+ value.set((stored ?? defaultOf()));
63
81
  loading.set(false);
64
- }
65
- catch (err) {
66
- if (!mounted)
82
+ })
83
+ .catch((err) => {
84
+ if (!mounted || epoch !== readEpoch)
67
85
  return;
68
86
  if (writeVersion === version) {
69
87
  error.set(err instanceof Error ? err : new Error(String(err)));
70
88
  }
71
89
  loading.set(false);
72
- }
90
+ });
73
91
  };
74
- void loadValue();
92
+ loadKey(get(keyStore));
75
93
  // Sync across tabs if supported — through the PROVIDER's own subscription, so
76
94
  // a non-browser backend (native, encrypted, memory) propagates the same way
77
- // instead of being limited to the browser `storage` event.
95
+ // instead of being limited to the browser `storage` event. Re-armed whenever
96
+ // the key or the `sync` option changes (React's [key, sync, storage] effect).
78
97
  let stopSync = null;
79
- if (sync && storage.subscribe) {
80
- stopSync = storage.subscribe(key, (next) => {
81
- writeVersion += 1;
82
- value.set(next === null ? currentDefault : next);
83
- });
84
- onDestroy(() => {
85
- stopSync?.();
86
- stopSync = null;
87
- });
88
- }
98
+ const armSync = () => {
99
+ stopSync?.();
100
+ stopSync = null;
101
+ if (syncEnabled() && storage.subscribe) {
102
+ stopSync = storage.subscribe(get(keyStore), (next) => {
103
+ writeVersion += 1;
104
+ value.set(next === null ? defaultOf() : next);
105
+ });
106
+ }
107
+ };
108
+ armSync();
109
+ onDestroy(() => {
110
+ stopSync?.();
111
+ stopSync = null;
112
+ });
113
+ // Follow the key: a changed key loads its own value; a changed `sync`
114
+ // re-arms the subscription. The stores call back at once with the values
115
+ // already read, which changes nothing.
116
+ let currentKey = get(keyStore);
117
+ let currentSync = syncEnabled();
118
+ const stopKey = keyStore.subscribe((next) => {
119
+ const syncNow = syncEnabled();
120
+ if (Object.is(next, currentKey) && Object.is(syncNow, currentSync))
121
+ return;
122
+ const keyChanged = !Object.is(next, currentKey);
123
+ currentKey = next;
124
+ currentSync = syncNow;
125
+ if (keyChanged)
126
+ loadKey(next);
127
+ else
128
+ armSync();
129
+ });
130
+ onDestroy(stopKey);
89
131
  const setValue = async (newValue) => {
90
132
  writeVersion += 1;
91
133
  try {
92
- await storage.set(key, newValue);
134
+ await storage.set(get(keyStore), newValue);
93
135
  value.set(newValue);
94
136
  error.set(null);
95
137
  }
@@ -101,8 +143,8 @@ export function useStorageValue(key, options) {
101
143
  const removeValue = async () => {
102
144
  writeVersion += 1;
103
145
  try {
104
- await storage.remove(key);
105
- value.set(currentDefault);
146
+ await storage.remove(get(keyStore));
147
+ value.set(defaultOf());
106
148
  error.set(null);
107
149
  }
108
150
  catch (err) {
@@ -129,12 +171,17 @@ export function useStorageValue(key, options) {
129
171
  * started before a newer write, remove or external change is discarded, so a
130
172
  * slow hydration never overwrites an edit the user already made.
131
173
  *
132
- * Pass `null` for `key` while the real key is unknown (no project selected
133
- * yet): the hook then behaves as local state around `defaultValue` and
134
- * persists nothing.
174
+ * Both arguments may be a plain value or a readable store of one (a store
175
+ * holding `undefined` means the argument was omitted): setting the `key` store
176
+ * re-reads, re-subscribes and re-hydrates the new key on the same component
177
+ * (a `null`/`undefined` key is local state around the default and persists
178
+ * nothing), and writes go to the key the hook holds at the moment they run.
179
+ * The latest `defaultValue` always applies.
135
180
  *
136
- * @param key - The storage key, or `null` when there is nothing to persist.
137
- * @param options - `defaultValue`, reported until the provider supplies one.
181
+ * @param key - The storage key, or `null` when there is nothing to persist
182
+ * (or a store of either).
183
+ * @param options - `defaultValue`, reported until the provider supplies one
184
+ * (or a store of them).
138
185
  * @returns The current value, its mutators, and whether it is definite yet.
139
186
  * @example
140
187
  * ```svelte
@@ -148,60 +195,90 @@ export function useStorageValue(key, options) {
148
195
  */
149
196
  export function useStoragePreference(key, options) {
150
197
  const store = getPreferenceStore();
151
- const defaultValue = options?.defaultValue;
198
+ const keyStore = toReadable(key);
199
+ const optionsStore = toReadable(options);
200
+ const defaultOf = () => get(optionsStore)?.defaultValue;
201
+ const currentKey = () => get(keyStore);
152
202
  const read = () => {
153
- if (!key)
154
- return defaultValue;
155
- const stored = store.get(key);
156
- return stored === null ? defaultValue : stored;
203
+ const keyNow = currentKey();
204
+ if (!keyNow)
205
+ return defaultOf();
206
+ const stored = store.get(keyNow);
207
+ return stored === null ? defaultOf() : stored;
157
208
  };
158
209
  const initial = read();
159
210
  const value = writable(initial);
160
- const ready = writable(!key);
211
+ const ready = writable(!currentKey());
161
212
  // The value `setValue`'s functional form receives, kept beside the store.
162
213
  let currentValue = initial;
163
- if (!key) {
164
- ready.set(true);
165
- value.set(defaultValue);
166
- currentValue = defaultValue;
167
- }
168
- else {
169
- let cancelled = false;
214
+ // React's [store, key, read] effect for one key: seed from whatever the
215
+ // store already knows, then let hydration converge it. With a synchronous
216
+ // provider the seed is a no-op change. A replaced key tears the old one
217
+ // down first, so its late hydration is discarded.
218
+ let stopStore = null;
219
+ let cancelled = false;
220
+ const followKey = (keyToFollow) => {
221
+ stopStore?.();
222
+ stopStore = null;
223
+ cancelled = true;
224
+ if (!keyToFollow) {
225
+ ready.set(true);
226
+ const fallback = defaultOf();
227
+ value.set(fallback);
228
+ currentValue = fallback;
229
+ return;
230
+ }
231
+ cancelled = false;
170
232
  const sync = () => {
171
- if (!cancelled) {
172
- const next = read();
173
- value.set(next);
174
- currentValue = next;
175
- }
233
+ if (cancelled)
234
+ return;
235
+ const next = read();
236
+ value.set(next);
237
+ currentValue = next;
176
238
  };
177
239
  // Seed from whatever the store already knows, then let hydration converge
178
240
  // it. With a synchronous provider this is a no-op change.
179
241
  sync();
180
242
  ready.set(false);
181
- const stop = store.subscribe(key, sync);
182
- onDestroy(() => {
183
- cancelled = true;
184
- stop();
185
- });
186
- void store.hydrate([key]).then(() => {
243
+ stopStore = store.subscribe(keyToFollow, sync);
244
+ void store.hydrate([keyToFollow]).then(() => {
187
245
  if (cancelled)
188
246
  return;
189
247
  sync();
190
248
  ready.set(true);
191
249
  });
192
- }
250
+ };
251
+ followKey(currentKey());
252
+ onDestroy(() => {
253
+ cancelled = true;
254
+ stopStore?.();
255
+ stopStore = null;
256
+ });
257
+ // Follow the key source: the store calls back at once with the key already
258
+ // read, which changes nothing.
259
+ let followedKey = currentKey();
260
+ const stopKey = keyStore.subscribe((next) => {
261
+ if (Object.is(next, followedKey))
262
+ return;
263
+ followedKey = next;
264
+ followKey(next);
265
+ });
266
+ onDestroy(stopKey);
193
267
  const setValue = (next) => {
194
268
  const resolved = typeof next === 'function' ? next(currentValue) : next;
195
269
  currentValue = resolved;
196
270
  value.set(resolved);
197
- if (key)
198
- store.set(key, resolved);
271
+ const keyNow = currentKey();
272
+ if (keyNow)
273
+ store.set(keyNow, resolved);
199
274
  };
200
275
  const removeValue = () => {
201
- currentValue = defaultValue;
202
- value.set(defaultValue);
203
- if (key)
204
- store.remove(key);
276
+ const fallback = defaultOf();
277
+ currentValue = fallback;
278
+ value.set(fallback);
279
+ const keyNow = currentKey();
280
+ if (keyNow)
281
+ store.remove(keyNow);
205
282
  };
206
283
  return {
207
284
  value: { subscribe: value.subscribe },
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import type { Readable } from 'svelte/store';
6
+ import { type Readable } from 'svelte/store';
7
7
  import type { Store } from '@molecule/app-state';
8
+ import { type MaybeReadable } from './maybe-readable.js';
8
9
  /** Options for {@link useStore}. */
9
10
  export interface UseStoreOptions<T, S> {
10
11
  /** Selects part of the state. */
@@ -16,17 +17,23 @@ export interface UseStoreOptions<T, S> {
16
17
  * Subscribes a store with an optional selector and equality function, React's
17
18
  * `useStore` in Svelte's idiom: a readable store of the selected value.
18
19
  *
20
+ * The store argument may be the store itself (a molecule store has `getState`
21
+ * AND `subscribe`, and is always a VALUE, never a source) or a readable store
22
+ * OF a store: setting it re-subscribes to the new store and re-reads its
23
+ * snapshot on the same component, the way React's re-render does. The options
24
+ * (or a store of them) are read whenever the snapshot is.
25
+ *
19
26
  * The store is the argument, so this hook needs NO state provider: it reads
20
- * `store.getState()` and subscribes with `store.subscribe()`. When
21
- * `equalityFn` says a new selected value equals the previous one, the previous
22
- * result is kept (the same value, not a fresh object).
27
+ * `store.getState()` and subscribes with `store.subscribe()`. When `equalityFn`
28
+ * says a new selected value equals the previous one, the previous result is
29
+ * kept (the same value, not a fresh object).
23
30
  *
24
31
  * The selector and equality function run with the same cadence as React's
25
32
  * `useSyncExternalStore` binding, because React re-reads its snapshot around
26
33
  * every render; {@link useSyncExternalStore} documents the cadence.
27
34
  *
28
- * @param store - The store to subscribe to.
29
- * @param options - Hook options (selector, equalityFn).
35
+ * @param store - The store to subscribe to (or a readable store of it).
36
+ * @param options - Hook options (selector, equalityFn), or a store of them.
30
37
  * @returns A readable store of the selected state.
31
38
  * @example
32
39
  * ```svelte
@@ -39,7 +46,7 @@ export interface UseStoreOptions<T, S> {
39
46
  * <p>{$count} / {$doubled}</p>
40
47
  * ```
41
48
  */
42
- export declare function useStore<T, S = T>(store: Store<T>, options?: UseStoreOptions<T, S>): Readable<S>;
49
+ export declare function useStore<T, S = T>(store: MaybeReadable<Store<T>>, options?: MaybeReadable<UseStoreOptions<T, S> | undefined>): Readable<S>;
43
50
  /**
44
51
  * The store's setState function, React's `useSetStore` in Svelte's idiom.
45
52
  *
@@ -1 +1 @@
1
- {"version":3,"file":"useStore.d.ts","sourceRoot":"","sources":["../../src/hooks/useStore.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAE5C,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AAIhD,oCAAoC;AACpC,MAAM,WAAW,eAAe,CAAC,CAAC,EAAE,CAAC;IACnC,iCAAiC;IACjC,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAA;IAC1B,qEAAqE;IACrE,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,OAAO,CAAA;CACrC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAqBhG;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAEpE;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,IAAI,SAAS,OAAO,EAAE,EAAE,CAAC,EACzD,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,EACf,MAAM,EAAE,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK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C,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,CAAC,GAC/F,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,CAAC,CAGtB"}
@@ -3,22 +3,30 @@
3
3
  *
4
4
  * @module
5
5
  */
6
+ import { get } from 'svelte/store';
6
7
  import { useSyncExternalStore } from './external-store.js';
8
+ import { toReadable } from './maybe-readable.js';
7
9
  /**
8
10
  * Subscribes a store with an optional selector and equality function, React's
9
11
  * `useStore` in Svelte's idiom: a readable store of the selected value.
10
12
  *
13
+ * The store argument may be the store itself (a molecule store has `getState`
14
+ * AND `subscribe`, and is always a VALUE, never a source) or a readable store
15
+ * OF a store: setting it re-subscribes to the new store and re-reads its
16
+ * snapshot on the same component, the way React's re-render does. The options
17
+ * (or a store of them) are read whenever the snapshot is.
18
+ *
11
19
  * The store is the argument, so this hook needs NO state provider: it reads
12
- * `store.getState()` and subscribes with `store.subscribe()`. When
13
- * `equalityFn` says a new selected value equals the previous one, the previous
14
- * result is kept (the same value, not a fresh object).
20
+ * `store.getState()` and subscribes with `store.subscribe()`. When `equalityFn`
21
+ * says a new selected value equals the previous one, the previous result is
22
+ * kept (the same value, not a fresh object).
15
23
  *
16
24
  * The selector and equality function run with the same cadence as React's
17
25
  * `useSyncExternalStore` binding, because React re-reads its snapshot around
18
26
  * every render; {@link useSyncExternalStore} documents the cadence.
19
27
  *
20
- * @param store - The store to subscribe to.
21
- * @param options - Hook options (selector, equalityFn).
28
+ * @param store - The store to subscribe to (or a readable store of it).
29
+ * @param options - Hook options (selector, equalityFn), or a store of them.
22
30
  * @returns A readable store of the selected state.
23
31
  * @example
24
32
  * ```svelte
@@ -32,12 +40,19 @@ import { useSyncExternalStore } from './external-store.js';
32
40
  * ```
33
41
  */
34
42
  export function useStore(store, options) {
35
- const { selector, equalityFn } = options ?? {};
43
+ const storeStore = toReadable(store);
44
+ const optionsStore = toReadable(options);
45
+ // The store currently subscribed: setting the source re-subscribes, as
46
+ // React's subscribe callback (keyed on the store) does on a re-render.
47
+ let currentStore = get(storeStore);
48
+ let stopStore = null;
49
+ let stopSource = null;
36
50
  // The previous selected value (React's prevSelectedRef): while an equality
37
51
  // function accepts it, it stays the result, so its identity is stable.
38
52
  let previous;
39
- return useSyncExternalStore((onChange) => store.subscribe(onChange), () => {
40
- const state = store.getState();
53
+ const getSnapshot = () => {
54
+ const { selector, equalityFn } = get(optionsStore) ?? {};
55
+ const state = currentStore.getState();
41
56
  const selected = selector ? selector(state) : state;
42
57
  // With an equality function and a previous value, an equal selection
43
58
  // keeps the previous result — the same value, not a fresh object.
@@ -47,7 +62,29 @@ export function useStore(store, options) {
47
62
  }
48
63
  previous = selected;
49
64
  return selected;
50
- });
65
+ };
66
+ const subscribe = (onChange) => {
67
+ stopStore = currentStore.subscribe(onChange);
68
+ // A new store in the source re-subscribes and re-checks the snapshot, the
69
+ // way React's useSyncExternalStore does when its subscribe function
70
+ // changes. The store calls back at once with the store already read.
71
+ stopSource = storeStore.subscribe((next) => {
72
+ const incoming = next;
73
+ if (Object.is(incoming, currentStore))
74
+ return;
75
+ currentStore = incoming;
76
+ stopStore?.();
77
+ stopStore = currentStore.subscribe(onChange);
78
+ onChange();
79
+ });
80
+ return () => {
81
+ stopSource?.();
82
+ stopStore?.();
83
+ stopSource = null;
84
+ stopStore = null;
85
+ };
86
+ };
87
+ return useSyncExternalStore(subscribe, getSnapshot);
51
88
  }
52
89
  /**
53
90
  * The store's setState function, React's `useSetStore` in Svelte's idiom.