@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,451 @@
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 { getOfflineStorage, isOfflineStorageInitialized, } from '@classic-homes/offline-core';
33
+ const DEFAULT_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
34
+ const DEFAULT_DEBOUNCE_MS = 500;
35
+ const DEFAULT_SUBMIT_COOLDOWN_MS = 5000;
36
+ /**
37
+ * Create a persisted form with file support
38
+ */
39
+ export function usePersistedForm(options) {
40
+ const { schema, initialValues, storageKey, excludeFields = [], fileFields = [], expirationMs = DEFAULT_EXPIRATION_MS, debounceMs = DEFAULT_DEBOUNCE_MS, submitCooldownMs = DEFAULT_SUBMIT_COOLDOWN_MS, onDraftRestored, onSubmit, multiDraft = false, draftId: initialDraftId, onDraftChange, } = options;
41
+ // Form state
42
+ let data = $state(JSON.parse(JSON.stringify(initialValues)));
43
+ let errors = $state({});
44
+ let globalError = $state(null);
45
+ let isSubmitting = $state(false);
46
+ let isSubmitted = $state(false);
47
+ let isDirty = $state(false);
48
+ let draftRestored = $state(false);
49
+ let fileRefs = $state({});
50
+ let lastSubmitTime = 0;
51
+ let debounceTimer = null;
52
+ // Multi-draft state
53
+ let currentDraftId = $state(initialDraftId ?? null);
54
+ let currentDraftMetadata = $state(null);
55
+ // Store original values for reset
56
+ const originalInitialValues = JSON.parse(JSON.stringify(initialValues));
57
+ /**
58
+ * Load draft from storage
59
+ */
60
+ async function loadDraft() {
61
+ if (!isOfflineStorageInitialized()) {
62
+ return;
63
+ }
64
+ try {
65
+ const storage = getOfflineStorage();
66
+ if (multiDraft) {
67
+ // Multi-draft mode: Use DraftManagerService
68
+ let draft = null;
69
+ if (currentDraftId) {
70
+ // Load specific draft
71
+ draft = await storage.draftManager.getDraft(currentDraftId);
72
+ }
73
+ else {
74
+ // Load current draft for this form
75
+ draft = await storage.draftManager.getCurrentDraft(storageKey);
76
+ }
77
+ if (draft) {
78
+ data = { ...JSON.parse(JSON.stringify(initialValues)), ...draft.data };
79
+ fileRefs = draft.fileRefs || {};
80
+ currentDraftId = draft.metadata.id;
81
+ currentDraftMetadata = draft.metadata;
82
+ draftRestored = true;
83
+ onDraftRestored?.();
84
+ onDraftChange?.(draft.metadata);
85
+ }
86
+ }
87
+ else {
88
+ // Legacy single-draft mode
89
+ const result = await storage.drafts.loadDraft(storageKey);
90
+ if (result.restored && result.draft) {
91
+ // Merge draft data with initial values
92
+ data = { ...JSON.parse(JSON.stringify(initialValues)), ...result.draft.data };
93
+ fileRefs = result.draft.fileRefs || {};
94
+ draftRestored = true;
95
+ onDraftRestored?.();
96
+ }
97
+ }
98
+ }
99
+ catch (err) {
100
+ console.warn('Failed to load form draft:', err);
101
+ }
102
+ }
103
+ /**
104
+ * Save draft to storage
105
+ */
106
+ async function saveDraft() {
107
+ if (!isOfflineStorageInitialized() || !isDirty) {
108
+ return;
109
+ }
110
+ try {
111
+ const storage = getOfflineStorage();
112
+ // Filter out excluded fields
113
+ const dataToPersist = { ...data };
114
+ for (const field of excludeFields) {
115
+ delete dataToPersist[field];
116
+ }
117
+ if (multiDraft) {
118
+ // Multi-draft mode: Use DraftManagerService
119
+ if (currentDraftId) {
120
+ // Update existing draft
121
+ await storage.draftManager.updateDraft(currentDraftId, dataToPersist, fileRefs);
122
+ // Update metadata
123
+ const metadata = await storage.draftManager.getDraftMetadata(currentDraftId);
124
+ if (metadata) {
125
+ currentDraftMetadata = metadata;
126
+ onDraftChange?.(metadata);
127
+ }
128
+ }
129
+ else {
130
+ // Create new draft
131
+ const metadata = await storage.draftManager.createDraft(storageKey, {
132
+ initialData: dataToPersist,
133
+ initialFileRefs: fileRefs,
134
+ expirationMs,
135
+ });
136
+ currentDraftId = metadata.id;
137
+ currentDraftMetadata = metadata;
138
+ await storage.draftManager.setCurrentDraft(storageKey, metadata.id);
139
+ onDraftChange?.(metadata);
140
+ }
141
+ }
142
+ else {
143
+ // Legacy single-draft mode
144
+ await storage.drafts.saveDraft(storageKey, dataToPersist, fileRefs, {
145
+ excludeFields: excludeFields,
146
+ expirationMs,
147
+ });
148
+ }
149
+ }
150
+ catch (err) {
151
+ console.warn('Failed to save form draft:', err);
152
+ }
153
+ }
154
+ /**
155
+ * Debounced draft saving
156
+ */
157
+ function scheduleSaveDraft() {
158
+ if (debounceTimer) {
159
+ clearTimeout(debounceTimer);
160
+ }
161
+ debounceTimer = setTimeout(() => {
162
+ void saveDraft();
163
+ }, debounceMs);
164
+ }
165
+ /**
166
+ * Set a field value
167
+ */
168
+ function setField(field, value) {
169
+ data[field] = value;
170
+ isDirty = true;
171
+ scheduleSaveDraft();
172
+ }
173
+ /**
174
+ * Set multiple fields
175
+ */
176
+ function setFields(fields) {
177
+ Object.assign(data, fields);
178
+ isDirty = true;
179
+ scheduleSaveDraft();
180
+ }
181
+ /**
182
+ * Validate a single field
183
+ */
184
+ function validateField(field) {
185
+ const fieldSchema = schema.shape[field];
186
+ if (!fieldSchema)
187
+ return true;
188
+ const result = fieldSchema.safeParse(data[field]);
189
+ if (result.success) {
190
+ delete errors[field];
191
+ return true;
192
+ }
193
+ errors[field] = result.error.issues[0]?.message ?? 'Invalid';
194
+ return false;
195
+ }
196
+ /**
197
+ * Validate entire form
198
+ */
199
+ function validate() {
200
+ const result = schema.safeParse(data);
201
+ if (result.success) {
202
+ errors = {};
203
+ return true;
204
+ }
205
+ const newErrors = {};
206
+ for (const issue of result.error.issues) {
207
+ const field = issue.path[0];
208
+ if (!newErrors[field]) {
209
+ newErrors[field] = issue.message;
210
+ }
211
+ }
212
+ errors = newErrors;
213
+ return false;
214
+ }
215
+ /**
216
+ * Get computed isValid
217
+ */
218
+ const isValid = $derived(Object.keys(errors).length === 0 && schema.safeParse(data).success);
219
+ /**
220
+ * Handle form submission
221
+ */
222
+ async function handleSubmit(event) {
223
+ event?.preventDefault();
224
+ // Check cooldown
225
+ const now = Date.now();
226
+ if (now - lastSubmitTime < submitCooldownMs) {
227
+ globalError = 'Please wait before submitting again';
228
+ return;
229
+ }
230
+ // Validate
231
+ if (!validate()) {
232
+ return;
233
+ }
234
+ isSubmitting = true;
235
+ globalError = null;
236
+ try {
237
+ // Get files for submission
238
+ const files = await getFilesForSubmit();
239
+ await onSubmit(data, files);
240
+ lastSubmitTime = now;
241
+ isSubmitted = true;
242
+ // Clear draft on success
243
+ await clearDraft();
244
+ }
245
+ catch (err) {
246
+ globalError = err instanceof Error ? err.message : 'Submission failed';
247
+ lastSubmitTime = 0; // Reset cooldown on error
248
+ throw err;
249
+ }
250
+ finally {
251
+ isSubmitting = false;
252
+ }
253
+ }
254
+ /**
255
+ * Reset the form
256
+ */
257
+ function reset() {
258
+ data = JSON.parse(JSON.stringify(originalInitialValues));
259
+ errors = {};
260
+ globalError = null;
261
+ isSubmitted = false;
262
+ isDirty = false;
263
+ draftRestored = false;
264
+ fileRefs = {};
265
+ void clearDraft();
266
+ }
267
+ /**
268
+ * Clear errors
269
+ */
270
+ function clearErrors() {
271
+ errors = {};
272
+ globalError = null;
273
+ }
274
+ /**
275
+ * Set a field error
276
+ */
277
+ function setError(field, message) {
278
+ errors[field] = message;
279
+ }
280
+ /**
281
+ * Set global error
282
+ */
283
+ function setGlobalError(message) {
284
+ globalError = message;
285
+ }
286
+ /**
287
+ * Clear the stored draft
288
+ */
289
+ async function clearDraft() {
290
+ if (!isOfflineStorageInitialized()) {
291
+ return;
292
+ }
293
+ try {
294
+ const storage = getOfflineStorage();
295
+ if (multiDraft && currentDraftId) {
296
+ // Multi-draft mode: Delete specific draft
297
+ await storage.draftManager.deleteDraft(currentDraftId, true);
298
+ currentDraftId = null;
299
+ currentDraftMetadata = null;
300
+ onDraftChange?.(null);
301
+ }
302
+ else {
303
+ // Legacy single-draft mode
304
+ await storage.drafts.clearDraft(storageKey);
305
+ }
306
+ // Also clear associated files
307
+ for (const fieldName of fileFields) {
308
+ await storage.files.deleteFormFiles(storageKey, fieldName);
309
+ }
310
+ }
311
+ catch (err) {
312
+ console.warn('Failed to clear form draft:', err);
313
+ }
314
+ }
315
+ /**
316
+ * Dismiss draft notification
317
+ */
318
+ function dismissDraftNotification() {
319
+ draftRestored = false;
320
+ }
321
+ /**
322
+ * Update file references for a field
323
+ */
324
+ function updateFileRefs(fieldName, fileIds) {
325
+ fileRefs = { ...fileRefs, [fieldName]: fileIds };
326
+ isDirty = true;
327
+ scheduleSaveDraft();
328
+ }
329
+ /**
330
+ * Get files for submission
331
+ */
332
+ async function getFilesForSubmit() {
333
+ if (!isOfflineStorageInitialized()) {
334
+ return {};
335
+ }
336
+ const storage = getOfflineStorage();
337
+ const result = {};
338
+ for (const fieldName of fileFields) {
339
+ const ids = fileRefs[fieldName] || [];
340
+ const fileMap = await storage.files.getFilesAsFileObjects(ids);
341
+ result[fieldName] = Array.from(fileMap.values());
342
+ }
343
+ return result;
344
+ }
345
+ /**
346
+ * Save current data as a new draft (multi-draft mode)
347
+ */
348
+ async function saveAsNewDraft(name) {
349
+ if (!isOfflineStorageInitialized()) {
350
+ throw new Error('Offline storage not initialized');
351
+ }
352
+ const storage = getOfflineStorage();
353
+ // Filter out excluded fields
354
+ const dataToPersist = { ...data };
355
+ for (const field of excludeFields) {
356
+ delete dataToPersist[field];
357
+ }
358
+ const metadata = await storage.draftManager.createDraft(storageKey, {
359
+ name,
360
+ initialData: dataToPersist,
361
+ initialFileRefs: fileRefs,
362
+ expirationMs,
363
+ });
364
+ // Switch to the new draft
365
+ currentDraftId = metadata.id;
366
+ currentDraftMetadata = metadata;
367
+ await storage.draftManager.setCurrentDraft(storageKey, metadata.id);
368
+ onDraftChange?.(metadata);
369
+ return metadata;
370
+ }
371
+ /**
372
+ * Load a specific draft by ID (multi-draft mode)
373
+ */
374
+ async function loadDraftById(draftIdToLoad) {
375
+ if (!isOfflineStorageInitialized()) {
376
+ return false;
377
+ }
378
+ const storage = getOfflineStorage();
379
+ const draft = await storage.draftManager.getDraft(draftIdToLoad);
380
+ if (!draft) {
381
+ return false;
382
+ }
383
+ // Update form state
384
+ data = { ...JSON.parse(JSON.stringify(initialValues)), ...draft.data };
385
+ fileRefs = draft.fileRefs || {};
386
+ currentDraftId = draft.metadata.id;
387
+ currentDraftMetadata = draft.metadata;
388
+ isDirty = false;
389
+ draftRestored = true;
390
+ // Set as current draft
391
+ await storage.draftManager.setCurrentDraft(storageKey, draftIdToLoad);
392
+ onDraftChange?.(draft.metadata);
393
+ onDraftRestored?.();
394
+ return true;
395
+ }
396
+ // Load draft on initialization
397
+ $effect(() => {
398
+ void loadDraft();
399
+ });
400
+ return {
401
+ get data() {
402
+ return data;
403
+ },
404
+ get errors() {
405
+ return errors;
406
+ },
407
+ get globalError() {
408
+ return globalError;
409
+ },
410
+ get isSubmitting() {
411
+ return isSubmitting;
412
+ },
413
+ get isSubmitted() {
414
+ return isSubmitted;
415
+ },
416
+ get isDirty() {
417
+ return isDirty;
418
+ },
419
+ get isValid() {
420
+ return isValid;
421
+ },
422
+ get draftRestored() {
423
+ return draftRestored;
424
+ },
425
+ get fileRefs() {
426
+ return fileRefs;
427
+ },
428
+ setField,
429
+ setFields,
430
+ validateField,
431
+ validate,
432
+ handleSubmit,
433
+ reset,
434
+ clearErrors,
435
+ setError,
436
+ setGlobalError,
437
+ clearDraft,
438
+ dismissDraftNotification,
439
+ updateFileRefs,
440
+ getFilesForSubmit,
441
+ // Multi-draft
442
+ get currentDraftId() {
443
+ return currentDraftId;
444
+ },
445
+ get currentDraftMetadata() {
446
+ return currentDraftMetadata;
447
+ },
448
+ saveAsNewDraft,
449
+ loadDraftById,
450
+ };
451
+ }
package/package.json ADDED
@@ -0,0 +1,85 @@
1
+ {
2
+ "name": "@classic-homes/offline-svelte",
3
+ "version": "0.1.1",
4
+ "description": "Svelte bindings for offline persistence and caching",
5
+ "type": "module",
6
+ "svelte": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "svelte": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./useFileStorage": {
15
+ "types": "./dist/useFileStorage.svelte.d.ts",
16
+ "svelte": "./dist/useFileStorage.svelte.js",
17
+ "default": "./dist/useFileStorage.svelte.js"
18
+ },
19
+ "./usePersistedForm": {
20
+ "types": "./dist/usePersistedForm.svelte.d.ts",
21
+ "svelte": "./dist/usePersistedForm.svelte.js",
22
+ "default": "./dist/usePersistedForm.svelte.js"
23
+ },
24
+ "./useOfflineCache": {
25
+ "types": "./dist/useOfflineCache.svelte.d.ts",
26
+ "svelte": "./dist/useOfflineCache.svelte.js",
27
+ "default": "./dist/useOfflineCache.svelte.js"
28
+ }
29
+ },
30
+ "sideEffects": false,
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "scripts": {
35
+ "build": "svelte-package -i src",
36
+ "dev": "svelte-package -i src --watch",
37
+ "clean": "rm -rf dist",
38
+ "typecheck": "svelte-check --tsconfig ./tsconfig.json",
39
+ "test": "vitest run",
40
+ "test:watch": "vitest",
41
+ "test:coverage": "vitest run --coverage"
42
+ },
43
+ "keywords": [
44
+ "svelte",
45
+ "offline",
46
+ "persistence",
47
+ "storage",
48
+ "cache",
49
+ "classic-theme"
50
+ ],
51
+ "license": "MIT",
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "https://github.com/Classic-Homes/classic-theme.git",
55
+ "directory": "packages/offline-svelte"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
60
+ "peerDependencies": {
61
+ "svelte": "^5.0.0",
62
+ "zod": "^3.23.0"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "zod": {
66
+ "optional": true
67
+ }
68
+ },
69
+ "dependencies": {
70
+ "@classic-homes/offline-core": "*"
71
+ },
72
+ "devDependencies": {
73
+ "@sveltejs/package": "^2.3.0",
74
+ "@sveltejs/vite-plugin-svelte": "^4.0.0",
75
+ "@testing-library/svelte": "^5.0.0",
76
+ "@vitest/coverage-v8": "^2.0.0",
77
+ "fake-indexeddb": "^6.0.0",
78
+ "jsdom": "^25.0.0",
79
+ "svelte": "^5.0.0",
80
+ "svelte-check": "^4.0.0",
81
+ "typescript": "^5.3.0",
82
+ "vitest": "^2.0.0",
83
+ "zod": "^3.23.0"
84
+ }
85
+ }