@classic-homes/offline-react 0.1.4 → 0.2.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/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { FileConstraints, FileValidationError, PersistedFile, DraftMetadata, CreateDraftOptions, StoredDraftV2, SyncAdapter, SyncResult, DraftConflict, ConflictResolution } from '@classic-homes/offline-core';
2
- export { ConflictResolution, CreateDraftOptions, DraftConflict, DraftMetadata, DraftSyncStatus, ListDraftsOptions, OfflineStorage, OfflineStorageOptions, StoredDraftV2, SyncAdapter, SyncConfig, SyncResult, getOfflineStorage, getOfflineStorageOrNull, initOfflineStorage, invalidateAllCache, invalidateCacheByTag, isOfflineStorageInitialized } from '@classic-homes/offline-core';
2
+ export { ConflictResolution, CreateDraftOptions, DraftConflict, DraftMetadata, DraftPayload, DraftSyncStatus, ListDraftsOptions, OfflineStorage, OfflineStorageOptions, RemoteDraft, StoredDraftV2, SyncAdapter, SyncConfig, SyncResult, getOfflineStorage, getOfflineStorageOrNull, initOfflineStorage, invalidateAllCache, invalidateCacheByTag, isOfflineStorageInitialized } from '@classic-homes/offline-core';
3
3
  import { z } from 'zod';
4
4
 
5
5
  /**
package/dist/index.js CHANGED
@@ -189,67 +189,100 @@ function usePersistedForm(options) {
189
189
  const [currentDraftId, setCurrentDraftId] = useState(initialDraftId ?? null);
190
190
  const [currentDraftMetadata, setCurrentDraftMetadata] = useState(null);
191
191
  const lastSubmitTimeRef = useRef(0);
192
+ const submittingRef = useRef(false);
192
193
  const debounceTimerRef = useRef(null);
194
+ const loadPromiseRef = useRef(Promise.resolve());
195
+ const touchedRef = useRef({});
196
+ const touchedFileRefsRef = useRef({});
193
197
  const originalValuesRef = useRef(JSON.parse(JSON.stringify(initialValues)));
198
+ const dataRef = useRef(data);
199
+ dataRef.current = data;
200
+ const fileRefsRef = useRef(fileRefs);
201
+ fileRefsRef.current = fileRefs;
202
+ const isDirtyRef = useRef(isDirty);
203
+ isDirtyRef.current = isDirty;
204
+ const currentDraftIdRef = useRef(currentDraftId);
205
+ currentDraftIdRef.current = currentDraftId;
206
+ const optionsRef = useRef(options);
207
+ optionsRef.current = options;
208
+ const cancelPendingSave = useCallback(() => {
209
+ if (debounceTimerRef.current) {
210
+ clearTimeout(debounceTimerRef.current);
211
+ debounceTimerRef.current = null;
212
+ }
213
+ }, []);
194
214
  const isValid = Object.keys(errors).length === 0 && schema.safeParse(data).success;
195
215
  const saveDraft = useCallback(async () => {
196
- if (!isOfflineStorageInitialized() || !isDirty) {
216
+ if (!isOfflineStorageInitialized() || !isDirtyRef.current) {
197
217
  return;
198
218
  }
219
+ await loadPromiseRef.current;
199
220
  try {
200
221
  const storage = getOfflineStorage();
201
- const dataToPersist = { ...data };
202
- for (const field of excludeFields) {
222
+ const { excludeFields: excludeFields2 = [], expirationMs: expirationMs2 = DEFAULT_EXPIRATION_MS } = optionsRef.current;
223
+ const fileRefs2 = fileRefsRef.current;
224
+ const dataToPersist = { ...dataRef.current };
225
+ for (const field of excludeFields2) {
203
226
  delete dataToPersist[field];
204
227
  }
205
228
  if (multiDraft) {
206
- if (currentDraftId) {
207
- await storage.draftManager.updateDraft(currentDraftId, dataToPersist, fileRefs);
208
- const metadata = await storage.draftManager.getDraftMetadata(currentDraftId);
229
+ let draftId = currentDraftIdRef.current;
230
+ if (draftId && !await storage.draftManager.updateDraft(draftId, dataToPersist, fileRefs2)) {
231
+ draftId = null;
232
+ }
233
+ if (draftId) {
234
+ const metadata = await storage.draftManager.getDraftMetadata(draftId);
209
235
  if (metadata) {
210
236
  setCurrentDraftMetadata(metadata);
211
- onDraftChange?.(metadata);
237
+ optionsRef.current.onDraftChange?.(metadata);
212
238
  }
213
239
  } else {
214
240
  const metadata = await storage.draftManager.createDraft(storageKey, {
215
241
  initialData: dataToPersist,
216
- initialFileRefs: fileRefs,
217
- expirationMs
242
+ initialFileRefs: fileRefs2,
243
+ expirationMs: expirationMs2
218
244
  });
245
+ currentDraftIdRef.current = metadata.id;
219
246
  setCurrentDraftId(metadata.id);
220
247
  setCurrentDraftMetadata(metadata);
221
248
  await storage.draftManager.setCurrentDraft(storageKey, metadata.id);
222
- onDraftChange?.(metadata);
249
+ optionsRef.current.onDraftChange?.(metadata);
223
250
  }
224
251
  } else {
225
- await storage.drafts.saveDraft(storageKey, dataToPersist, fileRefs, {
226
- excludeFields,
227
- expirationMs
252
+ await storage.drafts.saveDraft(storageKey, dataToPersist, fileRefs2, {
253
+ excludeFields: excludeFields2,
254
+ expirationMs: expirationMs2
228
255
  });
229
256
  }
230
257
  } catch (err) {
231
258
  console.warn("Failed to save form draft:", err);
232
259
  }
233
- }, [
234
- data,
235
- fileRefs,
236
- storageKey,
237
- excludeFields,
238
- expirationMs,
239
- isDirty,
240
- multiDraft,
241
- currentDraftId,
242
- onDraftChange
243
- ]);
260
+ }, [storageKey, multiDraft]);
244
261
  const scheduleSaveDraft = useCallback(() => {
245
- if (debounceTimerRef.current) {
246
- clearTimeout(debounceTimerRef.current);
247
- }
262
+ cancelPendingSave();
248
263
  debounceTimerRef.current = setTimeout(() => {
264
+ debounceTimerRef.current = null;
249
265
  void saveDraft();
250
266
  }, debounceMs);
251
- }, [saveDraft, debounceMs]);
267
+ }, [saveDraft, debounceMs, cancelPendingSave]);
268
+ const flushPendingSave = useCallback(() => {
269
+ if (debounceTimerRef.current) {
270
+ cancelPendingSave();
271
+ void saveDraft();
272
+ }
273
+ }, [saveDraft, cancelPendingSave]);
274
+ const flushRef = useRef(flushPendingSave);
275
+ flushRef.current = flushPendingSave;
276
+ useEffect(() => {
277
+ const onPageHide = () => flushRef.current();
278
+ window.addEventListener("pagehide", onPageHide);
279
+ return () => {
280
+ window.removeEventListener("pagehide", onPageHide);
281
+ flushRef.current();
282
+ };
283
+ }, []);
252
284
  useEffect(() => {
285
+ let cancelled = false;
253
286
  async function loadDraft() {
254
287
  if (!isOfflineStorageInitialized()) {
255
288
  return;
@@ -258,38 +291,62 @@ function usePersistedForm(options) {
258
291
  const storage = getOfflineStorage();
259
292
  if (multiDraft) {
260
293
  let draft = null;
261
- if (currentDraftId) {
262
- draft = await storage.draftManager.getDraft(currentDraftId);
294
+ if (initialDraftId) {
295
+ draft = await storage.draftManager.getDraft(initialDraftId);
263
296
  } else {
264
297
  draft = await storage.draftManager.getCurrentDraft(storageKey);
265
298
  }
266
- if (draft) {
267
- setData({ ...JSON.parse(JSON.stringify(initialValues)), ...draft.data });
268
- setFileRefs(draft.fileRefs || {});
299
+ if (draft && !cancelled) {
300
+ const { initialValues: initialValues2, onDraftRestored: onDraftRestored2, onDraftChange: onDraftChange2 } = optionsRef.current;
301
+ const restored = {
302
+ ...JSON.parse(JSON.stringify(initialValues2)),
303
+ ...draft.data,
304
+ ...touchedRef.current
305
+ };
306
+ const restoredFileRefs = { ...draft.fileRefs, ...touchedFileRefsRef.current };
307
+ dataRef.current = restored;
308
+ fileRefsRef.current = restoredFileRefs;
309
+ setData(restored);
310
+ setFileRefs(restoredFileRefs);
311
+ currentDraftIdRef.current = draft.metadata.id;
269
312
  setCurrentDraftId(draft.metadata.id);
270
313
  setCurrentDraftMetadata(draft.metadata);
271
314
  setDraftRestored(true);
272
- onDraftRestored?.();
273
- onDraftChange?.(draft.metadata);
315
+ onDraftRestored2?.();
316
+ onDraftChange2?.(draft.metadata);
274
317
  }
275
318
  } else {
276
319
  const result = await storage.drafts.loadDraft(storageKey);
277
- if (result.restored && result.draft) {
278
- setData({ ...JSON.parse(JSON.stringify(initialValues)), ...result.draft.data });
279
- setFileRefs(result.draft.fileRefs || {});
320
+ if (result.restored && result.draft && !cancelled) {
321
+ const { initialValues: initialValues2, onDraftRestored: onDraftRestored2 } = optionsRef.current;
322
+ const restored = {
323
+ ...JSON.parse(JSON.stringify(initialValues2)),
324
+ ...result.draft.data,
325
+ ...touchedRef.current
326
+ };
327
+ const restoredFileRefs = { ...result.draft.fileRefs, ...touchedFileRefsRef.current };
328
+ dataRef.current = restored;
329
+ fileRefsRef.current = restoredFileRefs;
330
+ setData(restored);
331
+ setFileRefs(restoredFileRefs);
280
332
  setDraftRestored(true);
281
- onDraftRestored?.();
333
+ onDraftRestored2?.();
282
334
  }
283
335
  }
284
336
  } catch (err) {
285
337
  console.warn("Failed to load form draft:", err);
286
338
  }
287
339
  }
288
- void loadDraft();
289
- }, [storageKey, initialValues, onDraftRestored, multiDraft, currentDraftId, onDraftChange]);
340
+ loadPromiseRef.current = loadDraft();
341
+ return () => {
342
+ cancelled = true;
343
+ };
344
+ }, [storageKey, multiDraft, initialDraftId]);
290
345
  const setField = useCallback(
291
346
  (field, value) => {
292
347
  setData((prev) => ({ ...prev, [field]: value }));
348
+ touchedRef.current = { ...touchedRef.current, [field]: value };
349
+ isDirtyRef.current = true;
293
350
  setIsDirty(true);
294
351
  scheduleSaveDraft();
295
352
  },
@@ -298,6 +355,8 @@ function usePersistedForm(options) {
298
355
  const setFields = useCallback(
299
356
  (fields) => {
300
357
  setData((prev) => ({ ...prev, ...fields }));
358
+ touchedRef.current = { ...touchedRef.current, ...fields };
359
+ isDirtyRef.current = true;
301
360
  setIsDirty(true);
302
361
  scheduleSaveDraft();
303
362
  },
@@ -349,6 +408,13 @@ function usePersistedForm(options) {
349
408
  for (const fieldName of fileFields) {
350
409
  const ids = fileRefs[fieldName] || [];
351
410
  const fileMap = await storage.files.getFilesAsFileObjects(ids);
411
+ const missing = ids.filter((id) => !fileMap.has(id));
412
+ if (missing.length > 0) {
413
+ console.warn(
414
+ `[usePersistedForm] ${missing.length} file(s) for "${fieldName}" are missing from storage (expired or deleted)`,
415
+ missing
416
+ );
417
+ }
352
418
  result[fieldName] = Array.from(fileMap.values());
353
419
  }
354
420
  return result;
@@ -359,24 +425,31 @@ function usePersistedForm(options) {
359
425
  }
360
426
  try {
361
427
  const storage = getOfflineStorage();
362
- if (multiDraft && currentDraftId) {
363
- await storage.draftManager.deleteDraft(currentDraftId, true);
364
- setCurrentDraftId(null);
365
- setCurrentDraftMetadata(null);
366
- onDraftChange?.(null);
428
+ const draftId = currentDraftIdRef.current;
429
+ if (multiDraft) {
430
+ if (draftId) {
431
+ await storage.draftManager.deleteDraft(draftId, true);
432
+ currentDraftIdRef.current = null;
433
+ setCurrentDraftId(null);
434
+ setCurrentDraftMetadata(null);
435
+ optionsRef.current.onDraftChange?.(null);
436
+ }
367
437
  } else {
368
438
  await storage.drafts.clearDraft(storageKey);
369
- }
370
- for (const fieldName of fileFields) {
371
- await storage.files.deleteFormFiles(storageKey, fieldName);
439
+ for (const fieldName of fileFields) {
440
+ await storage.files.deleteFormFiles(storageKey, fieldName);
441
+ }
372
442
  }
373
443
  } catch (err) {
374
444
  console.warn("Failed to clear form draft:", err);
375
445
  }
376
- }, [storageKey, fileFields, multiDraft, currentDraftId, onDraftChange]);
446
+ }, [storageKey, fileFields, multiDraft]);
377
447
  const handleSubmit = useCallback(
378
448
  async (event) => {
379
449
  event?.preventDefault();
450
+ if (submittingRef.current) {
451
+ return;
452
+ }
380
453
  const now = Date.now();
381
454
  if (now - lastSubmitTimeRef.current < submitCooldownMs) {
382
455
  setGlobalError("Please wait before submitting again");
@@ -385,6 +458,8 @@ function usePersistedForm(options) {
385
458
  if (!validate()) {
386
459
  return;
387
460
  }
461
+ cancelPendingSave();
462
+ submittingRef.current = true;
388
463
  setIsSubmitting(true);
389
464
  setGlobalError(null);
390
465
  try {
@@ -392,27 +467,43 @@ function usePersistedForm(options) {
392
467
  await onSubmit(data, files);
393
468
  lastSubmitTimeRef.current = now;
394
469
  setIsSubmitted(true);
470
+ cancelPendingSave();
395
471
  await clearDraft();
396
472
  } catch (err) {
397
473
  setGlobalError(err instanceof Error ? err.message : "Submission failed");
398
474
  lastSubmitTimeRef.current = 0;
475
+ void saveDraft();
399
476
  throw err;
400
477
  } finally {
478
+ submittingRef.current = false;
401
479
  setIsSubmitting(false);
402
480
  }
403
481
  },
404
- [data, validate, onSubmit, getFilesForSubmit, clearDraft, submitCooldownMs]
482
+ [
483
+ data,
484
+ validate,
485
+ onSubmit,
486
+ getFilesForSubmit,
487
+ clearDraft,
488
+ submitCooldownMs,
489
+ cancelPendingSave,
490
+ saveDraft
491
+ ]
405
492
  );
406
493
  const reset = useCallback(() => {
494
+ cancelPendingSave();
407
495
  setData(JSON.parse(JSON.stringify(originalValuesRef.current)));
408
496
  setErrors({});
409
497
  setGlobalError(null);
410
498
  setIsSubmitted(false);
499
+ isDirtyRef.current = false;
500
+ touchedRef.current = {};
501
+ touchedFileRefsRef.current = {};
411
502
  setIsDirty(false);
412
503
  setDraftRestored(false);
413
504
  setFileRefs({});
414
505
  void clearDraft();
415
- }, [clearDraft]);
506
+ }, [clearDraft, cancelPendingSave]);
416
507
  const clearErrors = useCallback(() => {
417
508
  setErrors({});
418
509
  setGlobalError(null);
@@ -423,6 +514,8 @@ function usePersistedForm(options) {
423
514
  const updateFileRefs = useCallback(
424
515
  (fieldName, fileIds) => {
425
516
  setFileRefs((prev) => ({ ...prev, [fieldName]: fileIds }));
517
+ touchedFileRefsRef.current = { ...touchedFileRefsRef.current, [fieldName]: fileIds };
518
+ isDirtyRef.current = true;
426
519
  setIsDirty(true);
427
520
  scheduleSaveDraft();
428
521
  },
@@ -447,6 +540,7 @@ function usePersistedForm(options) {
447
540
  initialFileRefs: fileRefs,
448
541
  expirationMs
449
542
  });
543
+ currentDraftIdRef.current = metadata.id;
450
544
  setCurrentDraftId(metadata.id);
451
545
  setCurrentDraftMetadata(metadata);
452
546
  await storage.draftManager.setCurrentDraft(storageKey, metadata.id);
@@ -467,8 +561,12 @@ function usePersistedForm(options) {
467
561
  }
468
562
  setData({ ...JSON.parse(JSON.stringify(initialValues)), ...draft.data });
469
563
  setFileRefs(draft.fileRefs || {});
564
+ currentDraftIdRef.current = draft.metadata.id;
470
565
  setCurrentDraftId(draft.metadata.id);
471
566
  setCurrentDraftMetadata(draft.metadata);
567
+ isDirtyRef.current = false;
568
+ touchedRef.current = {};
569
+ touchedFileRefsRef.current = {};
472
570
  setIsDirty(false);
473
571
  setDraftRestored(true);
474
572
  await storage.draftManager.setCurrentDraft(storageKey, draftIdToLoad);
@@ -784,16 +882,9 @@ function useDraftManager(options = {}) {
784
882
  };
785
883
  }
786
884
  function useDraftSync(options) {
787
- const {
788
- adapter,
789
- autoSync = false,
790
- syncIntervalMs = 3e4,
791
- autoSyncOnReconnect = true,
792
- onSyncComplete,
793
- onConflictDetected,
794
- onOnlineStatusChange,
795
- onSyncError
796
- } = options;
885
+ const { adapter, autoSync = false, syncIntervalMs = 3e4, autoSyncOnReconnect = true } = options;
886
+ const optionsRef = useRef(options);
887
+ optionsRef.current = options;
797
888
  const [isOnline, setIsOnline] = useState(
798
889
  typeof navigator !== "undefined" ? navigator.onLine : true
799
890
  );
@@ -804,56 +895,56 @@ function useDraftSync(options) {
804
895
  const [lastResult, setLastResult] = useState(null);
805
896
  const [error, setError] = useState(null);
806
897
  const syncServiceRef = useRef(null);
807
- const initSyncService = useCallback(async () => {
808
- if (!isOfflineStorageInitialized()) {
809
- return;
810
- }
811
- const storage = getOfflineStorage();
812
- const service = createSyncService(storage.adapter, {
813
- adapter,
814
- syncIntervalMs,
815
- autoSyncOnReconnect,
816
- onSyncComplete: (result) => {
817
- setIsSyncing(false);
818
- setLastSyncAt(result.timestamp);
819
- setLastResult(result);
820
- setConflicts(result.conflicts);
821
- setError(result.error ?? null);
822
- onSyncComplete?.(result);
823
- },
824
- onConflictDetected: (newConflicts) => {
825
- setConflicts(newConflicts);
826
- onConflictDetected?.(newConflicts);
827
- },
828
- onOnlineStatusChange: (online) => {
829
- setIsOnline(online);
830
- onOnlineStatusChange?.(online);
831
- },
832
- onSyncError: (err) => {
833
- setIsSyncing(false);
834
- setError(err.message);
835
- onSyncError?.(err);
898
+ const initSyncService = useCallback(
899
+ async (isCancelled) => {
900
+ if (!isOfflineStorageInitialized()) {
901
+ return null;
836
902
  }
837
- });
838
- await service.initialize();
839
- setIsOnline(service.isOnline);
840
- setLastSyncAt(service.lastSyncAt);
841
- setPendingCount(service.pendingCount);
842
- setConflicts(service.getConflicts());
843
- if (autoSync) {
844
- service.startAutoSync();
845
- }
846
- syncServiceRef.current = service;
847
- }, [
848
- adapter,
849
- syncIntervalMs,
850
- autoSyncOnReconnect,
851
- autoSync,
852
- onSyncComplete,
853
- onConflictDetected,
854
- onOnlineStatusChange,
855
- onSyncError
856
- ]);
903
+ const storage = getOfflineStorage();
904
+ const service = createSyncService(storage.adapter, {
905
+ adapter,
906
+ syncIntervalMs,
907
+ autoSyncOnReconnect,
908
+ onSyncComplete: (result) => {
909
+ setIsSyncing(false);
910
+ setLastSyncAt(result.timestamp);
911
+ setLastResult(result);
912
+ setPendingCount(service.pendingCount);
913
+ setConflicts(service.getConflicts());
914
+ setError(result.error ?? null);
915
+ optionsRef.current.onSyncComplete?.(result);
916
+ },
917
+ onConflictDetected: (newConflicts) => {
918
+ setConflicts(service.getConflicts());
919
+ optionsRef.current.onConflictDetected?.(newConflicts);
920
+ },
921
+ onOnlineStatusChange: (online) => {
922
+ setIsOnline(online);
923
+ optionsRef.current.onOnlineStatusChange?.(online);
924
+ },
925
+ onSyncError: (err) => {
926
+ setIsSyncing(false);
927
+ setError(err.message);
928
+ optionsRef.current.onSyncError?.(err);
929
+ }
930
+ });
931
+ await service.initialize();
932
+ if (isCancelled()) {
933
+ service.dispose();
934
+ return null;
935
+ }
936
+ setIsOnline(service.isOnline);
937
+ setLastSyncAt(service.lastSyncAt);
938
+ setPendingCount(service.pendingCount);
939
+ setConflicts(service.getConflicts());
940
+ if (autoSync) {
941
+ service.startAutoSync();
942
+ }
943
+ syncServiceRef.current = service;
944
+ return service;
945
+ },
946
+ [adapter, syncIntervalMs, autoSyncOnReconnect, autoSync]
947
+ );
857
948
  const syncAll = useCallback(async () => {
858
949
  const service = syncServiceRef.current;
859
950
  if (!service) {
@@ -948,9 +1039,17 @@ function useDraftSync(options) {
948
1039
  syncServiceRef.current = null;
949
1040
  }, []);
950
1041
  useEffect(() => {
951
- void initSyncService();
1042
+ let cancelled = false;
1043
+ let service = null;
1044
+ void initSyncService(() => cancelled).then((created) => {
1045
+ service = created;
1046
+ });
952
1047
  return () => {
953
- syncServiceRef.current?.dispose();
1048
+ cancelled = true;
1049
+ service?.dispose();
1050
+ if (syncServiceRef.current === service) {
1051
+ syncServiceRef.current = null;
1052
+ }
954
1053
  };
955
1054
  }, [initSyncService]);
956
1055
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/offline-react",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "description": "React bindings for offline persistence and caching",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -46,11 +46,6 @@
46
46
  "react": "^18.0.0 || ^19.0.0",
47
47
  "zod": "^3.23.0"
48
48
  },
49
- "peerDependenciesMeta": {
50
- "zod": {
51
- "optional": true
52
- }
53
- },
54
49
  "dependencies": {
55
50
  "@classic-homes/offline-core": "*"
56
51
  },