@classic-homes/offline-react 0.1.4 → 0.1.5

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,79 @@ 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);
193
194
  const originalValuesRef = useRef(JSON.parse(JSON.stringify(initialValues)));
195
+ const dataRef = useRef(data);
196
+ dataRef.current = data;
197
+ const fileRefsRef = useRef(fileRefs);
198
+ fileRefsRef.current = fileRefs;
199
+ const isDirtyRef = useRef(isDirty);
200
+ isDirtyRef.current = isDirty;
201
+ const currentDraftIdRef = useRef(currentDraftId);
202
+ currentDraftIdRef.current = currentDraftId;
203
+ const optionsRef = useRef(options);
204
+ optionsRef.current = options;
205
+ const cancelPendingSave = useCallback(() => {
206
+ if (debounceTimerRef.current) {
207
+ clearTimeout(debounceTimerRef.current);
208
+ debounceTimerRef.current = null;
209
+ }
210
+ }, []);
211
+ useEffect(() => cancelPendingSave, [cancelPendingSave]);
194
212
  const isValid = Object.keys(errors).length === 0 && schema.safeParse(data).success;
195
213
  const saveDraft = useCallback(async () => {
196
- if (!isOfflineStorageInitialized() || !isDirty) {
214
+ if (!isOfflineStorageInitialized() || !isDirtyRef.current) {
197
215
  return;
198
216
  }
199
217
  try {
200
218
  const storage = getOfflineStorage();
201
- const dataToPersist = { ...data };
202
- for (const field of excludeFields) {
219
+ const { excludeFields: excludeFields2 = [], expirationMs: expirationMs2 = DEFAULT_EXPIRATION_MS } = optionsRef.current;
220
+ const fileRefs2 = fileRefsRef.current;
221
+ const dataToPersist = { ...dataRef.current };
222
+ for (const field of excludeFields2) {
203
223
  delete dataToPersist[field];
204
224
  }
205
225
  if (multiDraft) {
206
- if (currentDraftId) {
207
- await storage.draftManager.updateDraft(currentDraftId, dataToPersist, fileRefs);
208
- const metadata = await storage.draftManager.getDraftMetadata(currentDraftId);
226
+ const draftId = currentDraftIdRef.current;
227
+ if (draftId) {
228
+ await storage.draftManager.updateDraft(draftId, dataToPersist, fileRefs2);
229
+ const metadata = await storage.draftManager.getDraftMetadata(draftId);
209
230
  if (metadata) {
210
231
  setCurrentDraftMetadata(metadata);
211
- onDraftChange?.(metadata);
232
+ optionsRef.current.onDraftChange?.(metadata);
212
233
  }
213
234
  } else {
214
235
  const metadata = await storage.draftManager.createDraft(storageKey, {
215
236
  initialData: dataToPersist,
216
- initialFileRefs: fileRefs,
217
- expirationMs
237
+ initialFileRefs: fileRefs2,
238
+ expirationMs: expirationMs2
218
239
  });
240
+ currentDraftIdRef.current = metadata.id;
219
241
  setCurrentDraftId(metadata.id);
220
242
  setCurrentDraftMetadata(metadata);
221
243
  await storage.draftManager.setCurrentDraft(storageKey, metadata.id);
222
- onDraftChange?.(metadata);
244
+ optionsRef.current.onDraftChange?.(metadata);
223
245
  }
224
246
  } else {
225
- await storage.drafts.saveDraft(storageKey, dataToPersist, fileRefs, {
226
- excludeFields,
227
- expirationMs
247
+ await storage.drafts.saveDraft(storageKey, dataToPersist, fileRefs2, {
248
+ excludeFields: excludeFields2,
249
+ expirationMs: expirationMs2
228
250
  });
229
251
  }
230
252
  } catch (err) {
231
253
  console.warn("Failed to save form draft:", err);
232
254
  }
233
- }, [
234
- data,
235
- fileRefs,
236
- storageKey,
237
- excludeFields,
238
- expirationMs,
239
- isDirty,
240
- multiDraft,
241
- currentDraftId,
242
- onDraftChange
243
- ]);
255
+ }, [storageKey, multiDraft]);
244
256
  const scheduleSaveDraft = useCallback(() => {
245
- if (debounceTimerRef.current) {
246
- clearTimeout(debounceTimerRef.current);
247
- }
257
+ cancelPendingSave();
248
258
  debounceTimerRef.current = setTimeout(() => {
259
+ debounceTimerRef.current = null;
249
260
  void saveDraft();
250
261
  }, debounceMs);
251
- }, [saveDraft, debounceMs]);
262
+ }, [saveDraft, debounceMs, cancelPendingSave]);
252
263
  useEffect(() => {
264
+ let cancelled = false;
253
265
  async function loadDraft() {
254
266
  if (!isOfflineStorageInitialized()) {
255
267
  return;
@@ -258,27 +270,30 @@ function usePersistedForm(options) {
258
270
  const storage = getOfflineStorage();
259
271
  if (multiDraft) {
260
272
  let draft = null;
261
- if (currentDraftId) {
262
- draft = await storage.draftManager.getDraft(currentDraftId);
273
+ if (initialDraftId) {
274
+ draft = await storage.draftManager.getDraft(initialDraftId);
263
275
  } else {
264
276
  draft = await storage.draftManager.getCurrentDraft(storageKey);
265
277
  }
266
- if (draft) {
267
- setData({ ...JSON.parse(JSON.stringify(initialValues)), ...draft.data });
278
+ if (draft && !cancelled && !isDirtyRef.current) {
279
+ const { initialValues: initialValues2, onDraftRestored: onDraftRestored2, onDraftChange: onDraftChange2 } = optionsRef.current;
280
+ setData({ ...JSON.parse(JSON.stringify(initialValues2)), ...draft.data });
268
281
  setFileRefs(draft.fileRefs || {});
282
+ currentDraftIdRef.current = draft.metadata.id;
269
283
  setCurrentDraftId(draft.metadata.id);
270
284
  setCurrentDraftMetadata(draft.metadata);
271
285
  setDraftRestored(true);
272
- onDraftRestored?.();
273
- onDraftChange?.(draft.metadata);
286
+ onDraftRestored2?.();
287
+ onDraftChange2?.(draft.metadata);
274
288
  }
275
289
  } else {
276
290
  const result = await storage.drafts.loadDraft(storageKey);
277
- if (result.restored && result.draft) {
278
- setData({ ...JSON.parse(JSON.stringify(initialValues)), ...result.draft.data });
291
+ if (result.restored && result.draft && !cancelled && !isDirtyRef.current) {
292
+ const { initialValues: initialValues2, onDraftRestored: onDraftRestored2 } = optionsRef.current;
293
+ setData({ ...JSON.parse(JSON.stringify(initialValues2)), ...result.draft.data });
279
294
  setFileRefs(result.draft.fileRefs || {});
280
295
  setDraftRestored(true);
281
- onDraftRestored?.();
296
+ onDraftRestored2?.();
282
297
  }
283
298
  }
284
299
  } catch (err) {
@@ -286,10 +301,14 @@ function usePersistedForm(options) {
286
301
  }
287
302
  }
288
303
  void loadDraft();
289
- }, [storageKey, initialValues, onDraftRestored, multiDraft, currentDraftId, onDraftChange]);
304
+ return () => {
305
+ cancelled = true;
306
+ };
307
+ }, [storageKey, multiDraft, initialDraftId]);
290
308
  const setField = useCallback(
291
309
  (field, value) => {
292
310
  setData((prev) => ({ ...prev, [field]: value }));
311
+ isDirtyRef.current = true;
293
312
  setIsDirty(true);
294
313
  scheduleSaveDraft();
295
314
  },
@@ -298,6 +317,7 @@ function usePersistedForm(options) {
298
317
  const setFields = useCallback(
299
318
  (fields) => {
300
319
  setData((prev) => ({ ...prev, ...fields }));
320
+ isDirtyRef.current = true;
301
321
  setIsDirty(true);
302
322
  scheduleSaveDraft();
303
323
  },
@@ -359,11 +379,13 @@ function usePersistedForm(options) {
359
379
  }
360
380
  try {
361
381
  const storage = getOfflineStorage();
362
- if (multiDraft && currentDraftId) {
363
- await storage.draftManager.deleteDraft(currentDraftId, true);
382
+ const draftId = currentDraftIdRef.current;
383
+ if (multiDraft && draftId) {
384
+ await storage.draftManager.deleteDraft(draftId, true);
385
+ currentDraftIdRef.current = null;
364
386
  setCurrentDraftId(null);
365
387
  setCurrentDraftMetadata(null);
366
- onDraftChange?.(null);
388
+ optionsRef.current.onDraftChange?.(null);
367
389
  } else {
368
390
  await storage.drafts.clearDraft(storageKey);
369
391
  }
@@ -373,10 +395,13 @@ function usePersistedForm(options) {
373
395
  } catch (err) {
374
396
  console.warn("Failed to clear form draft:", err);
375
397
  }
376
- }, [storageKey, fileFields, multiDraft, currentDraftId, onDraftChange]);
398
+ }, [storageKey, fileFields, multiDraft]);
377
399
  const handleSubmit = useCallback(
378
400
  async (event) => {
379
401
  event?.preventDefault();
402
+ if (submittingRef.current) {
403
+ return;
404
+ }
380
405
  const now = Date.now();
381
406
  if (now - lastSubmitTimeRef.current < submitCooldownMs) {
382
407
  setGlobalError("Please wait before submitting again");
@@ -385,6 +410,8 @@ function usePersistedForm(options) {
385
410
  if (!validate()) {
386
411
  return;
387
412
  }
413
+ cancelPendingSave();
414
+ submittingRef.current = true;
388
415
  setIsSubmitting(true);
389
416
  setGlobalError(null);
390
417
  try {
@@ -392,27 +419,31 @@ function usePersistedForm(options) {
392
419
  await onSubmit(data, files);
393
420
  lastSubmitTimeRef.current = now;
394
421
  setIsSubmitted(true);
422
+ cancelPendingSave();
395
423
  await clearDraft();
396
424
  } catch (err) {
397
425
  setGlobalError(err instanceof Error ? err.message : "Submission failed");
398
426
  lastSubmitTimeRef.current = 0;
399
427
  throw err;
400
428
  } finally {
429
+ submittingRef.current = false;
401
430
  setIsSubmitting(false);
402
431
  }
403
432
  },
404
- [data, validate, onSubmit, getFilesForSubmit, clearDraft, submitCooldownMs]
433
+ [data, validate, onSubmit, getFilesForSubmit, clearDraft, submitCooldownMs, cancelPendingSave]
405
434
  );
406
435
  const reset = useCallback(() => {
436
+ cancelPendingSave();
407
437
  setData(JSON.parse(JSON.stringify(originalValuesRef.current)));
408
438
  setErrors({});
409
439
  setGlobalError(null);
410
440
  setIsSubmitted(false);
441
+ isDirtyRef.current = false;
411
442
  setIsDirty(false);
412
443
  setDraftRestored(false);
413
444
  setFileRefs({});
414
445
  void clearDraft();
415
- }, [clearDraft]);
446
+ }, [clearDraft, cancelPendingSave]);
416
447
  const clearErrors = useCallback(() => {
417
448
  setErrors({});
418
449
  setGlobalError(null);
@@ -423,6 +454,7 @@ function usePersistedForm(options) {
423
454
  const updateFileRefs = useCallback(
424
455
  (fieldName, fileIds) => {
425
456
  setFileRefs((prev) => ({ ...prev, [fieldName]: fileIds }));
457
+ isDirtyRef.current = true;
426
458
  setIsDirty(true);
427
459
  scheduleSaveDraft();
428
460
  },
@@ -447,6 +479,7 @@ function usePersistedForm(options) {
447
479
  initialFileRefs: fileRefs,
448
480
  expirationMs
449
481
  });
482
+ currentDraftIdRef.current = metadata.id;
450
483
  setCurrentDraftId(metadata.id);
451
484
  setCurrentDraftMetadata(metadata);
452
485
  await storage.draftManager.setCurrentDraft(storageKey, metadata.id);
@@ -467,8 +500,10 @@ function usePersistedForm(options) {
467
500
  }
468
501
  setData({ ...JSON.parse(JSON.stringify(initialValues)), ...draft.data });
469
502
  setFileRefs(draft.fileRefs || {});
503
+ currentDraftIdRef.current = draft.metadata.id;
470
504
  setCurrentDraftId(draft.metadata.id);
471
505
  setCurrentDraftMetadata(draft.metadata);
506
+ isDirtyRef.current = false;
472
507
  setIsDirty(false);
473
508
  setDraftRestored(true);
474
509
  await storage.draftManager.setCurrentDraft(storageKey, draftIdToLoad);
@@ -784,16 +819,9 @@ function useDraftManager(options = {}) {
784
819
  };
785
820
  }
786
821
  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;
822
+ const { adapter, autoSync = false, syncIntervalMs = 3e4, autoSyncOnReconnect = true } = options;
823
+ const optionsRef = useRef(options);
824
+ optionsRef.current = options;
797
825
  const [isOnline, setIsOnline] = useState(
798
826
  typeof navigator !== "undefined" ? navigator.onLine : true
799
827
  );
@@ -804,56 +832,55 @@ function useDraftSync(options) {
804
832
  const [lastResult, setLastResult] = useState(null);
805
833
  const [error, setError] = useState(null);
806
834
  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);
835
+ const initSyncService = useCallback(
836
+ async (isCancelled) => {
837
+ if (!isOfflineStorageInitialized()) {
838
+ return null;
836
839
  }
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
- ]);
840
+ const storage = getOfflineStorage();
841
+ const service = createSyncService(storage.adapter, {
842
+ adapter,
843
+ syncIntervalMs,
844
+ autoSyncOnReconnect,
845
+ onSyncComplete: (result) => {
846
+ setIsSyncing(false);
847
+ setLastSyncAt(result.timestamp);
848
+ setLastResult(result);
849
+ setConflicts(service.getConflicts());
850
+ setError(result.error ?? null);
851
+ optionsRef.current.onSyncComplete?.(result);
852
+ },
853
+ onConflictDetected: (newConflicts) => {
854
+ setConflicts(service.getConflicts());
855
+ optionsRef.current.onConflictDetected?.(newConflicts);
856
+ },
857
+ onOnlineStatusChange: (online) => {
858
+ setIsOnline(online);
859
+ optionsRef.current.onOnlineStatusChange?.(online);
860
+ },
861
+ onSyncError: (err) => {
862
+ setIsSyncing(false);
863
+ setError(err.message);
864
+ optionsRef.current.onSyncError?.(err);
865
+ }
866
+ });
867
+ await service.initialize();
868
+ if (isCancelled()) {
869
+ service.dispose();
870
+ return null;
871
+ }
872
+ setIsOnline(service.isOnline);
873
+ setLastSyncAt(service.lastSyncAt);
874
+ setPendingCount(service.pendingCount);
875
+ setConflicts(service.getConflicts());
876
+ if (autoSync) {
877
+ service.startAutoSync();
878
+ }
879
+ syncServiceRef.current = service;
880
+ return service;
881
+ },
882
+ [adapter, syncIntervalMs, autoSyncOnReconnect, autoSync]
883
+ );
857
884
  const syncAll = useCallback(async () => {
858
885
  const service = syncServiceRef.current;
859
886
  if (!service) {
@@ -948,9 +975,17 @@ function useDraftSync(options) {
948
975
  syncServiceRef.current = null;
949
976
  }, []);
950
977
  useEffect(() => {
951
- void initSyncService();
978
+ let cancelled = false;
979
+ let service = null;
980
+ void initSyncService(() => cancelled).then((created) => {
981
+ service = created;
982
+ });
952
983
  return () => {
953
- syncServiceRef.current?.dispose();
984
+ cancelled = true;
985
+ service?.dispose();
986
+ if (syncServiceRef.current === service) {
987
+ syncServiceRef.current = null;
988
+ }
954
989
  };
955
990
  }, [initSyncService]);
956
991
  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.1.5",
4
4
  "description": "React bindings for offline persistence and caching",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",