@classic-homes/offline-svelte 0.1.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.
@@ -0,0 +1,229 @@
1
+ /**
2
+ * useOfflineCache - Svelte composable for caching data
3
+ *
4
+ * Provides reactive caching with TTL and stale-while-revalidate support.
5
+ *
6
+ * @example
7
+ * ```svelte
8
+ * <script lang="ts">
9
+ * import { useOfflineCache } from '@classic-homes/offline-svelte';
10
+ *
11
+ * const userCache = useOfflineCache<User>({
12
+ * key: 'current-user',
13
+ * ttl: 60 * 60 * 1000, // 1 hour
14
+ * staleWhileRevalidate: true,
15
+ * });
16
+ *
17
+ * // Load from cache or fetch
18
+ * $effect(() => {
19
+ * userCache.get(async () => {
20
+ * return await fetchCurrentUser();
21
+ * });
22
+ * });
23
+ * </script>
24
+ *
25
+ * {#if userCache.isLoading}
26
+ * <Spinner />
27
+ * {:else if userCache.data}
28
+ * <UserProfile user={userCache.data} />
29
+ * {/if}
30
+ * ```
31
+ */
32
+ import { getOfflineStorage, isOfflineStorageInitialized, } from '@classic-homes/offline-core';
33
+ /**
34
+ * Create a cache composable for a specific key
35
+ */
36
+ export function useOfflineCache(options) {
37
+ const { key, ttl, tags, staleWhileRevalidate = false, staleTime, fetcher } = options;
38
+ // Reactive state
39
+ let data = $state(null);
40
+ let isLoading = $state(false);
41
+ let isStale = $state(false);
42
+ let error = $state(null);
43
+ let ttlRemaining = $state(null);
44
+ /**
45
+ * Update state from cache result
46
+ */
47
+ function updateFromResult(result) {
48
+ if (result.hit) {
49
+ data = result.value;
50
+ isStale = result.stale;
51
+ ttlRemaining = result.ttlRemaining;
52
+ }
53
+ }
54
+ /**
55
+ * Get cached value or fetch it
56
+ */
57
+ async function get(fetcher) {
58
+ if (!isOfflineStorageInitialized()) {
59
+ // Without storage, just fetch directly
60
+ isLoading = true;
61
+ try {
62
+ const value = await fetcher();
63
+ data = value;
64
+ return value;
65
+ }
66
+ catch (err) {
67
+ error = err instanceof Error ? err : new Error(String(err));
68
+ throw error;
69
+ }
70
+ finally {
71
+ isLoading = false;
72
+ }
73
+ }
74
+ const storage = getOfflineStorage();
75
+ try {
76
+ isLoading = true;
77
+ error = null;
78
+ const value = await storage.cache.getOrSet(key, fetcher, {
79
+ ttl,
80
+ tags,
81
+ staleWhileRevalidate,
82
+ staleTime,
83
+ onFetching: () => {
84
+ isLoading = true;
85
+ },
86
+ onFetchComplete: (err) => {
87
+ isLoading = false;
88
+ if (err) {
89
+ error = err;
90
+ }
91
+ },
92
+ });
93
+ // Update reactive state
94
+ const result = await storage.cache.get(key);
95
+ updateFromResult(result);
96
+ return value;
97
+ }
98
+ catch (err) {
99
+ error = err instanceof Error ? err : new Error(String(err));
100
+ throw error;
101
+ }
102
+ finally {
103
+ isLoading = false;
104
+ }
105
+ }
106
+ /**
107
+ * Set cached value directly
108
+ */
109
+ async function set(value) {
110
+ if (!isOfflineStorageInitialized()) {
111
+ data = value;
112
+ return;
113
+ }
114
+ const storage = getOfflineStorage();
115
+ try {
116
+ await storage.cache.set(key, value, { ttl, tags });
117
+ data = value;
118
+ isStale = false;
119
+ ttlRemaining = ttl ?? null;
120
+ }
121
+ catch (err) {
122
+ error = err instanceof Error ? err : new Error(String(err));
123
+ throw error;
124
+ }
125
+ }
126
+ /**
127
+ * Invalidate the cache
128
+ */
129
+ async function invalidate() {
130
+ if (!isOfflineStorageInitialized()) {
131
+ data = null;
132
+ return;
133
+ }
134
+ const storage = getOfflineStorage();
135
+ await storage.cache.invalidate(key);
136
+ data = null;
137
+ isStale = false;
138
+ ttlRemaining = null;
139
+ }
140
+ /**
141
+ * Refresh the cache (re-fetch)
142
+ */
143
+ async function refresh(fetcher) {
144
+ await invalidate();
145
+ return get(fetcher);
146
+ }
147
+ /**
148
+ * Check if cache has a valid entry
149
+ */
150
+ async function has() {
151
+ if (!isOfflineStorageInitialized()) {
152
+ return false;
153
+ }
154
+ const storage = getOfflineStorage();
155
+ return storage.cache.has(key);
156
+ }
157
+ // Load initial cached value and auto-fetch if needed
158
+ $effect(() => {
159
+ if (!isOfflineStorageInitialized()) {
160
+ // If storage not initialized but fetcher provided, fetch directly
161
+ if (fetcher && !data) {
162
+ isLoading = true;
163
+ fetcher()
164
+ .then((value) => {
165
+ data = value;
166
+ })
167
+ .catch((err) => {
168
+ error = err instanceof Error ? err : new Error(String(err));
169
+ })
170
+ .finally(() => {
171
+ isLoading = false;
172
+ });
173
+ }
174
+ return;
175
+ }
176
+ const storage = getOfflineStorage();
177
+ storage.cache.get(key).then((result) => {
178
+ if (result.hit && !result.stale) {
179
+ updateFromResult(result);
180
+ }
181
+ else if (fetcher && !isLoading) {
182
+ // Auto-fetch if no valid cache and fetcher is provided
183
+ get(fetcher);
184
+ }
185
+ });
186
+ });
187
+ return {
188
+ get data() {
189
+ return data;
190
+ },
191
+ get isLoading() {
192
+ return isLoading;
193
+ },
194
+ get isStale() {
195
+ return isStale;
196
+ },
197
+ get error() {
198
+ return error;
199
+ },
200
+ get ttlRemaining() {
201
+ return ttlRemaining;
202
+ },
203
+ get,
204
+ set,
205
+ invalidate,
206
+ refresh,
207
+ has,
208
+ };
209
+ }
210
+ /**
211
+ * Invalidate cache entries by tag
212
+ */
213
+ export async function invalidateCacheByTag(tag) {
214
+ if (!isOfflineStorageInitialized()) {
215
+ return 0;
216
+ }
217
+ const storage = getOfflineStorage();
218
+ return storage.cache.invalidateByTag(tag);
219
+ }
220
+ /**
221
+ * Invalidate all cache entries
222
+ */
223
+ export async function invalidateAllCache() {
224
+ if (!isOfflineStorageInitialized()) {
225
+ return 0;
226
+ }
227
+ const storage = getOfflineStorage();
228
+ return storage.cache.invalidateAll();
229
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * usePersistedForm - Enhanced form persistence with file support
3
+ *
4
+ * This is an enhanced version of the original usePersistedForm that:
5
+ * - Uses the offline storage system instead of localStorage
6
+ * - Supports file field persistence
7
+ * - Coordinates form data and file references
8
+ *
9
+ * @example
10
+ * ```svelte
11
+ * <script lang="ts">
12
+ * import { usePersistedForm } from '@classic-homes/offline-svelte';
13
+ * import { z } from 'zod';
14
+ *
15
+ * const schema = z.object({
16
+ * name: z.string().min(1),
17
+ * email: z.string().email(),
18
+ * });
19
+ *
20
+ * const form = usePersistedForm({
21
+ * schema,
22
+ * initialValues: { name: '', email: '' },
23
+ * storageKey: 'contact-form',
24
+ * fileFields: ['documents'],
25
+ * onSubmit: async (data, files) => {
26
+ * await submitWithFiles(data, files);
27
+ * },
28
+ * });
29
+ * </script>
30
+ * ```
31
+ */
32
+ import type { z } from 'zod';
33
+ import { type DraftMetadata } from '@classic-homes/offline-core';
34
+ /**
35
+ * Base form field error type
36
+ */
37
+ export type FieldErrors<T> = Partial<Record<keyof T, string>>;
38
+ /**
39
+ * Options for the persisted form
40
+ */
41
+ export interface UsePersistedFormOptions<T extends z.ZodObject<z.ZodRawShape>> {
42
+ /** Zod schema for validation */
43
+ schema: T;
44
+ /** Initial form values */
45
+ initialValues: z.infer<T>;
46
+ /** Storage key for draft persistence */
47
+ storageKey: string;
48
+ /** Fields to exclude from persistence (e.g., consent fields) */
49
+ excludeFields?: (keyof z.infer<T>)[];
50
+ /** File field names that should be coordinated with file storage */
51
+ fileFields?: string[];
52
+ /** Expiration time in milliseconds (default: 7 days) */
53
+ expirationMs?: number;
54
+ /** Debounce time for saving drafts in milliseconds (default: 500ms) */
55
+ debounceMs?: number;
56
+ /** Cooldown time between submissions in milliseconds (default: 5000ms) */
57
+ submitCooldownMs?: number;
58
+ /** Callback when draft is restored */
59
+ onDraftRestored?: () => void;
60
+ /** Submit handler - receives form data and file map */
61
+ onSubmit: (data: z.infer<T>, files: Record<string, File[]>) => Promise<void>;
62
+ /** Enable multi-draft mode (V2 storage) */
63
+ multiDraft?: boolean;
64
+ /** Specific draft ID to load (multi-draft mode) */
65
+ draftId?: string;
66
+ /** Callback when draft metadata changes */
67
+ onDraftChange?: (metadata: DraftMetadata | null) => void;
68
+ }
69
+ /**
70
+ * Return type for the persisted form composable
71
+ */
72
+ export interface UsePersistedFormReturn<T extends z.ZodObject<z.ZodRawShape>> {
73
+ /** Form data (reactive) */
74
+ readonly data: z.infer<T>;
75
+ /** Field errors (reactive) */
76
+ readonly errors: FieldErrors<z.infer<T>>;
77
+ /** Global form error */
78
+ readonly globalError: string | null;
79
+ /** Whether form is submitting */
80
+ readonly isSubmitting: boolean;
81
+ /** Whether form was successfully submitted */
82
+ readonly isSubmitted: boolean;
83
+ /** Whether form has been modified */
84
+ readonly isDirty: boolean;
85
+ /** Whether form is valid */
86
+ readonly isValid: boolean;
87
+ /** Whether a draft was restored */
88
+ readonly draftRestored: boolean;
89
+ /** File references by field name */
90
+ readonly fileRefs: Record<string, string[]>;
91
+ /** Set a field value */
92
+ setField: <K extends keyof z.infer<T>>(field: K, value: z.infer<T>[K]) => void;
93
+ /** Set multiple field values */
94
+ setFields: (fields: Partial<z.infer<T>>) => void;
95
+ /** Validate a single field */
96
+ validateField: <K extends keyof z.infer<T>>(field: K) => boolean;
97
+ /** Validate the entire form */
98
+ validate: () => boolean;
99
+ /** Handle form submission */
100
+ handleSubmit: (event?: Event) => Promise<void>;
101
+ /** Reset the form */
102
+ reset: () => void;
103
+ /** Clear all errors */
104
+ clearErrors: () => void;
105
+ /** Set a field error */
106
+ setError: <K extends keyof z.infer<T>>(field: K, message: string) => void;
107
+ /** Set global error */
108
+ setGlobalError: (message: string | null) => void;
109
+ /** Clear the stored draft */
110
+ clearDraft: () => Promise<void>;
111
+ /** Dismiss the draft restored notification */
112
+ dismissDraftNotification: () => void;
113
+ /** Update file references for a field */
114
+ updateFileRefs: (fieldName: string, fileIds: string[]) => void;
115
+ /** Get files for submission */
116
+ getFilesForSubmit: () => Promise<Record<string, File[]>>;
117
+ /** Current draft ID (multi-draft mode) */
118
+ readonly currentDraftId: string | null;
119
+ /** Current draft metadata (multi-draft mode) */
120
+ readonly currentDraftMetadata: DraftMetadata | null;
121
+ /** Save current data as a new draft */
122
+ saveAsNewDraft: (name?: string) => Promise<DraftMetadata>;
123
+ /** Load a specific draft */
124
+ loadDraftById: (draftId: string) => Promise<boolean>;
125
+ }
126
+ /**
127
+ * Create a persisted form with file support
128
+ */
129
+ export declare function usePersistedForm<T extends z.ZodObject<z.ZodRawShape>>(options: UsePersistedFormOptions<T>): UsePersistedFormReturn<T>;