@molecule/app-svelte 3.3.0 → 3.5.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 (164) hide show
  1. package/README.md +2394 -221
  2. package/dist/agent-identity.js +0 -1
  3. package/dist/context.d.ts +101 -1
  4. package/dist/context.d.ts.map +1 -1
  5. package/dist/context.js +199 -3
  6. package/dist/hooks/external-store.d.ts +28 -0
  7. package/dist/hooks/external-store.d.ts.map +1 -0
  8. package/dist/hooks/external-store.js +95 -0
  9. package/dist/hooks/index.d.ts +37 -0
  10. package/dist/hooks/index.d.ts.map +1 -0
  11. package/dist/hooks/index.js +36 -0
  12. package/dist/hooks/live-store.d.ts +68 -0
  13. package/dist/hooks/live-store.d.ts.map +1 -0
  14. package/dist/hooks/live-store.js +76 -0
  15. package/dist/hooks/useAIModels.d.ts +58 -0
  16. package/dist/hooks/useAIModels.d.ts.map +1 -0
  17. package/dist/hooks/useAIModels.js +155 -0
  18. package/dist/hooks/useAsyncState.d.ts +52 -0
  19. package/dist/hooks/useAsyncState.d.ts.map +1 -0
  20. package/dist/hooks/useAsyncState.js +80 -0
  21. package/dist/hooks/useAuth.d.ts +99 -0
  22. package/dist/hooks/useAuth.d.ts.map +1 -0
  23. package/dist/hooks/useAuth.js +88 -0
  24. package/dist/hooks/useCapacitorApp.d.ts +51 -0
  25. package/dist/hooks/useCapacitorApp.d.ts.map +1 -0
  26. package/dist/hooks/useCapacitorApp.js +57 -0
  27. package/dist/hooks/useChangePassword.d.ts +41 -0
  28. package/dist/hooks/useChangePassword.d.ts.map +1 -0
  29. package/dist/hooks/useChangePassword.js +40 -0
  30. package/dist/hooks/useDevice.d.ts +48 -0
  31. package/dist/hooks/useDevice.d.ts.map +1 -0
  32. package/dist/hooks/useDevice.js +37 -0
  33. package/dist/hooks/useEditor.d.ts +65 -0
  34. package/dist/hooks/useEditor.d.ts.map +1 -0
  35. package/dist/hooks/useEditor.js +86 -0
  36. package/dist/hooks/useForm.d.ts +137 -0
  37. package/dist/hooks/useForm.d.ts.map +1 -0
  38. package/dist/hooks/useForm.js +221 -0
  39. package/dist/hooks/useHttp.d.ts +122 -0
  40. package/dist/hooks/useHttp.d.ts.map +1 -0
  41. package/dist/hooks/useHttp.js +220 -0
  42. package/dist/hooks/useLogger.d.ts +52 -0
  43. package/dist/hooks/useLogger.d.ts.map +1 -0
  44. package/dist/hooks/useLogger.js +64 -0
  45. package/dist/hooks/useLogin.d.ts +47 -0
  46. package/dist/hooks/useLogin.d.ts.map +1 -0
  47. package/dist/hooks/useLogin.js +44 -0
  48. package/dist/hooks/useOAuth.d.ts +96 -0
  49. package/dist/hooks/useOAuth.d.ts.map +1 -0
  50. package/dist/hooks/useOAuth.js +363 -0
  51. package/dist/hooks/useOptimisticValue.d.ts +58 -0
  52. package/dist/hooks/useOptimisticValue.d.ts.map +1 -0
  53. package/dist/hooks/useOptimisticValue.js +98 -0
  54. package/dist/hooks/usePasswordReset.d.ts +50 -0
  55. package/dist/hooks/usePasswordReset.d.ts.map +1 -0
  56. package/dist/hooks/usePasswordReset.js +50 -0
  57. package/dist/hooks/usePlatform.d.ts +45 -0
  58. package/dist/hooks/usePlatform.d.ts.map +1 -0
  59. package/dist/hooks/usePlatform.js +35 -0
  60. package/dist/hooks/usePreview.d.ts +54 -0
  61. package/dist/hooks/usePreview.d.ts.map +1 -0
  62. package/dist/hooks/usePreview.js +61 -0
  63. package/dist/hooks/useProfileForm.d.ts +100 -0
  64. package/dist/hooks/useProfileForm.d.ts.map +1 -0
  65. package/dist/hooks/useProfileForm.js +267 -0
  66. package/dist/hooks/usePromise.d.ts +62 -0
  67. package/dist/hooks/usePromise.d.ts.map +1 -0
  68. package/dist/hooks/usePromise.js +105 -0
  69. package/dist/hooks/usePush.d.ts +68 -0
  70. package/dist/hooks/usePush.d.ts.map +1 -0
  71. package/dist/hooks/usePush.js +79 -0
  72. package/dist/hooks/useRouter.d.ts +169 -0
  73. package/dist/hooks/useRouter.d.ts.map +1 -0
  74. package/dist/hooks/useRouter.js +212 -0
  75. package/dist/hooks/useSignup.d.ts +52 -0
  76. package/dist/hooks/useSignup.d.ts.map +1 -0
  77. package/dist/hooks/useSignup.js +42 -0
  78. package/dist/hooks/useStorage.d.ts +133 -0
  79. package/dist/hooks/useStorage.d.ts.map +1 -0
  80. package/dist/hooks/useStorage.js +228 -0
  81. package/dist/hooks/useStore.d.ts +69 -0
  82. package/dist/hooks/useStore.d.ts.map +1 -0
  83. package/dist/hooks/useStore.js +82 -0
  84. package/dist/hooks/useTheme.d.ts +55 -0
  85. package/dist/hooks/useTheme.d.ts.map +1 -0
  86. package/dist/hooks/useTheme.js +102 -0
  87. package/dist/hooks/useTranslation.d.ts +106 -0
  88. package/dist/hooks/useTranslation.d.ts.map +1 -0
  89. package/dist/hooks/useTranslation.js +159 -0
  90. package/dist/hooks/useVerifyPaymentReturn.d.ts +91 -0
  91. package/dist/hooks/useVerifyPaymentReturn.d.ts.map +1 -0
  92. package/dist/hooks/useVerifyPaymentReturn.js +189 -0
  93. package/dist/hooks/useVersion.d.ts +53 -0
  94. package/dist/hooks/useVersion.d.ts.map +1 -0
  95. package/dist/hooks/useVersion.js +70 -0
  96. package/dist/hooks/useWorkspace.d.ts +47 -0
  97. package/dist/hooks/useWorkspace.d.ts.map +1 -0
  98. package/dist/hooks/useWorkspace.js +68 -0
  99. package/dist/index.d.ts +2 -0
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +2 -1
  102. package/dist/session-ready/SessionReady.svelte +20 -0
  103. package/dist/session-ready/SessionReady.svelte.d.ts +5 -0
  104. package/dist/session-ready/SessionReady.svelte.d.ts.map +1 -0
  105. package/dist/session-ready/index.d.ts +7 -0
  106. package/dist/session-ready/index.d.ts.map +1 -0
  107. package/dist/session-ready/index.js +6 -0
  108. package/dist/stores/async-state.js +0 -1
  109. package/dist/stores/auth.js +0 -1
  110. package/dist/stores/capacitor-app.js +0 -1
  111. package/dist/stores/change-password.js +0 -1
  112. package/dist/stores/chat.d.ts.map +1 -1
  113. package/dist/stores/chat.js +3 -10
  114. package/dist/stores/device.js +0 -1
  115. package/dist/stores/forms.js +0 -1
  116. package/dist/stores/http.js +0 -1
  117. package/dist/stores/i18n.d.ts +3 -2
  118. package/dist/stores/i18n.d.ts.map +1 -1
  119. package/dist/stores/i18n.js +2 -3
  120. package/dist/stores/index.js +0 -1
  121. package/dist/stores/logger.js +0 -1
  122. package/dist/stores/login.js +0 -1
  123. package/dist/stores/oauth.js +0 -1
  124. package/dist/stores/password-reset.js +0 -1
  125. package/dist/stores/platform.js +0 -1
  126. package/dist/stores/promise.js +0 -1
  127. package/dist/stores/push.js +0 -1
  128. package/dist/stores/router.js +0 -1
  129. package/dist/stores/signup.js +0 -1
  130. package/dist/stores/state.js +0 -1
  131. package/dist/stores/storage.js +0 -1
  132. package/dist/stores/theme.js +0 -1
  133. package/dist/stores/version.js +0 -1
  134. package/dist/types.d.ts +20 -0
  135. package/dist/types.d.ts.map +1 -1
  136. package/dist/types.js +0 -1
  137. package/package.json +14 -9
  138. package/dist/agent-identity.js.map +0 -1
  139. package/dist/context.js.map +0 -1
  140. package/dist/index.js.map +0 -1
  141. package/dist/stores/async-state.js.map +0 -1
  142. package/dist/stores/auth.js.map +0 -1
  143. package/dist/stores/capacitor-app.js.map +0 -1
  144. package/dist/stores/change-password.js.map +0 -1
  145. package/dist/stores/chat.js.map +0 -1
  146. package/dist/stores/device.js.map +0 -1
  147. package/dist/stores/forms.js.map +0 -1
  148. package/dist/stores/http.js.map +0 -1
  149. package/dist/stores/i18n.js.map +0 -1
  150. package/dist/stores/index.js.map +0 -1
  151. package/dist/stores/logger.js.map +0 -1
  152. package/dist/stores/login.js.map +0 -1
  153. package/dist/stores/oauth.js.map +0 -1
  154. package/dist/stores/password-reset.js.map +0 -1
  155. package/dist/stores/platform.js.map +0 -1
  156. package/dist/stores/promise.js.map +0 -1
  157. package/dist/stores/push.js.map +0 -1
  158. package/dist/stores/router.js.map +0 -1
  159. package/dist/stores/signup.js.map +0 -1
  160. package/dist/stores/state.js.map +0 -1
  161. package/dist/stores/storage.js.map +0 -1
  162. package/dist/stores/theme.js.map +0 -1
  163. package/dist/stores/version.js.map +0 -1
  164. package/dist/types.js.map +0 -1
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Svelte hook for profile editing over the app's bonded form and auth clients,
3
+ * porting React's `useProfileForm`.
4
+ *
5
+ * @module
6
+ */
7
+ import { onDestroy } from 'svelte';
8
+ import { derived, writable } from 'svelte/store';
9
+ import { formValuesEqual, snapshotFormValue } from '@molecule/app-forms';
10
+ import { useAuthClient } from '../context.js';
11
+ import { useAuth } from './useAuth.js';
12
+ import { useForm } from './useForm.js';
13
+ /**
14
+ * Detaches the value snapshot the hook keeps as its baseline.
15
+ *
16
+ * Form values are a plain string-keyed object at runtime; the caller's values
17
+ * TYPE may be an `interface`, which has no index signature to spread from, so
18
+ * the copy goes through the record view and comes back as `TValues`.
19
+ *
20
+ * @param values - The values object to snapshot.
21
+ * @returns A detached form-value snapshot.
22
+ */
23
+ function copyValues(values) {
24
+ return snapshotFormValue(values);
25
+ }
26
+ /**
27
+ * Owns load → edit → submit → publish for the signed-in user's profile,
28
+ * React's `useProfileForm` in Svelte's idiom: call it during component init
29
+ * under `setMoleculeContext({ auth })`.
30
+ *
31
+ * Same-account background updates refresh untouched fields but preserve dirty
32
+ * controls. Session ownership comes from the auth client, independently of
33
+ * mutable profile fields; an explicit getIdentity adds the caller's identity
34
+ * check. Submission snapshots the registered values before asynchronous
35
+ * validation, sends only changed fields through `toPatch`, and uses the auth
36
+ * client's configured updateProfile transport. The saved server response
37
+ * becomes the clean baseline; edits made while saving remain dirty. No request
38
+ * is made for a patch with no fields. A failed request retains the edits and
39
+ * shared user.
40
+ *
41
+ * @param options - Controlled defaults, identity and wire adapters, optional cache/navigation callback.
42
+ * @returns Form state stores, typed control bindings, native submit binding and save error store.
43
+ * @example
44
+ * ```svelte
45
+ * <script>
46
+ * import { useProfileForm } from '@molecule/app-svelte'
47
+ * const profile = useProfileForm({
48
+ * defaultValues: { name: '', bio: '' },
49
+ * toValues: (user) => ({ name: user.name ?? '', bio: user.bio ?? '' }),
50
+ * toPatch: (changes) => changes,
51
+ * })
52
+ * </script>
53
+ * ```
54
+ */
55
+ export function useProfileForm(options) {
56
+ const { defaultValues, getIdentity: _identity, toValues: _values, toPatch: _patch, onSaved: _saved, ...formOptions } = options;
57
+ const form = useForm({ ...formOptions, defaultValues });
58
+ const client = useAuthClient();
59
+ const { user } = useAuth();
60
+ const error = writable(undefined);
61
+ const isSaving = writable(false);
62
+ // Committed configuration (React's optionsRef): the actions below close over
63
+ // this one options object, which is this mount's options.
64
+ const config = options;
65
+ const baseline = { current: copyValues(defaultValues) };
66
+ // A late same-account record must not undo fields the person edited, even
67
+ // after those edits became the clean baseline of a completed save.
68
+ const editedFields = new Set();
69
+ const owner = {
70
+ current: null,
71
+ };
72
+ const activeSave = { current: null };
73
+ const pendingPropagation = { current: undefined };
74
+ let mounted = true;
75
+ onDestroy(() => {
76
+ mounted = false;
77
+ });
78
+ const readValues = () => {
79
+ const values = copyValues(baseline.current);
80
+ for (const key of Object.keys(values))
81
+ values[key] = form.getValue(key);
82
+ return values;
83
+ };
84
+ const rebase = (next, preserveAgainst) => {
85
+ const current = readValues();
86
+ baseline.current = copyValues(next);
87
+ if (preserveAgainst) {
88
+ form.updateValues(next, { keepDirtyValues: true });
89
+ for (const key of Object.keys(current)) {
90
+ if (editedFields.has(key) || !formValuesEqual(current[key], preserveAgainst[key])) {
91
+ form.setValue(key, current[key]);
92
+ }
93
+ }
94
+ }
95
+ else {
96
+ form.reset(next);
97
+ }
98
+ };
99
+ // React's user layout effect, as a store subscription: it runs at init (the
100
+ // way the effect runs after mount) and on every user change.
101
+ let rebasedFor = undefined;
102
+ const applyUser = (currentUser) => {
103
+ if (rebasedFor === currentUser)
104
+ return;
105
+ rebasedFor = currentUser;
106
+ if (!currentUser) {
107
+ if (owner.current) {
108
+ owner.current = null;
109
+ pendingPropagation.current = undefined;
110
+ editedFields.clear();
111
+ rebase(copyValues(config.defaultValues));
112
+ error.set(undefined);
113
+ }
114
+ return;
115
+ }
116
+ const revision = client.getSessionRevision?.();
117
+ const identity = config.getIdentity?.(currentUser);
118
+ if (revision === undefined && !config.getIdentity) {
119
+ throw new Error('useProfileForm: provide getIdentity when the auth client has no session revision');
120
+ }
121
+ const previous = owner.current;
122
+ const sameAccount = !previous ||
123
+ (previous.client === client &&
124
+ previous.revision === revision &&
125
+ previous.identity === identity);
126
+ const previousBaseline = baseline.current;
127
+ // Keep this token across same-account hydration, but replace it when the
128
+ // account/client changes. A pending validation belongs to that exact owner.
129
+ if (!previous || !sameAccount) {
130
+ owner.current = { client, revision, identity };
131
+ editedFields.clear();
132
+ }
133
+ rebase(config.toValues(currentUser), sameAccount ? previousBaseline : undefined);
134
+ if (!sameAccount) {
135
+ pendingPropagation.current = undefined;
136
+ error.set(undefined);
137
+ }
138
+ };
139
+ const stopUser = user.subscribe(applyUser);
140
+ onDestroy(stopUser);
141
+ const submit = () => {
142
+ if (activeSave.current)
143
+ return activeSave.current;
144
+ const currentUser = client.getUser();
145
+ if (!mounted || !currentUser)
146
+ return Promise.resolve(undefined);
147
+ const revision = client.getSessionRevision?.();
148
+ const identity = config.getIdentity?.(currentUser);
149
+ const submissionOwner = owner.current;
150
+ const ownsProfile = () => {
151
+ const current = client.getUser();
152
+ return (mounted &&
153
+ owner.current === submissionOwner &&
154
+ current !== null &&
155
+ client.getSessionRevision?.() === revision &&
156
+ config.getIdentity?.(current) === identity);
157
+ };
158
+ const snapshot = readValues();
159
+ const before = copyValues(baseline.current);
160
+ const changes = {};
161
+ for (const key of Object.keys(snapshot)) {
162
+ if (!formValuesEqual(snapshot[key], before[key]))
163
+ changes[key] = snapshot[key];
164
+ }
165
+ error.set(undefined);
166
+ isSaving.set(true);
167
+ let saved;
168
+ const run = async () => {
169
+ try {
170
+ await form.handleSubmit(async () => {
171
+ // Validation can await arbitrary app work. Check BEFORE toPatch and
172
+ // again immediately before the mutation: its credentials are read by
173
+ // updateProfile now, not when the reader originally clicked Save.
174
+ if (!ownsProfile())
175
+ return;
176
+ const patch = config.toPatch(changes, snapshot);
177
+ if (Object.keys(patch).length > 0) {
178
+ if (!ownsProfile())
179
+ return;
180
+ saved = await client.updateProfile(patch);
181
+ if (!ownsProfile()) {
182
+ saved = undefined;
183
+ return;
184
+ }
185
+ if (mounted) {
186
+ const savedValues = config.toValues(saved);
187
+ const current = readValues();
188
+ for (const key of editedFields) {
189
+ if (formValuesEqual(current[key], snapshot[key]) &&
190
+ !formValuesEqual(savedValues[key], snapshot[key])) {
191
+ // The accepted response intentionally transformed or cleared
192
+ // this field (for example, a write-only password).
193
+ editedFields.delete(key);
194
+ form.setValue(key, savedValues[key]);
195
+ }
196
+ }
197
+ rebase(savedValues, snapshot);
198
+ }
199
+ pendingPropagation.current = saved;
200
+ }
201
+ if (pendingPropagation.current !== undefined) {
202
+ if (!ownsProfile()) {
203
+ saved = undefined;
204
+ return;
205
+ }
206
+ const propagated = pendingPropagation.current;
207
+ await config.onSaved?.(propagated);
208
+ pendingPropagation.current = undefined;
209
+ saved = propagated;
210
+ }
211
+ })();
212
+ return saved;
213
+ }
214
+ catch (failure) {
215
+ if (mounted)
216
+ error.set(failure);
217
+ return undefined;
218
+ }
219
+ finally {
220
+ activeSave.current = null;
221
+ if (mounted)
222
+ isSaving.set(false);
223
+ }
224
+ };
225
+ activeSave.current = run();
226
+ return activeSave.current;
227
+ };
228
+ const register = (name, registerOptions) => {
229
+ const registration = form.register(name, registerOptions);
230
+ return {
231
+ ...registration,
232
+ onChange: (event) => {
233
+ editedFields.add(name);
234
+ registration.onChange(event);
235
+ },
236
+ };
237
+ };
238
+ const setValue = (name, value) => {
239
+ editedFields.add(name);
240
+ form.setValue(name, value);
241
+ };
242
+ const reset = () => {
243
+ editedFields.clear();
244
+ form.reset(baseline.current);
245
+ error.set(undefined);
246
+ };
247
+ const onSubmit = (event) => {
248
+ event.preventDefault();
249
+ void submit();
250
+ };
251
+ return {
252
+ ...form,
253
+ formState: derived([form.formState, isSaving], ([formValues, saving]) => ({
254
+ ...formValues,
255
+ isSubmitting: saving || formValues.isSubmitting,
256
+ })),
257
+ isSubmitting: derived([isSaving, form.isSubmitting], ([saving, formSaving]) => saving || formSaving),
258
+ user,
259
+ ready: derived(user, (currentUser) => currentUser !== null),
260
+ error: { subscribe: error.subscribe },
261
+ register,
262
+ setValue,
263
+ reset,
264
+ submit,
265
+ formProps: { onSubmit },
266
+ };
267
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Svelte hook for tracking async function state, porting React's `usePromise`.
3
+ *
4
+ * @module
5
+ */
6
+ import { type Readable } from 'svelte/store';
7
+ import type { PromiseStatus } from '@molecule/app-utilities';
8
+ /**
9
+ * Extended promise state with actions, React's `UsePromiseState`.
10
+ */
11
+ export interface UsePromiseState<T> {
12
+ status: PromiseStatus;
13
+ value: T | null;
14
+ error: Error | null;
15
+ cancel: (message?: string) => void;
16
+ reset: () => void;
17
+ }
18
+ /**
19
+ * The store {@link usePromise} returns: the current `[state, call]` tuple.
20
+ */
21
+ export type UsePromiseStore<T, A extends unknown[]> = Readable<readonly [UsePromiseState<T>, (...args: A) => Promise<T>]>;
22
+ /**
23
+ * Wraps an async function with state tracking, React's `usePromise` in
24
+ * Svelte's idiom.
25
+ *
26
+ * For one UI action, pass `$store[0].status === 'pending'` to `Button loading`
27
+ * from `@molecule/app-ui-svelte` (or disable a native control). The control
28
+ * then refuses input while the request is pending and re-enables when the
29
+ * tracked call settles. Handle the returned promise's rejection; the hook
30
+ * also records the failure in `state.error`.
31
+ *
32
+ * This hook tracks the latest call: it does not serialize invocations or
33
+ * cancel their network requests. An explicit reset/cancel changes the tracked
34
+ * state, so it is not proof that an outstanding request has stopped. Use an
35
+ * app-owned queue when every click must be accepted in order.
36
+ *
37
+ * The result is a readable store of the `[state, call]` tuple (React's tuple
38
+ * shape): `$store[0]` is the current state, `$store[1]` the tracked function.
39
+ * A pending call keeps the PREVIOUS `value`; a rejection records the error
40
+ * (keeping the previous `value`) and rethrows to its caller; `cancel(message?)`
41
+ * marks the state `rejected` with `new Error(message)` — or no error when no
42
+ * message is given; `reset()` returns to idle.
43
+ *
44
+ * @param asyncFn - The async function to wrap.
45
+ * @returns A readable store of the [state, wrappedFunction] tuple.
46
+ * @example
47
+ * ```svelte
48
+ * <script>
49
+ * import { usePromise } from '@molecule/app-svelte'
50
+ * const fetchUser = usePromise((id: string) => api.getUser(id))
51
+ * const [state, call] = $fetchUser
52
+ * </script>
53
+ *
54
+ * <button onclick={() => call('123')} disabled={state.status === 'pending'}>
55
+ * {state.status === 'pending' ? 'Loading…' : 'Fetch user'}
56
+ * </button>
57
+ * {#if state.value}<div>{state.value.name}</div>{/if}
58
+ * {#if state.error}<div>Error: {state.error.message}</div>{/if}
59
+ * ```
60
+ */
61
+ export declare function usePromise<T, A extends unknown[]>(asyncFn: (...args: A) => Promise<T>): UsePromiseStore<T, A>;
62
+ //# sourceMappingURL=usePromise.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usePromise.d.ts","sourceRoot":"","sources":["../../src/hooks/usePromise.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,KAAK,QAAQ,EAA2B,MAAM,cAAc,CAAA;AAErE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AAE5D;;GAEG;AACH,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,MAAM,EAAE,aAAa,CAAA;IACrB,KAAK,EAAE,CAAC,GAAG,IAAI,CAAA;IACf,KAAK,EAAE,KAAK,GAAG,IAAI,CAAA;IACnB,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,MAAM,KAAK,IAAI,CAAA;IAClC,KAAK,EAAE,MAAM,IAAI,CAAA;CAClB;AAED;;GAEG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,EAAE,CAAC,SAAS,OAAO,EAAE,IAAI,QAAQ,CAC5D,SAAS,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,CAC1D,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,SAAS,OAAO,EAAE,EAC/C,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,GAClC,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,CAmEvB"}
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Svelte hook for tracking async function state, porting React's `usePromise`.
3
+ *
4
+ * @module
5
+ */
6
+ import { onDestroy } from 'svelte';
7
+ import { writable } from 'svelte/store';
8
+ /**
9
+ * Wraps an async function with state tracking, React's `usePromise` in
10
+ * Svelte's idiom.
11
+ *
12
+ * For one UI action, pass `$store[0].status === 'pending'` to `Button loading`
13
+ * from `@molecule/app-ui-svelte` (or disable a native control). The control
14
+ * then refuses input while the request is pending and re-enables when the
15
+ * tracked call settles. Handle the returned promise's rejection; the hook
16
+ * also records the failure in `state.error`.
17
+ *
18
+ * This hook tracks the latest call: it does not serialize invocations or
19
+ * cancel their network requests. An explicit reset/cancel changes the tracked
20
+ * state, so it is not proof that an outstanding request has stopped. Use an
21
+ * app-owned queue when every click must be accepted in order.
22
+ *
23
+ * The result is a readable store of the `[state, call]` tuple (React's tuple
24
+ * shape): `$store[0]` is the current state, `$store[1]` the tracked function.
25
+ * A pending call keeps the PREVIOUS `value`; a rejection records the error
26
+ * (keeping the previous `value`) and rethrows to its caller; `cancel(message?)`
27
+ * marks the state `rejected` with `new Error(message)` — or no error when no
28
+ * message is given; `reset()` returns to idle.
29
+ *
30
+ * @param asyncFn - The async function to wrap.
31
+ * @returns A readable store of the [state, wrappedFunction] tuple.
32
+ * @example
33
+ * ```svelte
34
+ * <script>
35
+ * import { usePromise } from '@molecule/app-svelte'
36
+ * const fetchUser = usePromise((id: string) => api.getUser(id))
37
+ * const [state, call] = $fetchUser
38
+ * </script>
39
+ *
40
+ * <button onclick={() => call('123')} disabled={state.status === 'pending'}>
41
+ * {state.status === 'pending' ? 'Loading…' : 'Fetch user'}
42
+ * </button>
43
+ * {#if state.value}<div>{state.value.name}</div>{/if}
44
+ * {#if state.error}<div>Error: {state.error.message}</div>{/if}
45
+ * ```
46
+ */
47
+ export function usePromise(asyncFn) {
48
+ let isUnmounted = false;
49
+ let callId = 0;
50
+ const state = {
51
+ status: 'idle',
52
+ value: null,
53
+ error: null,
54
+ cancel: (message) => {
55
+ callId += 1;
56
+ if (!isUnmounted) {
57
+ publish({
58
+ status: 'rejected',
59
+ value: state.value,
60
+ error: message ? new Error(message) : null,
61
+ });
62
+ }
63
+ },
64
+ reset: () => {
65
+ if (!isUnmounted) {
66
+ publish({ status: 'idle', value: null, error: null });
67
+ }
68
+ },
69
+ };
70
+ const tuple = writable([
71
+ state,
72
+ call,
73
+ ]);
74
+ onDestroy(() => {
75
+ isUnmounted = true;
76
+ });
77
+ /** Replaces the tracked state (the same `state` object, mutated). */
78
+ function publish(next) {
79
+ state.status = next.status;
80
+ state.value = next.value;
81
+ state.error = next.error;
82
+ tuple.set([state, call]);
83
+ }
84
+ /** The tracked function, one stable identity for the component's life. */
85
+ function call(...args) {
86
+ callId += 1;
87
+ const thisCallId = callId;
88
+ if (!isUnmounted) {
89
+ publish({ status: 'pending', value: state.value, error: null });
90
+ }
91
+ return asyncFn(...args).then((resolved) => {
92
+ if (thisCallId === callId && !isUnmounted) {
93
+ publish({ status: 'resolved', value: resolved, error: null });
94
+ }
95
+ return resolved;
96
+ }, (err) => {
97
+ const rejection = err instanceof Error ? err : new Error(String(err));
98
+ if (thisCallId === callId && !isUnmounted) {
99
+ publish({ status: 'rejected', value: state.value, error: rejection });
100
+ }
101
+ throw rejection;
102
+ });
103
+ }
104
+ return tuple;
105
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Svelte hook for push notifications, porting React's `usePush`.
3
+ *
4
+ * @module
5
+ */
6
+ import { type Readable } from 'svelte/store';
7
+ import type { NotificationActionListener, NotificationReceivedListener, PermissionStatus, PushRegisterOptions, PushToken, TokenChangeListener } from '@molecule/app-push';
8
+ /**
9
+ * Hook return type.
10
+ */
11
+ export interface UsePushResult {
12
+ /** The last permission status a check or request reported, null until one runs. */
13
+ permission: Readable<PermissionStatus | null>;
14
+ /** The token register() resolved, null until a registration. */
15
+ token: Readable<PushToken | null>;
16
+ /** Reads the permission status from the provider. */
17
+ checkPermission: () => Promise<PermissionStatus>;
18
+ /** Asks the user for permission and stores the answer. */
19
+ requestPermission: () => Promise<PermissionStatus>;
20
+ /** Registers for push and stores the token. */
21
+ register: (options?: PushRegisterOptions) => Promise<PushToken>;
22
+ /** Unregisters and clears the token. */
23
+ unregister: () => Promise<void>;
24
+ /** Subscribes a notification listener; returns its unsubscribe. */
25
+ onNotificationReceived: (listener: NotificationReceivedListener) => () => void;
26
+ /** Subscribes a notification-action listener; returns its unsubscribe. */
27
+ onNotificationAction: (listener: NotificationActionListener) => () => void;
28
+ /** Subscribes a token-change listener; returns its unsubscribe. */
29
+ onTokenChange: (listener: TokenChangeListener) => () => void;
30
+ /** Sets the badge count. */
31
+ setBadge: (count: number) => Promise<void>;
32
+ /** Clears the badge. */
33
+ clearBadge: () => Promise<void>;
34
+ }
35
+ /**
36
+ * Options for the usePush hook (e.g. check permission on mount).
37
+ */
38
+ export interface UsePushOptions {
39
+ /**
40
+ * Whether to check permission status on mount.
41
+ */
42
+ checkOnMount?: boolean;
43
+ }
44
+ /**
45
+ * Push notification state and actions, React's `usePush` in Svelte's idiom:
46
+ * called during component init, `permission` and `token` are readable stores
47
+ * the hook's own actions update, and the rest are plain functions.
48
+ *
49
+ * Uses module-level `getProvider()` — push is a singleton, not
50
+ * context-provided. The provider's listeners are caller-managed: the returned
51
+ * `on*` unsubscribes are the caller's to call, like React's.
52
+ *
53
+ * @param options - Hook options
54
+ * @returns Push notification state and action methods
55
+ * @example
56
+ * ```svelte
57
+ * <script>
58
+ * import { usePush } from '@molecule/app-svelte'
59
+ * const { permission, requestPermission, register } = usePush({ checkOnMount: true })
60
+ * </script>
61
+ *
62
+ * {#if $permission === 'default'}
63
+ * <button onclick={requestPermission}>Enable Notifications</button>
64
+ * {/if}
65
+ * ```
66
+ */
67
+ export declare function usePush(options?: UsePushOptions): UsePushResult;
68
+ //# sourceMappingURL=usePush.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usePush.d.ts","sourceRoot":"","sources":["../../src/hooks/usePush.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,QAAQ,EAAY,MAAM,cAAc,CAAA;AAGtD,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC5B,gBAAgB,EAEhB,mBAAmB,EACnB,SAAS,EACT,mBAAmB,EACpB,MAAM,oBAAoB,CAAA;AAG3B;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,mFAAmF;IACnF,UAAU,EAAE,QAAQ,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAA;IAC7C,gEAAgE;IAChE,KAAK,EAAE,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC,CAAA;IACjC,qDAAqD;IACrD,eAAe,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,CAAA;IAChD,0DAA0D;IAC1D,iBAAiB,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,CAAA;IAClD,+CAA+C;IAC/C,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,mBAAmB,KAAK,OAAO,CAAC,SAAS,CAAC,CAAA;IAC/D,wCAAwC;IACxC,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAC/B,mEAAmE;IACnE,sBAAsB,EAAE,CAAC,QAAQ,EAAE,4BAA4B,KAAK,MAAM,IAAI,CAAA;IAC9E,0EAA0E;IAC1E,oBAAoB,EAAE,CAAC,QAAQ,EAAE,0BAA0B,KAAK,MAAM,IAAI,CAAA;IAC1E,mEAAmE;IACnE,aAAa,EAAE,CAAC,QAAQ,EAAE,mBAAmB,KAAK,MAAM,IAAI,CAAA;IAC5D,4BAA4B;IAC5B,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC1C,wBAAwB;IACxB,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CAChC;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,OAAO,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,aAAa,CAoD/D"}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Svelte hook for push notifications, porting React's `usePush`.
3
+ *
4
+ * @module
5
+ */
6
+ import { writable } from 'svelte/store';
7
+ import { getLogger } from '@molecule/app-logger';
8
+ import { getProvider } from '@molecule/app-push';
9
+ /**
10
+ * Push notification state and actions, React's `usePush` in Svelte's idiom:
11
+ * called during component init, `permission` and `token` are readable stores
12
+ * the hook's own actions update, and the rest are plain functions.
13
+ *
14
+ * Uses module-level `getProvider()` — push is a singleton, not
15
+ * context-provided. The provider's listeners are caller-managed: the returned
16
+ * `on*` unsubscribes are the caller's to call, like React's.
17
+ *
18
+ * @param options - Hook options
19
+ * @returns Push notification state and action methods
20
+ * @example
21
+ * ```svelte
22
+ * <script>
23
+ * import { usePush } from '@molecule/app-svelte'
24
+ * const { permission, requestPermission, register } = usePush({ checkOnMount: true })
25
+ * </script>
26
+ *
27
+ * {#if $permission === 'default'}
28
+ * <button onclick={requestPermission}>Enable Notifications</button>
29
+ * {/if}
30
+ * ```
31
+ */
32
+ export function usePush(options) {
33
+ const { checkOnMount = false } = options ?? {};
34
+ const provider = getProvider();
35
+ const permission = writable(null);
36
+ const token = writable(null);
37
+ // React's mount effect: a failed mount check leaves the permission unknown
38
+ // until checkPermission() runs again; the failure goes to the logger.
39
+ if (checkOnMount) {
40
+ provider
41
+ .checkPermission()
42
+ .then((status) => permission.set(status))
43
+ .catch((error) => {
44
+ getLogger('usePush').warn('Checking push permission on mount failed', { error });
45
+ });
46
+ }
47
+ return {
48
+ permission: { subscribe: permission.subscribe },
49
+ token: { subscribe: token.subscribe },
50
+ checkPermission: async () => {
51
+ const status = await provider.checkPermission();
52
+ permission.set(status);
53
+ return status;
54
+ },
55
+ requestPermission: async () => {
56
+ const status = await provider.requestPermission();
57
+ permission.set(status);
58
+ return status;
59
+ },
60
+ register: async (registerOptions) => {
61
+ const pushToken = await provider.register(registerOptions);
62
+ token.set(pushToken);
63
+ return pushToken;
64
+ },
65
+ unregister: async () => {
66
+ await provider.unregister();
67
+ token.set(null);
68
+ },
69
+ onNotificationReceived: (listener) => provider.onNotificationReceived(listener),
70
+ onNotificationAction: (listener) => provider.onNotificationAction(listener),
71
+ onTokenChange: (listener) => provider.onTokenChange(listener),
72
+ setBadge: async (count) => {
73
+ await provider.setBadge(count);
74
+ },
75
+ clearBadge: async () => {
76
+ await provider.clearBadge();
77
+ },
78
+ };
79
+ }