@classic-homes/offline-react 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.
- package/README.md +298 -0
- package/dist/index.d.ts +399 -0
- package/dist/index.js +989 -0
- package/package.json +71 -0
package/README.md
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
# @classic-homes/offline-react
|
|
2
|
+
|
|
3
|
+
React hooks for offline persistence and caching. Provides reactive file storage, form draft persistence, and data caching for React applications.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **useFileStorage**: Reactive file storage with validation and previews
|
|
8
|
+
- **usePersistedForm**: Automatic form draft persistence
|
|
9
|
+
- **useOfflineCache**: Data caching with TTL and stale-while-revalidate
|
|
10
|
+
- **TypeScript**: Full type safety with generics
|
|
11
|
+
- **React 18/19**: Compatible with latest React versions
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @classic-homes/offline-react @classic-homes/offline-core
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
```tsx
|
|
22
|
+
import { useEffect } from 'react';
|
|
23
|
+
import { initOfflineStorage } from '@classic-homes/offline-core';
|
|
24
|
+
import { useFileStorage, usePersistedForm, useOfflineCache } from '@classic-homes/offline-react';
|
|
25
|
+
|
|
26
|
+
// Initialize storage at app startup
|
|
27
|
+
function App() {
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
initOfflineStorage();
|
|
30
|
+
}, []);
|
|
31
|
+
|
|
32
|
+
return <MyForm />;
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Hooks
|
|
37
|
+
|
|
38
|
+
### useFileStorage
|
|
39
|
+
|
|
40
|
+
Manage file attachments with validation, preview generation, and persistence.
|
|
41
|
+
|
|
42
|
+
```tsx
|
|
43
|
+
import { useFileStorage } from '@classic-homes/offline-react';
|
|
44
|
+
|
|
45
|
+
function FileUploadField() {
|
|
46
|
+
const documents = useFileStorage({
|
|
47
|
+
formKey: 'contact-form',
|
|
48
|
+
fieldName: 'documents',
|
|
49
|
+
maxFiles: 5,
|
|
50
|
+
maxSizeBytes: 10 * 1024 * 1024, // 10MB
|
|
51
|
+
acceptedTypes: ['application/pdf', 'image/*'],
|
|
52
|
+
onValidationError: (errors) => {
|
|
53
|
+
errors.forEach((e) => toast.error(e.message));
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const handleDrop = async (files: File[]) => {
|
|
58
|
+
await documents.addFiles(files);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
return (
|
|
62
|
+
<div>
|
|
63
|
+
{documents.isLoading ? (
|
|
64
|
+
<Spinner />
|
|
65
|
+
) : (
|
|
66
|
+
<FileList files={documents.files} onRemove={documents.removeFile} />
|
|
67
|
+
)}
|
|
68
|
+
<DropZone onDrop={handleDrop} />
|
|
69
|
+
</div>
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
#### Options
|
|
75
|
+
|
|
76
|
+
| Option | Type | Description |
|
|
77
|
+
| ------------------- | ---------- | ------------------------------------------------ |
|
|
78
|
+
| `formKey` | `string` | Form identifier |
|
|
79
|
+
| `fieldName` | `string` | Field name within the form |
|
|
80
|
+
| `maxFiles` | `number` | Maximum number of files |
|
|
81
|
+
| `maxSizeBytes` | `number` | Maximum file size in bytes |
|
|
82
|
+
| `acceptedTypes` | `string[]` | Accepted MIME types (supports wildcards) |
|
|
83
|
+
| `expirationMs` | `number` | File expiration time |
|
|
84
|
+
| `generatePreviews` | `boolean` | Generate preview URLs for images (default: true) |
|
|
85
|
+
| `onValidationError` | `function` | Callback for validation errors |
|
|
86
|
+
|
|
87
|
+
#### Return Value
|
|
88
|
+
|
|
89
|
+
| Property | Type | Description |
|
|
90
|
+
| ------------------- | ----------------- | -------------------------------- |
|
|
91
|
+
| `files` | `PersistedFile[]` | Current files |
|
|
92
|
+
| `fileIds` | `string[]` | File IDs for form submission |
|
|
93
|
+
| `isLoading` | `boolean` | Loading state |
|
|
94
|
+
| `error` | `Error \| null` | Current error |
|
|
95
|
+
| `addFiles` | `function` | Add files (validates and stores) |
|
|
96
|
+
| `removeFile` | `function` | Remove a file by ID |
|
|
97
|
+
| `clearFiles` | `function` | Remove all files |
|
|
98
|
+
| `reload` | `function` | Reload from storage |
|
|
99
|
+
| `getFilesForSubmit` | `function` | Get File objects for FormData |
|
|
100
|
+
|
|
101
|
+
### usePersistedForm
|
|
102
|
+
|
|
103
|
+
Automatically persist form state across page reloads.
|
|
104
|
+
|
|
105
|
+
```tsx
|
|
106
|
+
import { usePersistedForm } from '@classic-homes/offline-react';
|
|
107
|
+
import { z } from 'zod';
|
|
108
|
+
|
|
109
|
+
const schema = z.object({
|
|
110
|
+
name: z.string().min(1),
|
|
111
|
+
email: z.string().email(),
|
|
112
|
+
message: z.string(),
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
function ContactForm() {
|
|
116
|
+
const form = usePersistedForm({
|
|
117
|
+
formKey: 'contact-form',
|
|
118
|
+
defaultValues: { name: '', email: '', message: '' },
|
|
119
|
+
schema, // Optional Zod schema
|
|
120
|
+
debounceMs: 500,
|
|
121
|
+
excludeFields: ['password'], // Don't persist sensitive fields
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
const handleSubmit = async (e: React.FormEvent) => {
|
|
125
|
+
e.preventDefault();
|
|
126
|
+
if (!form.isValid) return;
|
|
127
|
+
|
|
128
|
+
await submitForm(form.values);
|
|
129
|
+
await form.clearDraft();
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
return (
|
|
133
|
+
<form onSubmit={handleSubmit}>
|
|
134
|
+
{form.hasDraft && (
|
|
135
|
+
<button type="button" onClick={form.restoreDraft}>
|
|
136
|
+
Restore draft from {form.draftInfo?.timestamp}
|
|
137
|
+
</button>
|
|
138
|
+
)}
|
|
139
|
+
|
|
140
|
+
<input
|
|
141
|
+
name="name"
|
|
142
|
+
value={form.values.name}
|
|
143
|
+
onChange={(e) => form.setValue('name', e.target.value)}
|
|
144
|
+
/>
|
|
145
|
+
{form.errors.name && <span>{form.errors.name}</span>}
|
|
146
|
+
|
|
147
|
+
<input
|
|
148
|
+
name="email"
|
|
149
|
+
value={form.values.email}
|
|
150
|
+
onChange={(e) => form.setValue('email', e.target.value)}
|
|
151
|
+
/>
|
|
152
|
+
|
|
153
|
+
<textarea
|
|
154
|
+
name="message"
|
|
155
|
+
value={form.values.message}
|
|
156
|
+
onChange={(e) => form.setValue('message', e.target.value)}
|
|
157
|
+
/>
|
|
158
|
+
|
|
159
|
+
<button type="submit" disabled={!form.isValid || form.isSubmitting}>
|
|
160
|
+
Submit
|
|
161
|
+
</button>
|
|
162
|
+
</form>
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
#### Options
|
|
168
|
+
|
|
169
|
+
| Option | Type | Description |
|
|
170
|
+
| --------------- | ----------- | ------------------------------------------ |
|
|
171
|
+
| `formKey` | `string` | Unique form identifier |
|
|
172
|
+
| `defaultValues` | `T` | Default form values |
|
|
173
|
+
| `schema` | `ZodSchema` | Optional Zod validation schema |
|
|
174
|
+
| `debounceMs` | `number` | Debounce time for auto-save (default: 500) |
|
|
175
|
+
| `excludeFields` | `string[]` | Fields to exclude from persistence |
|
|
176
|
+
| `expirationMs` | `number` | Draft expiration time |
|
|
177
|
+
| `autoRestore` | `boolean` | Auto-restore on mount (default: false) |
|
|
178
|
+
|
|
179
|
+
#### Return Value
|
|
180
|
+
|
|
181
|
+
| Property | Type | Description |
|
|
182
|
+
| -------------- | ---------------- | -------------------------------- |
|
|
183
|
+
| `values` | `T` | Current form values |
|
|
184
|
+
| `errors` | `FieldErrors<T>` | Validation errors by field |
|
|
185
|
+
| `isValid` | `boolean` | Whether form passes validation |
|
|
186
|
+
| `isDirty` | `boolean` | Whether form has unsaved changes |
|
|
187
|
+
| `hasDraft` | `boolean` | Whether a draft exists |
|
|
188
|
+
| `draftInfo` | `object` | Draft metadata |
|
|
189
|
+
| `setValue` | `function` | Set a field value |
|
|
190
|
+
| `setValues` | `function` | Set multiple values |
|
|
191
|
+
| `reset` | `function` | Reset to default values |
|
|
192
|
+
| `saveDraft` | `function` | Manually save draft |
|
|
193
|
+
| `restoreDraft` | `function` | Restore from draft |
|
|
194
|
+
| `clearDraft` | `function` | Delete the draft |
|
|
195
|
+
|
|
196
|
+
### useOfflineCache
|
|
197
|
+
|
|
198
|
+
Cache data with TTL and stale-while-revalidate support.
|
|
199
|
+
|
|
200
|
+
```tsx
|
|
201
|
+
import { useOfflineCache } from '@classic-homes/offline-react';
|
|
202
|
+
|
|
203
|
+
function UserProfile({ userId }: { userId: string }) {
|
|
204
|
+
const userCache = useOfflineCache<User>({
|
|
205
|
+
key: `user:${userId}`,
|
|
206
|
+
ttl: 5 * 60 * 1000, // 5 minutes
|
|
207
|
+
tags: ['user'],
|
|
208
|
+
staleWhileRevalidate: true,
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
useEffect(() => {
|
|
212
|
+
userCache.get(() => fetchUser(userId));
|
|
213
|
+
}, [userId]);
|
|
214
|
+
|
|
215
|
+
if (userCache.isLoading) return <Spinner />;
|
|
216
|
+
if (userCache.error) return <Error error={userCache.error} />;
|
|
217
|
+
if (!userCache.data) return null;
|
|
218
|
+
|
|
219
|
+
return (
|
|
220
|
+
<div>
|
|
221
|
+
<h1>{userCache.data.name}</h1>
|
|
222
|
+
{userCache.isStale && <span>Updating...</span>}
|
|
223
|
+
<button onClick={() => userCache.refresh(() => fetchUser(userId))}>Refresh</button>
|
|
224
|
+
</div>
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
#### Options
|
|
230
|
+
|
|
231
|
+
| Option | Type | Description |
|
|
232
|
+
| ---------------------- | ---------- | --------------------------------- |
|
|
233
|
+
| `key` | `string` | Cache key |
|
|
234
|
+
| `ttl` | `number` | Time to live in milliseconds |
|
|
235
|
+
| `tags` | `string[]` | Tags for bulk invalidation |
|
|
236
|
+
| `staleWhileRevalidate` | `boolean` | Return stale data while fetching |
|
|
237
|
+
| `staleTime` | `number` | How long stale data is acceptable |
|
|
238
|
+
|
|
239
|
+
#### Return Value
|
|
240
|
+
|
|
241
|
+
| Property | Type | Description |
|
|
242
|
+
| -------------- | ---------------- | --------------------- |
|
|
243
|
+
| `data` | `T \| null` | Cached data |
|
|
244
|
+
| `isLoading` | `boolean` | Loading state |
|
|
245
|
+
| `isStale` | `boolean` | Whether data is stale |
|
|
246
|
+
| `error` | `Error \| null` | Current error |
|
|
247
|
+
| `ttlRemaining` | `number \| null` | Time until expiration |
|
|
248
|
+
| `get` | `function` | Get cached or fetch |
|
|
249
|
+
| `set` | `function` | Set cache value |
|
|
250
|
+
| `invalidate` | `function` | Invalidate this key |
|
|
251
|
+
| `refresh` | `function` | Force re-fetch |
|
|
252
|
+
| `has` | `function` | Check if cached |
|
|
253
|
+
|
|
254
|
+
### Utility Functions
|
|
255
|
+
|
|
256
|
+
```tsx
|
|
257
|
+
import { invalidateCacheByTag, invalidateAllCache } from '@classic-homes/offline-react';
|
|
258
|
+
|
|
259
|
+
// Invalidate all entries with a tag
|
|
260
|
+
await invalidateCacheByTag('user');
|
|
261
|
+
|
|
262
|
+
// Invalidate entire cache
|
|
263
|
+
await invalidateAllCache();
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
## TypeScript
|
|
267
|
+
|
|
268
|
+
All hooks are fully typed with generics:
|
|
269
|
+
|
|
270
|
+
```tsx
|
|
271
|
+
interface User {
|
|
272
|
+
id: string;
|
|
273
|
+
name: string;
|
|
274
|
+
email: string;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const userCache = useOfflineCache<User>({ key: 'user' });
|
|
278
|
+
// userCache.data is User | null
|
|
279
|
+
|
|
280
|
+
const form = usePersistedForm<User>({
|
|
281
|
+
formKey: 'user',
|
|
282
|
+
defaultValues: { id: '', name: '', email: '' },
|
|
283
|
+
});
|
|
284
|
+
// form.values is User
|
|
285
|
+
// form.setValue('name', value) - 'name' is typed
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
## Testing
|
|
289
|
+
|
|
290
|
+
```bash
|
|
291
|
+
npm test # Run tests
|
|
292
|
+
npm run test:watch # Watch mode
|
|
293
|
+
npm run test:coverage # With coverage
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
## License
|
|
297
|
+
|
|
298
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
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, isOfflineStorageInitialized } from '@classic-homes/offline-core';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* useFileStorage - React hook for file persistence
|
|
7
|
+
*
|
|
8
|
+
* Provides reactive file storage with validation, preview generation,
|
|
9
|
+
* and automatic cleanup.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* import { useFileStorage } from '@classic-homes/offline-react';
|
|
14
|
+
*
|
|
15
|
+
* function FileUploadField() {
|
|
16
|
+
* const documents = useFileStorage({
|
|
17
|
+
* formKey: 'contact-form',
|
|
18
|
+
* fieldName: 'documents',
|
|
19
|
+
* maxFiles: 5,
|
|
20
|
+
* maxSizeBytes: 10 * 1024 * 1024,
|
|
21
|
+
* acceptedTypes: ['application/pdf', 'image/*'],
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* return (
|
|
25
|
+
* <FileUpload
|
|
26
|
+
* files={documents.files}
|
|
27
|
+
* onFilesAdded={documents.addFiles}
|
|
28
|
+
* onFileRemoved={documents.removeFile}
|
|
29
|
+
* />
|
|
30
|
+
* );
|
|
31
|
+
* }
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
interface UseFileStorageOptions extends FileConstraints {
|
|
36
|
+
/** Form key this field belongs to */
|
|
37
|
+
formKey: string;
|
|
38
|
+
/** Field name for this file input */
|
|
39
|
+
fieldName: string;
|
|
40
|
+
/** Custom expiration in milliseconds */
|
|
41
|
+
expirationMs?: number;
|
|
42
|
+
/** Generate preview URLs for images (default: true) */
|
|
43
|
+
generatePreviews?: boolean;
|
|
44
|
+
/** Callback when validation errors occur */
|
|
45
|
+
onValidationError?: (errors: FileValidationError[]) => void;
|
|
46
|
+
}
|
|
47
|
+
interface UseFileStorageReturn {
|
|
48
|
+
/** Current files */
|
|
49
|
+
files: PersistedFile[];
|
|
50
|
+
/** File IDs for form submission */
|
|
51
|
+
fileIds: string[];
|
|
52
|
+
/** Whether files are being loaded */
|
|
53
|
+
isLoading: boolean;
|
|
54
|
+
/** Current error if any */
|
|
55
|
+
error: Error | null;
|
|
56
|
+
/** Add files (validates and stores) */
|
|
57
|
+
addFiles: (files: File[]) => Promise<void>;
|
|
58
|
+
/** Remove a file by ID */
|
|
59
|
+
removeFile: (id: string) => Promise<void>;
|
|
60
|
+
/** Remove all files */
|
|
61
|
+
clearFiles: () => Promise<void>;
|
|
62
|
+
/** Reload files from storage */
|
|
63
|
+
reload: () => Promise<void>;
|
|
64
|
+
/** Get files as File objects for submission */
|
|
65
|
+
getFilesForSubmit: () => Promise<File[]>;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* React hook for file storage
|
|
69
|
+
*/
|
|
70
|
+
declare function useFileStorage(options: UseFileStorageOptions): UseFileStorageReturn;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* usePersistedForm - React hook for form persistence with file support
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```tsx
|
|
77
|
+
* import { usePersistedForm } from '@classic-homes/offline-react';
|
|
78
|
+
* import { z } from 'zod';
|
|
79
|
+
*
|
|
80
|
+
* const schema = z.object({
|
|
81
|
+
* name: z.string().min(1),
|
|
82
|
+
* email: z.string().email(),
|
|
83
|
+
* });
|
|
84
|
+
*
|
|
85
|
+
* function ContactForm() {
|
|
86
|
+
* const form = usePersistedForm({
|
|
87
|
+
* schema,
|
|
88
|
+
* initialValues: { name: '', email: '' },
|
|
89
|
+
* storageKey: 'contact-form',
|
|
90
|
+
* onSubmit: async (data, files) => {
|
|
91
|
+
* await submitWithFiles(data, files);
|
|
92
|
+
* },
|
|
93
|
+
* });
|
|
94
|
+
*
|
|
95
|
+
* return (
|
|
96
|
+
* <form onSubmit={form.handleSubmit}>
|
|
97
|
+
* <input
|
|
98
|
+
* value={form.data.name}
|
|
99
|
+
* onChange={(e) => form.setField('name', e.target.value)}
|
|
100
|
+
* />
|
|
101
|
+
* {form.errors.name && <span>{form.errors.name}</span>}
|
|
102
|
+
* {form.draftRestored && <div>Draft restored</div>}
|
|
103
|
+
* </form>
|
|
104
|
+
* );
|
|
105
|
+
* }
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
|
|
109
|
+
type FieldErrors<T> = Partial<Record<keyof T, string>>;
|
|
110
|
+
interface UsePersistedFormOptions<T extends z.ZodObject<z.ZodRawShape>> {
|
|
111
|
+
schema: T;
|
|
112
|
+
initialValues: z.infer<T>;
|
|
113
|
+
storageKey: string;
|
|
114
|
+
excludeFields?: (keyof z.infer<T>)[];
|
|
115
|
+
fileFields?: string[];
|
|
116
|
+
expirationMs?: number;
|
|
117
|
+
debounceMs?: number;
|
|
118
|
+
submitCooldownMs?: number;
|
|
119
|
+
onDraftRestored?: () => void;
|
|
120
|
+
onSubmit: (data: z.infer<T>, files: Record<string, File[]>) => Promise<void>;
|
|
121
|
+
/** Enable multi-draft mode (V2 storage) */
|
|
122
|
+
multiDraft?: boolean;
|
|
123
|
+
/** Specific draft ID to load (multi-draft mode) */
|
|
124
|
+
draftId?: string;
|
|
125
|
+
/** Callback when draft metadata changes */
|
|
126
|
+
onDraftChange?: (metadata: DraftMetadata | null) => void;
|
|
127
|
+
}
|
|
128
|
+
interface UsePersistedFormReturn<T extends z.ZodObject<z.ZodRawShape>> {
|
|
129
|
+
data: z.infer<T>;
|
|
130
|
+
errors: FieldErrors<z.infer<T>>;
|
|
131
|
+
globalError: string | null;
|
|
132
|
+
isSubmitting: boolean;
|
|
133
|
+
isSubmitted: boolean;
|
|
134
|
+
isDirty: boolean;
|
|
135
|
+
isValid: boolean;
|
|
136
|
+
draftRestored: boolean;
|
|
137
|
+
fileRefs: Record<string, string[]>;
|
|
138
|
+
setField: <K extends keyof z.infer<T>>(field: K, value: z.infer<T>[K]) => void;
|
|
139
|
+
setFields: (fields: Partial<z.infer<T>>) => void;
|
|
140
|
+
validateField: <K extends keyof z.infer<T>>(field: K) => boolean;
|
|
141
|
+
validate: () => boolean;
|
|
142
|
+
handleSubmit: (event?: React.FormEvent) => Promise<void>;
|
|
143
|
+
reset: () => void;
|
|
144
|
+
clearErrors: () => void;
|
|
145
|
+
setError: <K extends keyof z.infer<T>>(field: K, message: string) => void;
|
|
146
|
+
setGlobalError: (message: string | null) => void;
|
|
147
|
+
clearDraft: () => Promise<void>;
|
|
148
|
+
dismissDraftNotification: () => void;
|
|
149
|
+
updateFileRefs: (fieldName: string, fileIds: string[]) => void;
|
|
150
|
+
getFilesForSubmit: () => Promise<Record<string, File[]>>;
|
|
151
|
+
/** Current draft ID (multi-draft mode) */
|
|
152
|
+
currentDraftId: string | null;
|
|
153
|
+
/** Current draft metadata (multi-draft mode) */
|
|
154
|
+
currentDraftMetadata: DraftMetadata | null;
|
|
155
|
+
/** Save current data as a new draft */
|
|
156
|
+
saveAsNewDraft: (name?: string) => Promise<DraftMetadata>;
|
|
157
|
+
/** Load a specific draft */
|
|
158
|
+
loadDraftById: (draftId: string) => Promise<boolean>;
|
|
159
|
+
}
|
|
160
|
+
declare function usePersistedForm<T extends z.ZodObject<z.ZodRawShape>>(options: UsePersistedFormOptions<T>): UsePersistedFormReturn<T>;
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* useOfflineCache - React hook for caching data
|
|
164
|
+
*
|
|
165
|
+
* @example
|
|
166
|
+
* ```tsx
|
|
167
|
+
* import { useOfflineCache } from '@classic-homes/offline-react';
|
|
168
|
+
*
|
|
169
|
+
* function UserProfile() {
|
|
170
|
+
* const userCache = useOfflineCache<User>({
|
|
171
|
+
* key: 'current-user',
|
|
172
|
+
* ttl: 60 * 60 * 1000,
|
|
173
|
+
* staleWhileRevalidate: true,
|
|
174
|
+
* });
|
|
175
|
+
*
|
|
176
|
+
* useEffect(() => {
|
|
177
|
+
* userCache.get(() => fetchCurrentUser());
|
|
178
|
+
* }, []);
|
|
179
|
+
*
|
|
180
|
+
* if (userCache.isLoading) return <Spinner />;
|
|
181
|
+
* if (userCache.data) return <Profile user={userCache.data} />;
|
|
182
|
+
* }
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
interface UseOfflineCacheOptions {
|
|
186
|
+
key: string;
|
|
187
|
+
ttl?: number;
|
|
188
|
+
tags?: string[];
|
|
189
|
+
staleWhileRevalidate?: boolean;
|
|
190
|
+
staleTime?: number;
|
|
191
|
+
}
|
|
192
|
+
interface UseOfflineCacheReturn<T> {
|
|
193
|
+
data: T | null;
|
|
194
|
+
isLoading: boolean;
|
|
195
|
+
isStale: boolean;
|
|
196
|
+
error: Error | null;
|
|
197
|
+
ttlRemaining: number | null;
|
|
198
|
+
get: (fetcher: () => Promise<T>) => Promise<T>;
|
|
199
|
+
set: (value: T) => Promise<void>;
|
|
200
|
+
invalidate: () => Promise<void>;
|
|
201
|
+
refresh: (fetcher: () => Promise<T>) => Promise<T>;
|
|
202
|
+
has: () => Promise<boolean>;
|
|
203
|
+
}
|
|
204
|
+
declare function useOfflineCache<T>(options: UseOfflineCacheOptions): UseOfflineCacheReturn<T>;
|
|
205
|
+
/**
|
|
206
|
+
* Invalidate cache entries by tag
|
|
207
|
+
*/
|
|
208
|
+
declare function invalidateCacheByTag(tag: string): Promise<number>;
|
|
209
|
+
/**
|
|
210
|
+
* Invalidate all cache entries
|
|
211
|
+
*/
|
|
212
|
+
declare function invalidateAllCache(): Promise<number>;
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* useDraftManager - React hook for multi-draft management
|
|
216
|
+
*
|
|
217
|
+
* @example
|
|
218
|
+
* ```tsx
|
|
219
|
+
* import { useDraftManager } from '@classic-homes/offline-react';
|
|
220
|
+
*
|
|
221
|
+
* function DraftList() {
|
|
222
|
+
* const manager = useDraftManager({ formKey: 'contact-form' });
|
|
223
|
+
*
|
|
224
|
+
* async function handleNewDraft() {
|
|
225
|
+
* const draft = await manager.createDraft({ name: 'New Contact' });
|
|
226
|
+
* manager.selectDraft(draft.id);
|
|
227
|
+
* }
|
|
228
|
+
*
|
|
229
|
+
* return (
|
|
230
|
+
* <ul>
|
|
231
|
+
* {manager.drafts.map((draft) => (
|
|
232
|
+
* <li key={draft.id} className={draft.id === manager.selectedDraftId ? 'selected' : ''}>
|
|
233
|
+
* <button onClick={() => manager.selectDraft(draft.id)}>
|
|
234
|
+
* {draft.name}
|
|
235
|
+
* </button>
|
|
236
|
+
* <button onClick={() => manager.deleteDraft(draft.id)}>Delete</button>
|
|
237
|
+
* </li>
|
|
238
|
+
* ))}
|
|
239
|
+
* </ul>
|
|
240
|
+
* );
|
|
241
|
+
* }
|
|
242
|
+
* ```
|
|
243
|
+
*/
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Options for useDraftManager
|
|
247
|
+
*/
|
|
248
|
+
interface UseDraftManagerOptions {
|
|
249
|
+
/** Filter drafts by form key */
|
|
250
|
+
formKey?: string;
|
|
251
|
+
/** Auto-load drafts on initialization */
|
|
252
|
+
autoLoad?: boolean;
|
|
253
|
+
/** Sort field for draft list */
|
|
254
|
+
sortBy?: 'createdAt' | 'updatedAt' | 'name';
|
|
255
|
+
/** Sort direction */
|
|
256
|
+
sortOrder?: 'asc' | 'desc';
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Return type for useDraftManager
|
|
260
|
+
*/
|
|
261
|
+
interface UseDraftManagerReturn {
|
|
262
|
+
/** List of draft metadata */
|
|
263
|
+
drafts: DraftMetadata[];
|
|
264
|
+
/** Whether drafts are being loaded */
|
|
265
|
+
isLoading: boolean;
|
|
266
|
+
/** Current error if any */
|
|
267
|
+
error: string | null;
|
|
268
|
+
/** Currently selected draft ID */
|
|
269
|
+
selectedDraftId: string | null;
|
|
270
|
+
/** Number of drafts */
|
|
271
|
+
count: number;
|
|
272
|
+
/** Create a new draft */
|
|
273
|
+
createDraft: (options?: CreateDraftOptions) => Promise<DraftMetadata>;
|
|
274
|
+
/** Load a draft by ID */
|
|
275
|
+
loadDraft: <T = Record<string, unknown>>(draftId: string) => Promise<StoredDraftV2<T> | null>;
|
|
276
|
+
/** Rename a draft */
|
|
277
|
+
renameDraft: (draftId: string, name: string) => Promise<void>;
|
|
278
|
+
/** Delete a draft */
|
|
279
|
+
deleteDraft: (draftId: string) => Promise<void>;
|
|
280
|
+
/** Duplicate a draft */
|
|
281
|
+
duplicateDraft: (draftId: string, newName?: string) => Promise<DraftMetadata | null>;
|
|
282
|
+
/** Select a draft */
|
|
283
|
+
selectDraft: (draftId: string | null) => void;
|
|
284
|
+
/** Refresh the draft list */
|
|
285
|
+
refresh: () => Promise<void>;
|
|
286
|
+
/** Clear all drafts for the form key */
|
|
287
|
+
clearAll: () => Promise<void>;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* React hook for multi-draft management
|
|
291
|
+
*/
|
|
292
|
+
declare function useDraftManager(options?: UseDraftManagerOptions): UseDraftManagerReturn;
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* useDraftSync - React hook for cloud sync management
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* ```tsx
|
|
299
|
+
* import { useDraftSync } from '@classic-homes/offline-react';
|
|
300
|
+
*
|
|
301
|
+
* function SyncStatus() {
|
|
302
|
+
* // Create a sync adapter (implement SyncAdapter interface)
|
|
303
|
+
* const adapter = useMemo(() => createMySyncAdapter(), []);
|
|
304
|
+
*
|
|
305
|
+
* const sync = useDraftSync({
|
|
306
|
+
* adapter,
|
|
307
|
+
* autoSync: true,
|
|
308
|
+
* });
|
|
309
|
+
*
|
|
310
|
+
* return (
|
|
311
|
+
* <div>
|
|
312
|
+
* <span>Status: {sync.isOnline ? 'Online' : 'Offline'}</span>
|
|
313
|
+
* {sync.isSyncing && <span>Syncing...</span>}
|
|
314
|
+
* {sync.pendingCount > 0 && <span>{sync.pendingCount} pending</span>}
|
|
315
|
+
*
|
|
316
|
+
* {sync.conflicts.length > 0 && (
|
|
317
|
+
* <div>
|
|
318
|
+
* <h3>Conflicts</h3>
|
|
319
|
+
* {sync.conflicts.map((conflict) => (
|
|
320
|
+
* <div key={conflict.localDraftId}>
|
|
321
|
+
* <span>{conflict.localDraft.metadata.name}</span>
|
|
322
|
+
* <button onClick={() => sync.resolveConflict(conflict.localDraftId, 'keep-local')}>
|
|
323
|
+
* Keep Local
|
|
324
|
+
* </button>
|
|
325
|
+
* <button onClick={() => sync.resolveConflict(conflict.localDraftId, 'keep-remote')}>
|
|
326
|
+
* Keep Remote
|
|
327
|
+
* </button>
|
|
328
|
+
* </div>
|
|
329
|
+
* ))}
|
|
330
|
+
* </div>
|
|
331
|
+
* )}
|
|
332
|
+
* </div>
|
|
333
|
+
* );
|
|
334
|
+
* }
|
|
335
|
+
* ```
|
|
336
|
+
*/
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Options for useDraftSync
|
|
340
|
+
*/
|
|
341
|
+
interface UseDraftSyncOptions {
|
|
342
|
+
/** Sync adapter implementation */
|
|
343
|
+
adapter: SyncAdapter;
|
|
344
|
+
/** Enable auto-sync on interval */
|
|
345
|
+
autoSync?: boolean;
|
|
346
|
+
/** Auto-sync interval in milliseconds (default: 30000) */
|
|
347
|
+
syncIntervalMs?: number;
|
|
348
|
+
/** Auto-sync when coming back online */
|
|
349
|
+
autoSyncOnReconnect?: boolean;
|
|
350
|
+
/** Callback when sync completes */
|
|
351
|
+
onSyncComplete?: (result: SyncResult) => void;
|
|
352
|
+
/** Callback when conflicts are detected */
|
|
353
|
+
onConflictDetected?: (conflicts: DraftConflict[]) => void;
|
|
354
|
+
/** Callback when online status changes */
|
|
355
|
+
onOnlineStatusChange?: (online: boolean) => void;
|
|
356
|
+
/** Callback for sync errors */
|
|
357
|
+
onSyncError?: (error: Error) => void;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Return type for useDraftSync
|
|
361
|
+
*/
|
|
362
|
+
interface UseDraftSyncReturn {
|
|
363
|
+
/** Whether device is online */
|
|
364
|
+
isOnline: boolean;
|
|
365
|
+
/** Whether sync is in progress */
|
|
366
|
+
isSyncing: boolean;
|
|
367
|
+
/** Timestamp of last successful sync */
|
|
368
|
+
lastSyncAt: number | null;
|
|
369
|
+
/** Current conflicts */
|
|
370
|
+
conflicts: DraftConflict[];
|
|
371
|
+
/** Number of drafts pending sync */
|
|
372
|
+
pendingCount: number;
|
|
373
|
+
/** Last sync result */
|
|
374
|
+
lastResult: SyncResult | null;
|
|
375
|
+
/** Current error if any */
|
|
376
|
+
error: string | null;
|
|
377
|
+
/** Sync all drafts */
|
|
378
|
+
syncAll: () => Promise<SyncResult>;
|
|
379
|
+
/** Sync a specific draft */
|
|
380
|
+
syncDraft: (draftId: string) => Promise<SyncResult>;
|
|
381
|
+
/** Force push a draft (overwrite remote) */
|
|
382
|
+
forcePush: (draftId: string) => Promise<void>;
|
|
383
|
+
/** Force pull a draft (overwrite local) */
|
|
384
|
+
forcePull: (draftId: string) => Promise<void>;
|
|
385
|
+
/** Resolve a conflict */
|
|
386
|
+
resolveConflict: (draftId: string, resolution: ConflictResolution) => Promise<void>;
|
|
387
|
+
/** Start auto-sync */
|
|
388
|
+
startAutoSync: () => void;
|
|
389
|
+
/** Stop auto-sync */
|
|
390
|
+
stopAutoSync: () => void;
|
|
391
|
+
/** Dispose the sync service */
|
|
392
|
+
dispose: () => void;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* React hook for cloud sync management
|
|
396
|
+
*/
|
|
397
|
+
declare function useDraftSync(options: UseDraftSyncOptions): UseDraftSyncReturn;
|
|
398
|
+
|
|
399
|
+
export { type FieldErrors, type UseDraftManagerOptions, type UseDraftManagerReturn, type UseDraftSyncOptions, type UseDraftSyncReturn, type UseFileStorageOptions, type UseFileStorageReturn, type UseOfflineCacheOptions, type UseOfflineCacheReturn, type UsePersistedFormOptions, type UsePersistedFormReturn, invalidateAllCache, invalidateCacheByTag, useDraftManager, useDraftSync, useFileStorage, useOfflineCache, usePersistedForm };
|