@classic-homes/offline-svelte 0.1.5 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/useDraftSync.svelte.js +58 -27
- package/dist/usePersistedForm.svelte.js +70 -22
- package/package.json +4 -7
- package/dist/__tests__/setup.d.ts +0 -1
- package/dist/__tests__/setup.js +0 -48
- package/dist/__tests__/useFileStorage.test.d.ts +0 -1
- package/dist/__tests__/useFileStorage.test.js +0 -139
- package/dist/__tests__/useOfflineCache.test.d.ts +0 -1
- package/dist/__tests__/useOfflineCache.test.js +0 -119
- package/dist/__tests__/usePersistedForm.test.d.ts +0 -1
- package/dist/__tests__/usePersistedForm.test.js +0 -150
- package/dist/__tests__/usePersistedFormRunes.svelte.test.d.ts +0 -1
- package/dist/__tests__/usePersistedFormRunes.svelte.test.js +0 -90
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
* {/if}
|
|
44
44
|
* ```
|
|
45
45
|
*/
|
|
46
|
-
import {
|
|
46
|
+
import { untrack } from 'svelte';
|
|
47
47
|
import { getOfflineStorage, isOfflineStorageInitialized, createSyncService, } from '@classic-homes/offline-core';
|
|
48
48
|
/**
|
|
49
49
|
* Create a draft sync composable
|
|
@@ -61,6 +61,7 @@ export function useDraftSync(options) {
|
|
|
61
61
|
let isAutoSyncActive = $state(false);
|
|
62
62
|
// Sync service instance
|
|
63
63
|
let syncService = null;
|
|
64
|
+
let disposed = false;
|
|
64
65
|
/**
|
|
65
66
|
* Initialize the sync service
|
|
66
67
|
*/
|
|
@@ -69,7 +70,8 @@ export function useDraftSync(options) {
|
|
|
69
70
|
return;
|
|
70
71
|
}
|
|
71
72
|
const storage = getOfflineStorage();
|
|
72
|
-
|
|
73
|
+
// Local reference: dispose() may clear syncService while this awaits
|
|
74
|
+
const service = createSyncService(storage.adapter, {
|
|
73
75
|
adapter,
|
|
74
76
|
syncIntervalMs,
|
|
75
77
|
autoSyncOnReconnect,
|
|
@@ -77,14 +79,15 @@ export function useDraftSync(options) {
|
|
|
77
79
|
isSyncing = false;
|
|
78
80
|
lastSyncAt = result.timestamp;
|
|
79
81
|
lastResult = result;
|
|
82
|
+
pendingCount = service.pendingCount;
|
|
80
83
|
// The service keeps unresolved conflicts across syncs; a sync that
|
|
81
84
|
// finds no new ones must not clear the list.
|
|
82
|
-
conflicts =
|
|
85
|
+
conflicts = service.getConflicts();
|
|
83
86
|
error = result.error ?? null;
|
|
84
87
|
onSyncComplete?.(result);
|
|
85
88
|
},
|
|
86
89
|
onConflictDetected: (newConflicts) => {
|
|
87
|
-
conflicts =
|
|
90
|
+
conflicts = service.getConflicts();
|
|
88
91
|
onConflictDetected?.(newConflicts);
|
|
89
92
|
},
|
|
90
93
|
onOnlineStatusChange: (online) => {
|
|
@@ -97,15 +100,21 @@ export function useDraftSync(options) {
|
|
|
97
100
|
onSyncError?.(err);
|
|
98
101
|
},
|
|
99
102
|
});
|
|
100
|
-
|
|
103
|
+
syncService = service;
|
|
104
|
+
await service.initialize();
|
|
105
|
+
// Destroyed (or disposed) while initializing: dispose() already disposed
|
|
106
|
+
// this service; don't touch it or restart auto-sync
|
|
107
|
+
if (disposed || syncService !== service) {
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
101
110
|
// Update state from service
|
|
102
|
-
isOnline =
|
|
103
|
-
lastSyncAt =
|
|
104
|
-
pendingCount =
|
|
105
|
-
conflicts =
|
|
111
|
+
isOnline = service.isOnline;
|
|
112
|
+
lastSyncAt = service.lastSyncAt;
|
|
113
|
+
pendingCount = service.pendingCount;
|
|
114
|
+
conflicts = service.getConflicts();
|
|
106
115
|
// Start auto-sync if enabled
|
|
107
116
|
if (autoSync) {
|
|
108
|
-
|
|
117
|
+
service.startAutoSync();
|
|
109
118
|
isAutoSyncActive = true;
|
|
110
119
|
}
|
|
111
120
|
}
|
|
@@ -113,7 +122,9 @@ export function useDraftSync(options) {
|
|
|
113
122
|
* Sync all drafts
|
|
114
123
|
*/
|
|
115
124
|
async function syncAll() {
|
|
116
|
-
|
|
125
|
+
// Local reference: dispose() clears syncService while this awaits
|
|
126
|
+
const service = syncService;
|
|
127
|
+
if (!service) {
|
|
117
128
|
return {
|
|
118
129
|
success: false,
|
|
119
130
|
uploaded: 0,
|
|
@@ -128,14 +139,19 @@ export function useDraftSync(options) {
|
|
|
128
139
|
}
|
|
129
140
|
isSyncing = true;
|
|
130
141
|
error = null;
|
|
142
|
+
// Disposed meanwhile: the outcome belongs to a service (and possibly an
|
|
143
|
+
// account) this state no longer shows
|
|
144
|
+
const isCurrent = () => !disposed && syncService === service;
|
|
131
145
|
try {
|
|
132
|
-
const result = await
|
|
133
|
-
|
|
146
|
+
const result = await service.syncAll();
|
|
147
|
+
if (isCurrent())
|
|
148
|
+
pendingCount = service.pendingCount;
|
|
134
149
|
return result;
|
|
135
150
|
}
|
|
136
151
|
catch (err) {
|
|
137
152
|
const errorMsg = err instanceof Error ? err.message : 'Sync failed';
|
|
138
|
-
|
|
153
|
+
if (isCurrent())
|
|
154
|
+
error = errorMsg;
|
|
139
155
|
return {
|
|
140
156
|
success: false,
|
|
141
157
|
uploaded: 0,
|
|
@@ -178,8 +194,10 @@ export function useDraftSync(options) {
|
|
|
178
194
|
if (!syncService) {
|
|
179
195
|
throw new Error('Sync service not initialized');
|
|
180
196
|
}
|
|
181
|
-
|
|
182
|
-
|
|
197
|
+
const service = syncService;
|
|
198
|
+
await service.forcePush(draftId);
|
|
199
|
+
if (syncService === service)
|
|
200
|
+
conflicts = service.getConflicts();
|
|
183
201
|
}
|
|
184
202
|
/**
|
|
185
203
|
* Force pull a draft
|
|
@@ -188,8 +206,10 @@ export function useDraftSync(options) {
|
|
|
188
206
|
if (!syncService) {
|
|
189
207
|
throw new Error('Sync service not initialized');
|
|
190
208
|
}
|
|
191
|
-
|
|
192
|
-
|
|
209
|
+
const service = syncService;
|
|
210
|
+
await service.forcePull(draftId);
|
|
211
|
+
if (syncService === service)
|
|
212
|
+
conflicts = service.getConflicts();
|
|
193
213
|
}
|
|
194
214
|
/**
|
|
195
215
|
* Resolve a conflict
|
|
@@ -198,8 +218,10 @@ export function useDraftSync(options) {
|
|
|
198
218
|
if (!syncService) {
|
|
199
219
|
throw new Error('Sync service not initialized');
|
|
200
220
|
}
|
|
201
|
-
|
|
202
|
-
|
|
221
|
+
const service = syncService;
|
|
222
|
+
await service.resolveConflict(draftId, resolution);
|
|
223
|
+
if (syncService === service)
|
|
224
|
+
conflicts = service.getConflicts();
|
|
203
225
|
}
|
|
204
226
|
/**
|
|
205
227
|
* Start auto-sync
|
|
@@ -219,16 +241,25 @@ export function useDraftSync(options) {
|
|
|
219
241
|
* Dispose the sync service
|
|
220
242
|
*/
|
|
221
243
|
function dispose() {
|
|
222
|
-
|
|
244
|
+
// The service stops its in-flight sync and drops these callbacks; the
|
|
245
|
+
// returned promise (lock released) is not needed here
|
|
246
|
+
void syncService?.dispose();
|
|
223
247
|
syncService = null;
|
|
248
|
+
isSyncing = false;
|
|
249
|
+
isAutoSyncActive = false;
|
|
224
250
|
}
|
|
225
|
-
// Initialize on mount
|
|
251
|
+
// Initialize on mount, clean up on destroy. untrack: initialization writes
|
|
252
|
+
// state this effect must not subscribe to.
|
|
226
253
|
$effect(() => {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
254
|
+
untrack(() => {
|
|
255
|
+
initSyncService().catch((err) => {
|
|
256
|
+
error = err instanceof Error ? err.message : 'Failed to initialize sync';
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
return () => {
|
|
260
|
+
disposed = true;
|
|
261
|
+
dispose();
|
|
262
|
+
};
|
|
232
263
|
});
|
|
233
264
|
return {
|
|
234
265
|
get isOnline() {
|
|
@@ -51,6 +51,12 @@ export function usePersistedForm(options) {
|
|
|
51
51
|
let lastSubmitTime = 0;
|
|
52
52
|
let submitInFlight = false;
|
|
53
53
|
let debounceTimer = null;
|
|
54
|
+
// Settles when the initial draft load finishes; autosaves wait for it
|
|
55
|
+
let loadPromise = Promise.resolve();
|
|
56
|
+
// Fields (and file refs) edited since mount, layered over a draft that
|
|
57
|
+
// finishes loading after the user started typing
|
|
58
|
+
let touched = {};
|
|
59
|
+
let touchedFileRefs = {};
|
|
54
60
|
// Multi-draft state
|
|
55
61
|
let currentDraftId = $state(initialDraftId ?? null);
|
|
56
62
|
let currentDraftMetadata = $state(null);
|
|
@@ -76,10 +82,10 @@ export function usePersistedForm(options) {
|
|
|
76
82
|
// Load current draft for this form
|
|
77
83
|
draft = await storage.draftManager.getCurrentDraft(storageKey);
|
|
78
84
|
}
|
|
79
|
-
//
|
|
80
|
-
if (draft
|
|
81
|
-
data = { ...JSON.parse(JSON.stringify(initialValues)), ...draft.data };
|
|
82
|
-
fileRefs = draft.fileRefs
|
|
85
|
+
// Edits made while the draft was loading stay on top of it
|
|
86
|
+
if (draft) {
|
|
87
|
+
data = { ...JSON.parse(JSON.stringify(initialValues)), ...draft.data, ...touched };
|
|
88
|
+
fileRefs = { ...draft.fileRefs, ...touchedFileRefs };
|
|
83
89
|
currentDraftId = draft.metadata.id;
|
|
84
90
|
currentDraftMetadata = draft.metadata;
|
|
85
91
|
draftRestored = true;
|
|
@@ -90,10 +96,10 @@ export function usePersistedForm(options) {
|
|
|
90
96
|
else {
|
|
91
97
|
// Legacy single-draft mode
|
|
92
98
|
const result = await storage.drafts.loadDraft(storageKey);
|
|
93
|
-
if (result.restored && result.draft
|
|
94
|
-
// Merge draft data with initial values
|
|
95
|
-
data = { ...JSON.parse(JSON.stringify(initialValues)), ...result.draft.data };
|
|
96
|
-
fileRefs = result.draft.fileRefs
|
|
99
|
+
if (result.restored && result.draft) {
|
|
100
|
+
// Merge draft data with initial values; edits made while loading win
|
|
101
|
+
data = { ...JSON.parse(JSON.stringify(initialValues)), ...result.draft.data, ...touched };
|
|
102
|
+
fileRefs = { ...result.draft.fileRefs, ...touchedFileRefs };
|
|
97
103
|
draftRestored = true;
|
|
98
104
|
onDraftRestored?.();
|
|
99
105
|
}
|
|
@@ -110,6 +116,9 @@ export function usePersistedForm(options) {
|
|
|
110
116
|
if (!isOfflineStorageInitialized() || !isDirty) {
|
|
111
117
|
return;
|
|
112
118
|
}
|
|
119
|
+
// Saving before the stored draft has loaded would create a second draft
|
|
120
|
+
// (or overwrite the stored one) instead of updating it
|
|
121
|
+
await loadPromise;
|
|
113
122
|
try {
|
|
114
123
|
const storage = getOfflineStorage();
|
|
115
124
|
// Snapshot the $state proxies: IndexedDB/OPFS structured cloning throws
|
|
@@ -122,9 +131,13 @@ export function usePersistedForm(options) {
|
|
|
122
131
|
}
|
|
123
132
|
if (multiDraft) {
|
|
124
133
|
// Multi-draft mode: Use DraftManagerService
|
|
134
|
+
// Expired or deleted meanwhile: save the edits as a new draft rather
|
|
135
|
+
// than silently dropping them
|
|
136
|
+
if (currentDraftId &&
|
|
137
|
+
!(await storage.draftManager.updateDraft(currentDraftId, dataToPersist, fileRefsToPersist))) {
|
|
138
|
+
currentDraftId = null;
|
|
139
|
+
}
|
|
125
140
|
if (currentDraftId) {
|
|
126
|
-
// Update existing draft
|
|
127
|
-
await storage.draftManager.updateDraft(currentDraftId, dataToPersist, fileRefsToPersist);
|
|
128
141
|
// Update metadata
|
|
129
142
|
const metadata = await storage.draftManager.getDraftMetadata(currentDraftId);
|
|
130
143
|
if (metadata) {
|
|
@@ -167,6 +180,18 @@ export function usePersistedForm(options) {
|
|
|
167
180
|
void saveDraft();
|
|
168
181
|
}, debounceMs);
|
|
169
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* Run a queued debounced save now instead of dropping it
|
|
185
|
+
*/
|
|
186
|
+
function flushPendingSave() {
|
|
187
|
+
if (debounceTimer) {
|
|
188
|
+
cancelPendingSave();
|
|
189
|
+
// Next microtask: during an effect teardown Svelte reads $state as it
|
|
190
|
+
// was before the effect's last run, so saving synchronously here would
|
|
191
|
+
// see isDirty === false and save nothing
|
|
192
|
+
void Promise.resolve().then(saveDraft);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
170
195
|
/**
|
|
171
196
|
* Cancel a queued debounced save
|
|
172
197
|
*/
|
|
@@ -181,6 +206,7 @@ export function usePersistedForm(options) {
|
|
|
181
206
|
*/
|
|
182
207
|
function setField(field, value) {
|
|
183
208
|
data[field] = value;
|
|
209
|
+
touched = { ...touched, [field]: value };
|
|
184
210
|
isDirty = true;
|
|
185
211
|
scheduleSaveDraft();
|
|
186
212
|
}
|
|
@@ -189,6 +215,7 @@ export function usePersistedForm(options) {
|
|
|
189
215
|
*/
|
|
190
216
|
function setFields(fields) {
|
|
191
217
|
Object.assign(data, fields);
|
|
218
|
+
touched = { ...touched, ...fields };
|
|
192
219
|
isDirty = true;
|
|
193
220
|
scheduleSaveDraft();
|
|
194
221
|
}
|
|
@@ -267,6 +294,8 @@ export function usePersistedForm(options) {
|
|
|
267
294
|
catch (err) {
|
|
268
295
|
globalError = err instanceof Error ? err.message : 'Submission failed';
|
|
269
296
|
lastSubmitTime = 0; // Reset cooldown on error
|
|
297
|
+
// The autosave was cancelled for the submit; keep the edits
|
|
298
|
+
void saveDraft();
|
|
270
299
|
throw err;
|
|
271
300
|
}
|
|
272
301
|
finally {
|
|
@@ -284,6 +313,8 @@ export function usePersistedForm(options) {
|
|
|
284
313
|
globalError = null;
|
|
285
314
|
isSubmitted = false;
|
|
286
315
|
isDirty = false;
|
|
316
|
+
touched = {};
|
|
317
|
+
touchedFileRefs = {};
|
|
287
318
|
draftRestored = false;
|
|
288
319
|
fileRefs = {};
|
|
289
320
|
void clearDraft();
|
|
@@ -316,20 +347,23 @@ export function usePersistedForm(options) {
|
|
|
316
347
|
}
|
|
317
348
|
try {
|
|
318
349
|
const storage = getOfflineStorage();
|
|
319
|
-
if (multiDraft
|
|
320
|
-
// Multi-draft mode:
|
|
321
|
-
|
|
322
|
-
currentDraftId
|
|
323
|
-
|
|
324
|
-
|
|
350
|
+
if (multiDraft) {
|
|
351
|
+
// Multi-draft mode: delete this draft and only its own files. Other
|
|
352
|
+
// drafts of the same form keep theirs, so no deleteFormFiles here.
|
|
353
|
+
if (currentDraftId) {
|
|
354
|
+
await storage.draftManager.deleteDraft(currentDraftId, true);
|
|
355
|
+
currentDraftId = null;
|
|
356
|
+
currentDraftMetadata = null;
|
|
357
|
+
onDraftChange?.(null);
|
|
358
|
+
}
|
|
325
359
|
}
|
|
326
360
|
else {
|
|
327
361
|
// Legacy single-draft mode
|
|
328
362
|
await storage.drafts.clearDraft(storageKey);
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
363
|
+
// Also clear associated files
|
|
364
|
+
for (const fieldName of fileFields) {
|
|
365
|
+
await storage.files.deleteFormFiles(storageKey, fieldName);
|
|
366
|
+
}
|
|
333
367
|
}
|
|
334
368
|
}
|
|
335
369
|
catch (err) {
|
|
@@ -347,6 +381,7 @@ export function usePersistedForm(options) {
|
|
|
347
381
|
*/
|
|
348
382
|
function updateFileRefs(fieldName, fileIds) {
|
|
349
383
|
fileRefs = { ...fileRefs, [fieldName]: fileIds };
|
|
384
|
+
touchedFileRefs = { ...touchedFileRefs, [fieldName]: fileIds };
|
|
350
385
|
isDirty = true;
|
|
351
386
|
scheduleSaveDraft();
|
|
352
387
|
}
|
|
@@ -362,6 +397,10 @@ export function usePersistedForm(options) {
|
|
|
362
397
|
for (const fieldName of fileFields) {
|
|
363
398
|
const ids = fileRefs[fieldName] || [];
|
|
364
399
|
const fileMap = await storage.files.getFilesAsFileObjects(ids);
|
|
400
|
+
const missing = ids.filter((id) => !fileMap.has(id));
|
|
401
|
+
if (missing.length > 0) {
|
|
402
|
+
console.warn(`[usePersistedForm] ${missing.length} file(s) for "${fieldName}" are missing from storage (expired or deleted)`, missing);
|
|
403
|
+
}
|
|
365
404
|
result[fieldName] = Array.from(fileMap.values());
|
|
366
405
|
}
|
|
367
406
|
return result;
|
|
@@ -411,6 +450,8 @@ export function usePersistedForm(options) {
|
|
|
411
450
|
currentDraftId = draft.metadata.id;
|
|
412
451
|
currentDraftMetadata = draft.metadata;
|
|
413
452
|
isDirty = false;
|
|
453
|
+
touched = {};
|
|
454
|
+
touchedFileRefs = {};
|
|
414
455
|
draftRestored = true;
|
|
415
456
|
// Set as current draft
|
|
416
457
|
await storage.draftManager.setCurrentDraft(storageKey, draftIdToLoad);
|
|
@@ -421,11 +462,18 @@ export function usePersistedForm(options) {
|
|
|
421
462
|
// Load draft on initialization. untrack: loadDraft reads currentDraftId
|
|
422
463
|
// (and isDirty), which the composable itself changes on autosave/clear;
|
|
423
464
|
// tracking them would reload and clobber in-progress edits.
|
|
465
|
+
// Destroying the component or leaving the page flushes a queued save
|
|
466
|
+
// rather than dropping the last edits.
|
|
424
467
|
$effect(() => {
|
|
425
468
|
untrack(() => {
|
|
426
|
-
|
|
469
|
+
loadPromise = loadDraft();
|
|
427
470
|
});
|
|
428
|
-
|
|
471
|
+
const onPageHide = () => flushPendingSave();
|
|
472
|
+
window.addEventListener('pagehide', onPageHide);
|
|
473
|
+
return () => {
|
|
474
|
+
window.removeEventListener('pagehide', onPageHide);
|
|
475
|
+
flushPendingSave();
|
|
476
|
+
};
|
|
429
477
|
});
|
|
430
478
|
return {
|
|
431
479
|
get data() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@classic-homes/offline-svelte",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Svelte bindings for offline persistence and caching",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"svelte": "./dist/index.js",
|
|
@@ -29,7 +29,9 @@
|
|
|
29
29
|
},
|
|
30
30
|
"sideEffects": false,
|
|
31
31
|
"files": [
|
|
32
|
-
"dist"
|
|
32
|
+
"dist",
|
|
33
|
+
"!dist/__tests__",
|
|
34
|
+
"!dist/**/*.test.*"
|
|
33
35
|
],
|
|
34
36
|
"scripts": {
|
|
35
37
|
"build": "svelte-package -i src",
|
|
@@ -61,11 +63,6 @@
|
|
|
61
63
|
"svelte": "^5.0.0",
|
|
62
64
|
"zod": "^3.23.0"
|
|
63
65
|
},
|
|
64
|
-
"peerDependenciesMeta": {
|
|
65
|
-
"zod": {
|
|
66
|
-
"optional": true
|
|
67
|
-
}
|
|
68
|
-
},
|
|
69
66
|
"dependencies": {
|
|
70
67
|
"@classic-homes/offline-core": "*"
|
|
71
68
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import 'fake-indexeddb/auto';
|
package/dist/__tests__/setup.js
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Vitest setup file for Svelte tests
|
|
3
|
-
*/
|
|
4
|
-
import { vi, beforeEach } from 'vitest';
|
|
5
|
-
import 'fake-indexeddb/auto';
|
|
6
|
-
// Mock URL.createObjectURL and revokeObjectURL
|
|
7
|
-
global.URL.createObjectURL = vi.fn((blob) => `blob:mock-${blob.size}`);
|
|
8
|
-
global.URL.revokeObjectURL = vi.fn();
|
|
9
|
-
// Mock navigator.storage
|
|
10
|
-
Object.defineProperty(navigator, 'storage', {
|
|
11
|
-
value: {
|
|
12
|
-
estimate: vi.fn().mockResolvedValue({
|
|
13
|
-
quota: 1000000000,
|
|
14
|
-
usage: 0,
|
|
15
|
-
}),
|
|
16
|
-
},
|
|
17
|
-
writable: true,
|
|
18
|
-
});
|
|
19
|
-
// Mock localStorage for tests
|
|
20
|
-
const localStorageStore = {};
|
|
21
|
-
const localStorageMock = {
|
|
22
|
-
getItem: vi.fn((key) => localStorageStore[key] ?? null),
|
|
23
|
-
setItem: vi.fn((key, value) => {
|
|
24
|
-
localStorageStore[key] = value;
|
|
25
|
-
}),
|
|
26
|
-
removeItem: vi.fn((key) => {
|
|
27
|
-
delete localStorageStore[key];
|
|
28
|
-
}),
|
|
29
|
-
clear: vi.fn(() => {
|
|
30
|
-
for (const key of Object.keys(localStorageStore)) {
|
|
31
|
-
delete localStorageStore[key];
|
|
32
|
-
}
|
|
33
|
-
}),
|
|
34
|
-
get length() {
|
|
35
|
-
return Object.keys(localStorageStore).length;
|
|
36
|
-
},
|
|
37
|
-
key: vi.fn((index) => Object.keys(localStorageStore)[index] ?? null),
|
|
38
|
-
};
|
|
39
|
-
Object.defineProperty(globalThis, 'localStorage', {
|
|
40
|
-
value: localStorageMock,
|
|
41
|
-
writable: true,
|
|
42
|
-
});
|
|
43
|
-
beforeEach(() => {
|
|
44
|
-
for (const key of Object.keys(localStorageStore)) {
|
|
45
|
-
delete localStorageStore[key];
|
|
46
|
-
}
|
|
47
|
-
vi.clearAllMocks();
|
|
48
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests for useFileStorage composable
|
|
3
|
-
*
|
|
4
|
-
* Note: Svelte 5 runes ($state, $effect) require the Svelte compiler context.
|
|
5
|
-
* These tests focus on the FileStorageService used by the composable.
|
|
6
|
-
*/
|
|
7
|
-
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
|
8
|
-
import { initOfflineStorage } from '@classic-homes/offline-core';
|
|
9
|
-
describe('FileStorageService integration (used by useFileStorage)', () => {
|
|
10
|
-
let storage;
|
|
11
|
-
beforeEach(async () => {
|
|
12
|
-
storage = await initOfflineStorage({
|
|
13
|
-
preferredAdapters: ['memory'],
|
|
14
|
-
});
|
|
15
|
-
});
|
|
16
|
-
afterEach(async () => {
|
|
17
|
-
await storage.cleanup.runCleanup();
|
|
18
|
-
await storage.dispose();
|
|
19
|
-
});
|
|
20
|
-
describe('file validation', () => {
|
|
21
|
-
it('should validate file size', () => {
|
|
22
|
-
const file = new File(['x'.repeat(2000)], 'large.txt', { type: 'text/plain' });
|
|
23
|
-
const errors = storage.files.validateFiles([file], { maxSizeBytes: 1000 });
|
|
24
|
-
expect(errors).toHaveLength(1);
|
|
25
|
-
expect(errors[0].code).toBe('TOO_LARGE');
|
|
26
|
-
});
|
|
27
|
-
it('should validate file count', () => {
|
|
28
|
-
const files = [
|
|
29
|
-
new File(['1'], 'file1.txt'),
|
|
30
|
-
new File(['2'], 'file2.txt'),
|
|
31
|
-
new File(['3'], 'file3.txt'),
|
|
32
|
-
];
|
|
33
|
-
const errors = storage.files.validateFiles(files, { maxFiles: 2 });
|
|
34
|
-
expect(errors).toHaveLength(1);
|
|
35
|
-
expect(errors[0].code).toBe('TOO_MANY_FILES');
|
|
36
|
-
});
|
|
37
|
-
it('should validate file type', () => {
|
|
38
|
-
const file = new File(['data'], 'doc.pdf', { type: 'application/pdf' });
|
|
39
|
-
const errors = storage.files.validateFiles([file], { acceptedTypes: ['image/*'] });
|
|
40
|
-
expect(errors).toHaveLength(1);
|
|
41
|
-
expect(errors[0].code).toBe('INVALID_TYPE');
|
|
42
|
-
});
|
|
43
|
-
it('should accept wildcard MIME types', () => {
|
|
44
|
-
const imageFile = new File(['data'], 'img.png', { type: 'image/png' });
|
|
45
|
-
const errors = storage.files.validateFiles([imageFile], { acceptedTypes: ['image/*'] });
|
|
46
|
-
expect(errors).toHaveLength(0);
|
|
47
|
-
});
|
|
48
|
-
});
|
|
49
|
-
describe('file storage', () => {
|
|
50
|
-
it('should store and retrieve files', async () => {
|
|
51
|
-
const file = new File(['test content'], 'test.txt', { type: 'text/plain' });
|
|
52
|
-
const stored = await storage.files.storeFile(file, {
|
|
53
|
-
formKey: 'form1',
|
|
54
|
-
fieldName: 'attachment',
|
|
55
|
-
});
|
|
56
|
-
expect(stored.id).toMatch(/^file:/);
|
|
57
|
-
expect(stored.filename).toBe('test.txt');
|
|
58
|
-
expect(stored.formKey).toBe('form1');
|
|
59
|
-
expect(stored.fieldName).toBe('attachment');
|
|
60
|
-
const retrieved = await storage.files.getFile(stored.id);
|
|
61
|
-
expect(retrieved).not.toBeNull();
|
|
62
|
-
expect(retrieved.filename).toBe('test.txt');
|
|
63
|
-
});
|
|
64
|
-
it('should store multiple files', async () => {
|
|
65
|
-
const files = [new File(['1'], 'file1.txt'), new File(['2'], 'file2.txt')];
|
|
66
|
-
const stored = await storage.files.storeFiles(files, {
|
|
67
|
-
formKey: 'form1',
|
|
68
|
-
fieldName: 'attachments',
|
|
69
|
-
});
|
|
70
|
-
expect(stored).toHaveLength(2);
|
|
71
|
-
});
|
|
72
|
-
it('should filter files by formKey and fieldName', async () => {
|
|
73
|
-
await storage.files.storeFile(new File(['1'], 'f1.txt'), {
|
|
74
|
-
formKey: 'form1',
|
|
75
|
-
fieldName: 'docs',
|
|
76
|
-
});
|
|
77
|
-
await storage.files.storeFile(new File(['2'], 'f2.txt'), {
|
|
78
|
-
formKey: 'form1',
|
|
79
|
-
fieldName: 'photos',
|
|
80
|
-
});
|
|
81
|
-
await storage.files.storeFile(new File(['3'], 'f3.txt'), {
|
|
82
|
-
formKey: 'form2',
|
|
83
|
-
fieldName: 'docs',
|
|
84
|
-
});
|
|
85
|
-
const form1Files = await storage.files.getFiles({ formKey: 'form1' });
|
|
86
|
-
expect(form1Files).toHaveLength(2);
|
|
87
|
-
const docsFiles = await storage.files.getFiles({ formKey: 'form1', fieldName: 'docs' });
|
|
88
|
-
expect(docsFiles).toHaveLength(1);
|
|
89
|
-
expect(docsFiles[0].fieldName).toBe('docs');
|
|
90
|
-
});
|
|
91
|
-
it('should delete files', async () => {
|
|
92
|
-
const stored = await storage.files.storeFile(new File(['data'], 'test.txt'), {
|
|
93
|
-
formKey: 'form1',
|
|
94
|
-
fieldName: 'doc',
|
|
95
|
-
});
|
|
96
|
-
const deleted = await storage.files.deleteFile(stored.id);
|
|
97
|
-
expect(deleted).toBe(true);
|
|
98
|
-
const retrieved = await storage.files.getFile(stored.id);
|
|
99
|
-
expect(retrieved).toBeNull();
|
|
100
|
-
});
|
|
101
|
-
it('should delete all files for a form', async () => {
|
|
102
|
-
await storage.files.storeFile(new File(['1'], 'f1.txt'), {
|
|
103
|
-
formKey: 'form1',
|
|
104
|
-
fieldName: 'docs',
|
|
105
|
-
});
|
|
106
|
-
await storage.files.storeFile(new File(['2'], 'f2.txt'), {
|
|
107
|
-
formKey: 'form1',
|
|
108
|
-
fieldName: 'photos',
|
|
109
|
-
});
|
|
110
|
-
await storage.files.storeFile(new File(['3'], 'f3.txt'), {
|
|
111
|
-
formKey: 'form2',
|
|
112
|
-
fieldName: 'docs',
|
|
113
|
-
});
|
|
114
|
-
const result = await storage.files.deleteFormFiles('form1');
|
|
115
|
-
expect(result.deletedCount).toBe(2);
|
|
116
|
-
const remaining = await storage.files.getFiles();
|
|
117
|
-
expect(remaining).toHaveLength(1);
|
|
118
|
-
expect(remaining[0].formKey).toBe('form2');
|
|
119
|
-
});
|
|
120
|
-
it('should generate preview URLs for images', async () => {
|
|
121
|
-
const imageFile = new File(['fake image'], 'photo.png', { type: 'image/png' });
|
|
122
|
-
const stored = await storage.files.storeFile(imageFile, {
|
|
123
|
-
formKey: 'form1',
|
|
124
|
-
fieldName: 'photo',
|
|
125
|
-
});
|
|
126
|
-
const retrieved = await storage.files.getFile(stored.id, true);
|
|
127
|
-
expect(retrieved.previewUrl).toBeDefined();
|
|
128
|
-
expect(retrieved.previewUrl).toMatch(/^blob:/);
|
|
129
|
-
});
|
|
130
|
-
it('should convert files back to File objects for submission', async () => {
|
|
131
|
-
const stored = await storage.files.storeFile(new File(['content'], 'test.txt', { type: 'text/plain' }), { formKey: 'form1', fieldName: 'doc' });
|
|
132
|
-
const fileMap = await storage.files.getFilesAsFileObjects([stored.id]);
|
|
133
|
-
expect(fileMap.size).toBe(1);
|
|
134
|
-
const file = fileMap.get(stored.id);
|
|
135
|
-
expect(file.name).toBe('test.txt');
|
|
136
|
-
expect(file.type).toBe('text/plain');
|
|
137
|
-
});
|
|
138
|
-
});
|
|
139
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests for useOfflineCache composable
|
|
3
|
-
*
|
|
4
|
-
* Note: Svelte 5 runes ($state, $effect) require the Svelte compiler context.
|
|
5
|
-
* These tests focus on the utility functions and basic functionality.
|
|
6
|
-
*/
|
|
7
|
-
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
8
|
-
import { initOfflineStorage } from '@classic-homes/offline-core';
|
|
9
|
-
import { invalidateCacheByTag, invalidateAllCache } from '../useOfflineCache.svelte.js';
|
|
10
|
-
describe('useOfflineCache utilities', () => {
|
|
11
|
-
let storage;
|
|
12
|
-
beforeEach(async () => {
|
|
13
|
-
storage = await initOfflineStorage({
|
|
14
|
-
preferredAdapters: ['memory'],
|
|
15
|
-
});
|
|
16
|
-
});
|
|
17
|
-
afterEach(async () => {
|
|
18
|
-
await storage.cleanup.runCleanup();
|
|
19
|
-
await storage.dispose();
|
|
20
|
-
});
|
|
21
|
-
describe('invalidateCacheByTag', () => {
|
|
22
|
-
it('should invalidate entries by tag', async () => {
|
|
23
|
-
await storage.cache.set('k1', 'v1', { tags: ['user'] });
|
|
24
|
-
await storage.cache.set('k2', 'v2', { tags: ['user'] });
|
|
25
|
-
await storage.cache.set('k3', 'v3', { tags: ['other'] });
|
|
26
|
-
const deleted = await invalidateCacheByTag('user');
|
|
27
|
-
expect(deleted).toBe(2);
|
|
28
|
-
// Verify entries are gone
|
|
29
|
-
const result1 = await storage.cache.get('k1');
|
|
30
|
-
const result2 = await storage.cache.get('k2');
|
|
31
|
-
const result3 = await storage.cache.get('k3');
|
|
32
|
-
expect(result1.hit).toBe(false);
|
|
33
|
-
expect(result2.hit).toBe(false);
|
|
34
|
-
expect(result3.hit).toBe(true);
|
|
35
|
-
});
|
|
36
|
-
it('should return 0 when no entries match', async () => {
|
|
37
|
-
await storage.cache.set('k1', 'v1', { tags: ['other'] });
|
|
38
|
-
const deleted = await invalidateCacheByTag('nonexistent');
|
|
39
|
-
expect(deleted).toBe(0);
|
|
40
|
-
});
|
|
41
|
-
});
|
|
42
|
-
describe('invalidateAllCache', () => {
|
|
43
|
-
it('should invalidate all cache entries', async () => {
|
|
44
|
-
await storage.cache.set('k1', 'v1');
|
|
45
|
-
await storage.cache.set('k2', 'v2');
|
|
46
|
-
await storage.cache.set('k3', 'v3');
|
|
47
|
-
const deleted = await invalidateAllCache();
|
|
48
|
-
expect(deleted).toBe(3);
|
|
49
|
-
// Verify all entries are gone
|
|
50
|
-
const keys = await storage.cache.keys();
|
|
51
|
-
expect(keys).toHaveLength(0);
|
|
52
|
-
});
|
|
53
|
-
it('should return 0 when cache is empty', async () => {
|
|
54
|
-
const deleted = await invalidateAllCache();
|
|
55
|
-
expect(deleted).toBe(0);
|
|
56
|
-
});
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
describe('CacheService integration (used by useOfflineCache)', () => {
|
|
60
|
-
let storage;
|
|
61
|
-
beforeEach(async () => {
|
|
62
|
-
storage = await initOfflineStorage({
|
|
63
|
-
preferredAdapters: ['memory'],
|
|
64
|
-
});
|
|
65
|
-
});
|
|
66
|
-
afterEach(async () => {
|
|
67
|
-
await storage.cleanup.runCleanup();
|
|
68
|
-
await storage.dispose();
|
|
69
|
-
});
|
|
70
|
-
it('should support get and set operations', async () => {
|
|
71
|
-
await storage.cache.set('test-key', { name: 'test', value: 42 }, { ttl: 10000 });
|
|
72
|
-
const result = await storage.cache.get('test-key');
|
|
73
|
-
expect(result.hit).toBe(true);
|
|
74
|
-
expect(result.value).toEqual({ name: 'test', value: 42 });
|
|
75
|
-
});
|
|
76
|
-
it('should support getOrSet with fetcher', async () => {
|
|
77
|
-
const fetcher = vi.fn().mockResolvedValue('fetched-value');
|
|
78
|
-
const value = await storage.cache.getOrSet('key', fetcher, { ttl: 10000 });
|
|
79
|
-
expect(value).toBe('fetched-value');
|
|
80
|
-
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
81
|
-
// Second call should use cache
|
|
82
|
-
const value2 = await storage.cache.getOrSet('key', fetcher);
|
|
83
|
-
expect(value2).toBe('fetched-value');
|
|
84
|
-
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
85
|
-
});
|
|
86
|
-
it('should support invalidation', async () => {
|
|
87
|
-
await storage.cache.set('key', 'value');
|
|
88
|
-
await storage.cache.invalidate('key');
|
|
89
|
-
const result = await storage.cache.get('key');
|
|
90
|
-
expect(result.hit).toBe(false);
|
|
91
|
-
});
|
|
92
|
-
it('should track staleness', async () => {
|
|
93
|
-
vi.useFakeTimers();
|
|
94
|
-
const now = Date.now();
|
|
95
|
-
vi.setSystemTime(now);
|
|
96
|
-
await storage.cache.set('key', 'value', { ttl: 1000 });
|
|
97
|
-
// Fresh
|
|
98
|
-
let result = await storage.cache.get('key');
|
|
99
|
-
expect(result.hit).toBe(true);
|
|
100
|
-
expect(result.stale).toBe(false);
|
|
101
|
-
// Expired (stale)
|
|
102
|
-
vi.setSystemTime(now + 2000);
|
|
103
|
-
result = await storage.cache.get('key');
|
|
104
|
-
expect(result.hit).toBe(true);
|
|
105
|
-
expect(result.stale).toBe(true);
|
|
106
|
-
vi.useRealTimers();
|
|
107
|
-
});
|
|
108
|
-
it('should support tags for bulk invalidation', async () => {
|
|
109
|
-
await storage.cache.set('user:1', { name: 'John' }, { tags: ['user', 'active'] });
|
|
110
|
-
await storage.cache.set('user:2', { name: 'Jane' }, { tags: ['user', 'inactive'] });
|
|
111
|
-
await storage.cache.set('post:1', { title: 'Hello' }, { tags: ['post'] });
|
|
112
|
-
const deleted = await storage.cache.invalidateByTag('user');
|
|
113
|
-
expect(deleted).toBe(2);
|
|
114
|
-
const userResult = await storage.cache.get('user:1');
|
|
115
|
-
expect(userResult.hit).toBe(false);
|
|
116
|
-
const postResult = await storage.cache.get('post:1');
|
|
117
|
-
expect(postResult.hit).toBe(true);
|
|
118
|
-
});
|
|
119
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests for usePersistedForm composable
|
|
3
|
-
*
|
|
4
|
-
* Note: Svelte 5 runes ($state, $effect) require the Svelte compiler context.
|
|
5
|
-
* These tests focus on the DraftStorageService used by the composable.
|
|
6
|
-
*/
|
|
7
|
-
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
8
|
-
import { initOfflineStorage } from '@classic-homes/offline-core';
|
|
9
|
-
describe('DraftStorageService integration (used by usePersistedForm)', () => {
|
|
10
|
-
let storage;
|
|
11
|
-
beforeEach(async () => {
|
|
12
|
-
storage = await initOfflineStorage({
|
|
13
|
-
preferredAdapters: ['memory'],
|
|
14
|
-
});
|
|
15
|
-
});
|
|
16
|
-
afterEach(async () => {
|
|
17
|
-
await storage.cleanup.runCleanup();
|
|
18
|
-
await storage.dispose();
|
|
19
|
-
});
|
|
20
|
-
describe('draft persistence', () => {
|
|
21
|
-
it('should save and load drafts', async () => {
|
|
22
|
-
const formData = { name: 'John', email: 'john@example.com' };
|
|
23
|
-
await storage.drafts.saveDraft('contact-form', formData);
|
|
24
|
-
const result = await storage.drafts.loadDraft('contact-form');
|
|
25
|
-
expect(result.restored).toBe(true);
|
|
26
|
-
expect(result.draft).not.toBeNull();
|
|
27
|
-
expect(result.draft.data).toEqual(formData);
|
|
28
|
-
});
|
|
29
|
-
it('should return empty result for non-existent draft', async () => {
|
|
30
|
-
const result = await storage.drafts.loadDraft('non-existent');
|
|
31
|
-
expect(result.restored).toBe(false);
|
|
32
|
-
expect(result.draft).toBeNull();
|
|
33
|
-
});
|
|
34
|
-
it('should exclude specified fields', async () => {
|
|
35
|
-
const formData = {
|
|
36
|
-
name: 'John',
|
|
37
|
-
password: 'secret123',
|
|
38
|
-
confirmPassword: 'secret123',
|
|
39
|
-
};
|
|
40
|
-
await storage.drafts.saveDraft('signup', formData, {}, {
|
|
41
|
-
excludeFields: ['password', 'confirmPassword'],
|
|
42
|
-
});
|
|
43
|
-
const result = await storage.drafts.loadDraft('signup');
|
|
44
|
-
expect(result.draft.data.name).toBe('John');
|
|
45
|
-
expect(result.draft.data.password).toBeUndefined();
|
|
46
|
-
expect(result.draft.data.confirmPassword).toBeUndefined();
|
|
47
|
-
});
|
|
48
|
-
it('should save draft with file references', async () => {
|
|
49
|
-
const formData = { title: 'Document' };
|
|
50
|
-
const fileRefs = {
|
|
51
|
-
attachments: ['file:1', 'file:2'],
|
|
52
|
-
photo: ['file:3'],
|
|
53
|
-
};
|
|
54
|
-
await storage.drafts.saveDraft('upload-form', formData, fileRefs);
|
|
55
|
-
const result = await storage.drafts.loadDraft('upload-form');
|
|
56
|
-
expect(result.draft.fileRefs).toEqual(fileRefs);
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
describe('draft clearing', () => {
|
|
60
|
-
it('should clear a draft', async () => {
|
|
61
|
-
await storage.drafts.saveDraft('form1', { value: 1 });
|
|
62
|
-
await storage.drafts.clearDraft('form1');
|
|
63
|
-
const result = await storage.drafts.loadDraft('form1');
|
|
64
|
-
expect(result.draft).toBeNull();
|
|
65
|
-
});
|
|
66
|
-
it('should clear all drafts', async () => {
|
|
67
|
-
await storage.drafts.saveDraft('form1', { v: 1 });
|
|
68
|
-
await storage.drafts.saveDraft('form2', { v: 2 });
|
|
69
|
-
const deleted = await storage.drafts.clearAllDrafts();
|
|
70
|
-
expect(deleted).toBe(2);
|
|
71
|
-
expect(await storage.drafts.hasDraft('form1')).toBe(false);
|
|
72
|
-
expect(await storage.drafts.hasDraft('form2')).toBe(false);
|
|
73
|
-
});
|
|
74
|
-
});
|
|
75
|
-
describe('draft existence check', () => {
|
|
76
|
-
it('should return true for existing draft', async () => {
|
|
77
|
-
await storage.drafts.saveDraft('form1', { value: 1 });
|
|
78
|
-
expect(await storage.drafts.hasDraft('form1')).toBe(true);
|
|
79
|
-
});
|
|
80
|
-
it('should return false for non-existent draft', async () => {
|
|
81
|
-
expect(await storage.drafts.hasDraft('non-existent')).toBe(false);
|
|
82
|
-
});
|
|
83
|
-
});
|
|
84
|
-
describe('draft listing', () => {
|
|
85
|
-
it('should list all draft form keys', async () => {
|
|
86
|
-
await storage.drafts.saveDraft('form1', { v: 1 });
|
|
87
|
-
await storage.drafts.saveDraft('form2', { v: 2 });
|
|
88
|
-
await storage.drafts.saveDraft('form3', { v: 3 });
|
|
89
|
-
const keys = await storage.drafts.listDraftFormKeys();
|
|
90
|
-
expect(keys).toHaveLength(3);
|
|
91
|
-
expect(keys).toContain('form1');
|
|
92
|
-
expect(keys).toContain('form2');
|
|
93
|
-
expect(keys).toContain('form3');
|
|
94
|
-
});
|
|
95
|
-
});
|
|
96
|
-
describe('draft info', () => {
|
|
97
|
-
it('should return draft info for existing draft', async () => {
|
|
98
|
-
vi.useFakeTimers();
|
|
99
|
-
const now = Date.now();
|
|
100
|
-
vi.setSystemTime(now);
|
|
101
|
-
await storage.drafts.saveDraft('form1', { value: 1 }, { field1: ['file:1'] }, { expirationMs: 10000 });
|
|
102
|
-
const info = await storage.drafts.getDraftInfo('form1');
|
|
103
|
-
expect(info.exists).toBe(true);
|
|
104
|
-
expect(info.timestamp).toBe(now);
|
|
105
|
-
expect(info.expiresAt).toBe(now + 10000);
|
|
106
|
-
expect(info.hasFiles).toBe(true);
|
|
107
|
-
vi.useRealTimers();
|
|
108
|
-
});
|
|
109
|
-
it('should return hasFiles false when no files', async () => {
|
|
110
|
-
await storage.drafts.saveDraft('form1', { value: 1 });
|
|
111
|
-
const info = await storage.drafts.getDraftInfo('form1');
|
|
112
|
-
expect(info.hasFiles).toBe(false);
|
|
113
|
-
});
|
|
114
|
-
});
|
|
115
|
-
describe('draft merging', () => {
|
|
116
|
-
it('should merge data into existing draft', async () => {
|
|
117
|
-
await storage.drafts.saveDraft('form1', { name: 'John', email: 'old@example.com' });
|
|
118
|
-
await storage.drafts.mergeDraft('form1', { email: 'new@example.com', phone: '123' });
|
|
119
|
-
const result = await storage.drafts.loadDraft('form1');
|
|
120
|
-
expect(result.draft.data).toEqual({
|
|
121
|
-
name: 'John',
|
|
122
|
-
email: 'new@example.com',
|
|
123
|
-
phone: '123',
|
|
124
|
-
});
|
|
125
|
-
});
|
|
126
|
-
it('should preserve file references when merging', async () => {
|
|
127
|
-
await storage.drafts.saveDraft('form1', { name: 'John' }, { docs: ['file:1'] });
|
|
128
|
-
await storage.drafts.mergeDraft('form1', { email: 'john@example.com' });
|
|
129
|
-
const result = await storage.drafts.loadDraft('form1');
|
|
130
|
-
expect(result.draft.fileRefs.docs).toEqual(['file:1']);
|
|
131
|
-
});
|
|
132
|
-
});
|
|
133
|
-
describe('file reference updates', () => {
|
|
134
|
-
it('should update file references', async () => {
|
|
135
|
-
await storage.drafts.saveDraft('form1', { title: 'Doc' }, { files: ['file:1'] });
|
|
136
|
-
const updated = await storage.drafts.updateFileRefs('form1', 'files', [
|
|
137
|
-
'file:1',
|
|
138
|
-
'file:2',
|
|
139
|
-
'file:3',
|
|
140
|
-
]);
|
|
141
|
-
expect(updated).toBe(true);
|
|
142
|
-
const result = await storage.drafts.loadDraft('form1');
|
|
143
|
-
expect(result.draft.fileRefs.files).toEqual(['file:1', 'file:2', 'file:3']);
|
|
144
|
-
});
|
|
145
|
-
it('should return false when draft does not exist', async () => {
|
|
146
|
-
const updated = await storage.drafts.updateFileRefs('non-existent', 'files', ['file:1']);
|
|
147
|
-
expect(updated).toBe(false);
|
|
148
|
-
});
|
|
149
|
-
});
|
|
150
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests that run the usePersistedForm composable itself (runes compiled via
|
|
3
|
-
* the .svelte.test.ts suffix).
|
|
4
|
-
*/
|
|
5
|
-
import { describe, it, expect, afterEach, vi } from 'vitest';
|
|
6
|
-
import { flushSync } from 'svelte';
|
|
7
|
-
import { z } from 'zod';
|
|
8
|
-
import { initOfflineStorage, resetOfflineStorage, } from '@classic-homes/offline-core';
|
|
9
|
-
import { usePersistedForm } from '../usePersistedForm.svelte.js';
|
|
10
|
-
const schema = z.object({ name: z.string(), tags: z.array(z.string()) });
|
|
11
|
-
const DEBOUNCE_MS = 10;
|
|
12
|
-
function mount(options = {}) {
|
|
13
|
-
let form;
|
|
14
|
-
const destroy = $effect.root(() => {
|
|
15
|
-
form = usePersistedForm({
|
|
16
|
-
schema,
|
|
17
|
-
initialValues: { name: '', tags: [] },
|
|
18
|
-
storageKey: 'runes-form',
|
|
19
|
-
debounceMs: DEBOUNCE_MS,
|
|
20
|
-
submitCooldownMs: 0,
|
|
21
|
-
onSubmit: async () => { },
|
|
22
|
-
...options,
|
|
23
|
-
});
|
|
24
|
-
});
|
|
25
|
-
flushSync();
|
|
26
|
-
return { form, destroy };
|
|
27
|
-
}
|
|
28
|
-
describe('usePersistedForm (Svelte)', () => {
|
|
29
|
-
let storage;
|
|
30
|
-
let destroy;
|
|
31
|
-
afterEach(async () => {
|
|
32
|
-
destroy?.();
|
|
33
|
-
destroy = undefined;
|
|
34
|
-
await resetOfflineStorage();
|
|
35
|
-
});
|
|
36
|
-
it('persists drafts through IndexedDB (no $state proxies reach structured clone)', async () => {
|
|
37
|
-
storage = await initOfflineStorage({ preferredAdapters: ['indexeddb'] });
|
|
38
|
-
const warn = vi.spyOn(console, 'warn');
|
|
39
|
-
const mounted = mount();
|
|
40
|
-
destroy = mounted.destroy;
|
|
41
|
-
mounted.form.setField('tags', ['a', 'b']);
|
|
42
|
-
mounted.form.updateFileRefs('docs', ['file:1']);
|
|
43
|
-
await vi.waitFor(async () => {
|
|
44
|
-
const result = await storage.drafts.loadDraft('runes-form');
|
|
45
|
-
expect(result.draft?.data).toEqual({ name: '', tags: ['a', 'b'] });
|
|
46
|
-
expect(result.draft?.fileRefs).toEqual({ docs: ['file:1'] });
|
|
47
|
-
});
|
|
48
|
-
expect(warn).not.toHaveBeenCalledWith('Failed to save form draft:', expect.anything());
|
|
49
|
-
warn.mockRestore();
|
|
50
|
-
});
|
|
51
|
-
it('does not load another draft into the form after submit clears the current one', async () => {
|
|
52
|
-
storage = await initOfflineStorage({ preferredAdapters: ['memory'] });
|
|
53
|
-
await storage.draftManager.createDraft('runes-form', {
|
|
54
|
-
initialData: { name: 'older', tags: [] },
|
|
55
|
-
});
|
|
56
|
-
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
57
|
-
await storage.draftManager.createDraft('runes-form', {
|
|
58
|
-
initialData: { name: 'newest', tags: [] },
|
|
59
|
-
});
|
|
60
|
-
const mounted = mount({ multiDraft: true });
|
|
61
|
-
destroy = mounted.destroy;
|
|
62
|
-
const { form } = mounted;
|
|
63
|
-
await vi.waitFor(() => expect(form.data.name).toBe('newest'));
|
|
64
|
-
form.setField('name', 'submitted');
|
|
65
|
-
await form.handleSubmit();
|
|
66
|
-
flushSync();
|
|
67
|
-
await new Promise((resolve) => setTimeout(resolve, DEBOUNCE_MS * 3));
|
|
68
|
-
expect(form.currentDraftId).toBeNull();
|
|
69
|
-
expect(form.data.name).toBe('submitted');
|
|
70
|
-
const remaining = await storage.draftManager.listDrafts({ formKey: 'runes-form' });
|
|
71
|
-
expect(remaining.map((d) => d.name)).toHaveLength(1);
|
|
72
|
-
});
|
|
73
|
-
it('ignores a second submit and drops the queued autosave', async () => {
|
|
74
|
-
storage = await initOfflineStorage({ preferredAdapters: ['memory'] });
|
|
75
|
-
let release;
|
|
76
|
-
const onSubmit = vi.fn(() => new Promise((resolve) => (release = resolve)));
|
|
77
|
-
const mounted = mount({ onSubmit });
|
|
78
|
-
destroy = mounted.destroy;
|
|
79
|
-
const { form } = mounted;
|
|
80
|
-
form.setField('name', 'x');
|
|
81
|
-
const first = form.handleSubmit();
|
|
82
|
-
await form.handleSubmit();
|
|
83
|
-
await vi.waitFor(() => expect(onSubmit).toHaveBeenCalled());
|
|
84
|
-
release();
|
|
85
|
-
await first;
|
|
86
|
-
await new Promise((resolve) => setTimeout(resolve, DEBOUNCE_MS * 3));
|
|
87
|
-
expect(onSubmit).toHaveBeenCalledTimes(1);
|
|
88
|
-
expect((await storage.drafts.loadDraft('runes-form')).draft).toBeNull();
|
|
89
|
-
});
|
|
90
|
-
});
|