@hvakr/firestate 0.1.4 → 0.1.6

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 CHANGED
@@ -33,35 +33,35 @@ Firestate provides a declarative, schema-first approach that eliminates boilerpl
33
33
  Firestate exposes two layers. Pick one based on what you're building:
34
34
 
35
35
  - **`createFirestate` + `doc` / `col`** (recommended for app code) — declare a Firestore resource (a document or collection) with a `path` template and a Zod `schema`, and the library generates one typed React hook per entry. In return you get:
36
- - the data type (`TaskList`) inferred from the schema via `z.infer`
37
- - the param keys (`{ listId }`) inferred from the path template and enforced at call sites
38
- - runtime validation on `set` / `add` writes — bad data throws at the call site instead of after a Firestore round trip
36
+ - the data type (`TaskList`) inferred from the schema via `z.infer`
37
+ - the param keys (`{ listId }`) inferred from the path template and enforced at call sites
38
+ - runtime validation on `set` / `add` writes — bad data throws at the call site instead of after a Firestore round trip
39
39
 
40
- Partial `update(diff)` calls are intentionally NOT validated: diffs commonly include Firestore sentinels like `serverTimestamp()` that a strict schema would reject.
40
+ Partial `update(diff)` calls are intentionally NOT validated: diffs commonly include Firestore sentinels like `serverTimestamp()` that a strict schema would reject.
41
41
 
42
- Treat `createFirestate` as a **per-resource hook factory**, not an app-wide registry: give each document/collection its own module (`firestore/taskList.ts`, `firestore/tasks.ts`, …) with one `createFirestate` call, and export the hooks flat. See [Organizing by resource](#organizing-by-resource).
42
+ Treat `createFirestate` as a **per-resource hook factory**, not an app-wide registry: give each document/collection its own module (`firestore/taskList.ts`, `firestore/tasks.ts`, …) with one `createFirestate` call, and export the hooks flat. See [Organizing by resource](#organizing-by-resource).
43
43
 
44
- ```ts
45
- // firestore/taskList.ts
46
- import { z } from 'zod'
47
- import { createFirestate, doc } from '@hvakr/firestate'
44
+ ```ts
45
+ // firestore/taskList.ts
46
+ import { z } from 'zod'
47
+ import { createFirestate, doc } from '@hvakr/firestate'
48
48
 
49
- const TaskListSchema = z.object({ name: z.string(), createdAt: z.number() })
49
+ const TaskListSchema = z.object({ name: z.string(), createdAt: z.number() })
50
50
 
51
- const taskList = doc({ path: 'taskLists/{listId}', schema: TaskListSchema })
51
+ const taskList = doc({ path: 'taskLists/{listId}', schema: TaskListSchema })
52
52
 
53
- export const { useTaskList } = createFirestate({ taskList })
53
+ export const { useTaskList } = createFirestate({ taskList })
54
54
 
55
- // useTaskList({ listId }) — { listId: string } statically required
56
- // useTaskList() — type error: missing listId
57
- // useTaskList({ wrong: 'a' }) — type error: wrong key
58
- ```
55
+ // useTaskList({ listId }) — { listId: string } statically required
56
+ // useTaskList() — type error: missing listId
57
+ // useTaskList({ wrong: 'a' }) — type error: wrong key
58
+ ```
59
59
 
60
60
  - **`defineDocument` / `defineCollection` + `useDocument` / `useCollection`** (lower-level escape hatch) — write the path-derivation function yourself, use the standalone hooks. Reach for these when:
61
- - your path doesn't fit the `{name}` template (computed from non-string state, conditional segments)
62
- - you need the definition outside React (Node scripts, server-side, tests)
63
- - your control flow doesn't fit a module-level registry
64
- - you want plain TypeScript types without a Zod schema (the schema field is optional here)
61
+ - your path doesn't fit the `{name}` template (computed from non-string state, conditional segments)
62
+ - you need the definition outside React (Node scripts, server-side, tests)
63
+ - your control flow doesn't fit a module-level registry
64
+ - you want plain TypeScript types without a Zod schema (the schema field is optional here)
65
65
 
66
66
  Both layers share the same store, undo manager, and sync semantics — the registry is a thin layer on top of the lower-level primitives.
67
67
 
@@ -74,12 +74,16 @@ Both layers share the same store, undo manager, and sync semantics — the regis
74
74
  import { z } from 'zod'
75
75
  import { createFirestate, col } from '@hvakr/firestate'
76
76
 
77
- const TaskSchema = z.object({ title: z.string(), completed: z.boolean(), createdAt: z.number() })
77
+ const TaskSchema = z.object({
78
+ title: z.string(),
79
+ completed: z.boolean(),
80
+ createdAt: z.number(),
81
+ })
78
82
  const tasks = col({ path: 'taskLists/{listId}/tasks', schema: TaskSchema })
79
83
 
80
84
  export const { useTasks, useTaskById } = createFirestate({
81
- tasks, // → useTasks (full handle)
82
- taskById: tasks.select((s, p: { id: string }) => s.data[p.id]),
85
+ tasks, // → useTasks (full handle)
86
+ taskById: tasks.select((s, p: { id: string }) => s.data[p.id]),
83
87
  })
84
88
 
85
89
  // firestore/taskList.ts is a sibling module with its own createFirestate call.
@@ -89,10 +93,10 @@ export const { useTasks, useTaskById } = createFirestate({
89
93
  Why per-resource rather than one central call:
90
94
 
91
95
  - **It scales.** A central registry becomes a chokepoint every feature edits; resource modules keep a resource's schema, hooks, and slices colocated and let you code-split.
92
- - **Sharing still works app-wide.** Subscriptions are keyed by *definition identity*, and a resource module's definition lives at module scope (one stable object), so every component using `useTasks`/`useTaskById` shares one `onSnapshot` listener and one optimistic state — no matter how many modules.
96
+ - **Sharing still works app-wide.** Subscriptions are keyed by _definition identity_, and a resource module's definition lives at module scope (one stable object), so every component using `useTasks`/`useTaskById` shares one `onSnapshot` listener and one optimistic state — no matter how many modules.
93
97
  - **The store stays global.** All resource modules mount under one `FirestateProvider`, so undo/redo and sync tracking span every resource regardless of how you split the files.
94
98
 
95
- **The one rule:** keep a resource's base hook *and* all its `.select` slices in the **same** `createFirestate` call. Each call builds its own definitions, so splitting one resource across two calls would fork it into two listeners. Separate *resources* in separate calls is exactly what you want; separating *one* resource is the mistake.
99
+ **The one rule:** keep a resource's base hook _and_ all its `.select` slices in the **same** `createFirestate` call. Each call builds its own definitions, so splitting one resource across two calls would fork it into two listeners. Separate _resources_ in separate calls is exactly what you want; separating _one_ resource is the mistake.
96
100
 
97
101
  ## Table of Contents
98
102
 
@@ -125,9 +129,9 @@ Firestate requires the following peer dependencies:
125
129
 
126
130
  ```json
127
131
  {
128
- "firebase": "^10.0.0 || ^11.0.0",
129
- "react": "^18.0.0 || ^19.0.0",
130
- "zod": "^4.0.0"
132
+ "firebase": "^10.0.0 || ^11.0.0",
133
+ "react": "^18.0.0 || ^19.0.0",
134
+ "zod": "^4.0.0"
131
135
  }
132
136
  ```
133
137
 
@@ -205,11 +209,7 @@ import { db } from './firebase'
205
209
 
206
210
  function App() {
207
211
  return (
208
- <FirestateProvider
209
- firestore={db}
210
- autosave={1000}
211
- maxUndoLength={20}
212
- >
212
+ <FirestateProvider firestore={db} autosave={1000} maxUndoLength={20}>
213
213
  <YourApp />
214
214
  </FirestateProvider>
215
215
  )
@@ -241,7 +241,10 @@ function ProjectEditor({ projectId }: { projectId: string }) {
241
241
 
242
242
  // Opt into save state only where you render it — shares the project's one
243
243
  // listener, so it doesn't add a subscription.
244
- const { isSaving } = useDocumentSyncStatus({ definition: projectDoc, params })
244
+ const { isSaving } = useDocumentSyncStatus({
245
+ definition: projectDoc,
246
+ params,
247
+ })
245
248
 
246
249
  // Access undo/redo
247
250
  const { undo, redo, canUndo, canRedo } = useUndoManager()
@@ -252,8 +255,12 @@ function ProjectEditor({ projectId }: { projectId: string }) {
252
255
  return (
253
256
  <div>
254
257
  {/* Undo/Redo buttons */}
255
- <button onClick={undo} disabled={!canUndo}>Undo</button>
256
- <button onClick={redo} disabled={!canRedo}>Redo</button>
258
+ <button onClick={undo} disabled={!canUndo}>
259
+ Undo
260
+ </button>
261
+ <button onClick={redo} disabled={!canRedo}>
262
+ Redo
263
+ </button>
257
264
 
258
265
  {/* Edit project name - changes auto-save */}
259
266
  <input
@@ -343,6 +350,9 @@ project.update({ name: 'New Name' }, { undoGroupId: groupId })
343
350
  spaces.update({ space1: { name: 'Updated' } }, { undoGroupId: groupId })
344
351
  ```
345
352
 
353
+ Grouped actions undo newest-first and redo oldest-first, so one undo/redo
354
+ always applies the complete group in write order.
355
+
346
356
  To skip undo tracking:
347
357
 
348
358
  ```tsx
@@ -365,6 +375,12 @@ function App() {
365
375
  <FirestateProvider
366
376
  firestore={db}
367
377
  onNavigate={(path) => navigate(path)}
378
+ onUndo={(action) =>
379
+ analytics.track('undo', { description: action.description })
380
+ }
381
+ onRedo={(action) =>
382
+ analytics.track('redo', { description: action.description })
383
+ }
368
384
  >
369
385
  {children}
370
386
  </FirestateProvider>
@@ -387,10 +403,39 @@ Actions record a path via the `path` field on `UndoAction`:
387
403
  undoManager.push({
388
404
  undo: () => restoreValue(),
389
405
  redo: () => applyValue(),
390
- path: '/projects/123', // navigate here on undo/redo
406
+ path: '/projects/123', // navigate here on undo/redo
391
407
  })
392
408
  ```
393
409
 
410
+ Undo actions pushed by a normal handle write (`update`/`add`/`remove`) can't set
411
+ `path` at the call site, so on their own they never trigger `onNavigate`. Give
412
+ the store a `getUndoPath` callback and it stamps the current router path onto
413
+ every handle-pushed action, so navigation-aware undo works for ordinary writes —
414
+ not just manual `undoManager.push({ path })`. Read the path from your router:
415
+
416
+ ```tsx
417
+ import { useLocation, useNavigate } from 'react-router-dom'
418
+
419
+ function App() {
420
+ const location = useLocation()
421
+ const navigate = useNavigate()
422
+
423
+ return (
424
+ <FirestateProvider
425
+ firestore={db}
426
+ getUndoPath={() => location.pathname}
427
+ onNavigate={(path) => navigate(path)}
428
+ >
429
+ {children}
430
+ </FirestateProvider>
431
+ )
432
+ }
433
+ ```
434
+
435
+ `getUndoPath` also works on `createStore({ firestore: db, getUndoPath: () => router.currentPath })`.
436
+ Return `undefined` to leave an action pathless. When actions merge into one undo
437
+ group, the merged group keeps the newest action's path.
438
+
394
439
  ### Lazy Collections
395
440
 
396
441
  For large applications, you may not want to subscribe to every collection immediately:
@@ -499,10 +544,7 @@ Use the second argument for hook options such as `enabled`, `readOnly`,
499
544
  ```tsx
500
545
  const spaces = useSpaces(
501
546
  { projectId },
502
- {
503
- enabled: Boolean(projectId),
504
- queryConstraints,
505
- }
547
+ { enabled: Boolean(projectId), queryConstraints }
506
548
  )
507
549
  ```
508
550
 
@@ -594,14 +636,14 @@ type parameter, or let it be inferred from a Zod schema.
594
636
 
595
637
  ```typescript
596
638
  const projectDoc = defineDocument<Project>({
597
- collection: 'projects', // Collection path
598
- id: (params) => params.id, // Document ID (string or function)
599
- autosave: 1000, // Optional: debounce interval (ms)
600
- minLoadTime: 0, // Optional: minimum loading time (ms)
601
- readOnly: false, // Optional: prevent updates
602
- retryOnError: false, // Optional: retry on listener errors
603
- retryInterval: 5000, // Optional: retry interval (ms)
604
- schema: ProjectSchema, // Optional: Zod schema (validates set/add)
639
+ collection: 'projects', // Collection path
640
+ id: (params) => params.id, // Document ID (string or function)
641
+ autosave: 1000, // Optional: debounce interval (ms)
642
+ minLoadTime: 0, // Optional: minimum loading time (ms)
643
+ readOnly: false, // Optional: prevent updates
644
+ retryOnError: false, // Optional: retry on listener errors
645
+ retryInterval: 5000, // Optional: retry interval (ms)
646
+ schema: ProjectSchema, // Optional: Zod schema (validates set/add)
605
647
  })
606
648
  ```
607
649
 
@@ -612,12 +654,12 @@ Creates a collection definition.
612
654
  ```typescript
613
655
  const spacesCollection = defineCollection<Space>({
614
656
  path: (params) => `projects/${params.id}/spaces`, // Collection path
615
- autosave: 1000, // Optional: debounce interval
616
- minLoadTime: 0, // Optional: minimum loading time
617
- readOnly: false, // Optional: prevent updates
618
- lazy: false, // Optional: defer subscription
619
- queryConstraints: [], // Optional: Firestore constraints
620
- schema: SpaceSchema, // Optional: Zod schema (validates add)
657
+ autosave: 1000, // Optional: debounce interval
658
+ minLoadTime: 0, // Optional: minimum loading time
659
+ readOnly: false, // Optional: prevent updates
660
+ lazy: false, // Optional: defer subscription
661
+ queryConstraints: [], // Optional: Firestore constraints
662
+ schema: SpaceSchema, // Optional: Zod schema (validates add)
621
663
  })
622
664
  ```
623
665
 
@@ -629,20 +671,20 @@ Subscribe to a document.
629
671
 
630
672
  ```typescript
631
673
  const {
632
- data, // Current document data (T | undefined)
633
- update, // Update with partial diff
634
- set, // Replace entire document
635
- delete: del, // Delete the document
636
- isLoaded, // Whether the initial snapshot has arrived (ready to render)
637
- sync, // Force sync immediately
638
- error, // Error from listener, if any
639
- ref, // Firestore DocumentReference
674
+ data, // Current document data (T | undefined)
675
+ update, // Update with partial diff
676
+ set, // Replace entire document
677
+ delete: del, // Delete the document
678
+ isLoaded, // Whether the initial snapshot has arrived (ready to render)
679
+ sync, // Force sync immediately
680
+ error, // Error from listener, if any
681
+ ref, // Firestore DocumentReference
640
682
  } = useDocument({
641
683
  definition: projectDoc,
642
684
  params: { projectId: '123' },
643
- readOnly: false, // Optional: override read-only
644
- undoable: true, // Optional: enable undo (default: true)
645
- enabled: true, // Optional: set false until required params exist
685
+ readOnly: false, // Optional: override read-only
686
+ undoable: true, // Optional: enable undo (default: true)
687
+ enabled: true, // Optional: set false until required params exist
646
688
  })
647
689
 
648
690
  // The default handle is SYNC-AGNOSTIC: no `isSynced`, so a save settling does
@@ -658,22 +700,22 @@ Subscribe to a collection.
658
700
 
659
701
  ```typescript
660
702
  const {
661
- data, // Record<string, T> of documents
662
- update, // Update one or more documents
663
- add, // Add a new document (explicit or auto-generated id)
664
- remove, // Remove a document
665
- isLoaded, // Active AND past the initial load (isActive && !isLoading)
666
- isActive, // Whether subscription is active (for lazy collections)
667
- load, // Activate a lazy subscription
668
- sync, // Force sync immediately
669
- error, // Error from listener, if any
670
- ref, // Firestore CollectionReference
703
+ data, // Record<string, T> of documents
704
+ update, // Update one or more documents
705
+ add, // Add a new document (explicit or auto-generated id)
706
+ remove, // Remove a document
707
+ isLoaded, // Active AND past the initial load (isActive && !isLoading)
708
+ isActive, // Whether subscription is active (for lazy collections)
709
+ load, // Activate a lazy subscription
710
+ sync, // Force sync immediately
711
+ error, // Error from listener, if any
712
+ ref, // Firestore CollectionReference
671
713
  } = useCollection({
672
714
  definition: spacesCollection,
673
715
  params: { projectId: '123' },
674
716
  queryConstraints: [where('floor', '==', 1)],
675
717
  undoable: true,
676
- enabled: true, // Optional: set false until required params exist
718
+ enabled: true, // Optional: set false until required params exist
677
719
  })
678
720
 
679
721
  // queryConstraints are keyed by query identity, not array reference: the
@@ -708,7 +750,7 @@ By default a component re-renders when the data, the load state (`isLoaded`), or
708
750
  **sync-agnostic default handle** (`data`, `isLoaded`, `error`, the writers, and
709
751
  `ref` — plus a collection's `isActive`). It deliberately omits `isSynced`, so a
710
752
  save settling does not re-render it (see [Sync status and loading status](#sync-status-and-loading-status)).
711
- Pass a `selector` to take further control: it receives the resource's *full*
753
+ Pass a `selector` to take further control: it receives the resource's _full_
712
754
  observable state — including `isLoading`/`isSynced` — and returns the slice the
713
755
  component reacts to, so the component re-renders **only** when that slice changes.
714
756
 
@@ -716,7 +758,7 @@ A selected handle exposes exactly your slice as `data`, plus the writer surface
716
758
  (`update`/`set`/`delete`/`add`/`remove`/`load`/`sync`) and `ref` — the status
717
759
  flags are **not** on it. You react to precisely what you select; status is not a
718
760
  freebie, so read it from the state inside the selector when you need it. A
719
- selector changes what you *read*, never what you *write*.
761
+ selector changes what you _read_, never what you _write_.
720
762
 
721
763
  ```typescript
722
764
  // Re-renders only when the title changes — not on any other field, and not on a
@@ -746,7 +788,7 @@ const { data: space } = useCollection({
746
788
  `s.data` is `undefined` while a document is loading (and the collection record is
747
789
  `{}`), so selectors should handle the empty case.
748
790
 
749
- When writing from a narrowed handle, use `update` — it takes a *partial* and
791
+ When writing from a narrowed handle, use `update` — it takes a _partial_ and
750
792
  merges, so a selected field is just `update({ field: next })`. `set` still
751
793
  **replaces the entire document**, not the slice: never pass the selected value
752
794
  to `set` (e.g. `set(title)`) or you will overwrite every other field. Reach for
@@ -784,7 +826,7 @@ optimistic edits live. Only the read-only handle's own writers are disabled.
784
826
  #### Sync status and loading status
785
827
 
786
828
  The default data handle is **sync-agnostic**: it carries `data`/`isLoaded`/
787
- `error` but never `isSynced`. That matters because `isSynced` flips on *every*
829
+ `error` but never `isSynced`. That matters because `isSynced` flips on _every_
788
830
  autosave settle — so if the data handle carried it, every component that merely
789
831
  reads a record would re-render an extra time after each save. Most readers only
790
832
  want the data; the few that render save state (a "Saving…" indicator, a
@@ -818,7 +860,7 @@ on the load transition, never on data. Collection status hooks take the same
818
860
  `queryConstraints` as the data hook (pass the same query to share the listener).
819
861
 
820
862
  On a **lazy** collection, a status hook does not call `load()` itself — so as
821
- the *only* subscriber it stays idle (`{ isSynced: true, isSaving: false }` /
863
+ the _only_ subscriber it stays idle (`{ isSynced: true, isSaving: false }` /
822
864
  `{ isLoading: false, isLoaded: false }`) and attaches no listener. Pair it with
823
865
  the data hook, whose `load()` activates the one shared listener the status hook
824
866
  then rides. Non-lazy collections activate on mount, so this is lazy-only.
@@ -832,7 +874,7 @@ With the lower-level API there are standalone equivalents —
832
874
  `{ definition, params, enabled }` (collections also `queryConstraints`).
833
875
 
834
876
  This is the per-resource counterpart to [`useIsSynced()`](#useissynced), which
835
- reports a single provider-wide aggregate across *all* tracked resources.
877
+ reports a single provider-wide aggregate across _all_ tracked resources.
836
878
 
837
879
  #### `useUndoManager()`
838
880
 
@@ -840,13 +882,13 @@ Access the undo manager.
840
882
 
841
883
  ```typescript
842
884
  const {
843
- canUndo, // Whether undo is available
844
- canRedo, // Whether redo is available
845
- undo, // Undo the last action
846
- redo, // Redo the last undone action
847
- clear, // Clear undo/redo history
848
- undoStack, // Array of undo actions
849
- redoStack, // Array of redo actions
885
+ canUndo, // Whether undo is available
886
+ canRedo, // Whether redo is available
887
+ undo, // Undo the last action
888
+ redo, // Redo the last undone action
889
+ clear, // Clear undo/redo history
890
+ undoStack, // Array of undo actions
891
+ redoStack, // Array of redo actions
850
892
  } = useUndoManager()
851
893
  ```
852
894
 
@@ -874,11 +916,18 @@ Main provider component.
874
916
 
875
917
  ```tsx
876
918
  <FirestateProvider
877
- firestore={db} // Required: Firestore instance
878
- autosave={1000} // Optional: default debounce (ms)
879
- minLoadTime={0} // Optional: minimum loading time (ms)
880
- maxUndoLength={20} // Optional: max undo stack size
881
- onNavigate={(path) => navigate(path)} // Optional: router navigate for path-aware undo/redo
919
+ firestore={db} // Required: Firestore instance
920
+ autosave={1000} // Optional: default debounce (ms)
921
+ minLoadTime={0} // Optional: minimum loading time (ms)
922
+ maxUndoLength={20} // Optional: max undo stack size
923
+ getUndoPath={() => location.pathname} // Optional: stamp router path onto handle-pushed undo actions
924
+ onNavigate={(path) => navigate(path)} // Optional: router navigate for path-aware undo/redo
925
+ onUndo={(action) =>
926
+ analytics.track('undo', { description: action.description })
927
+ }
928
+ onRedo={(action) =>
929
+ analytics.track('redo', { description: action.description })
930
+ }
882
931
  onError={(error, context) => {
883
932
  // Optional: custom error handler
884
933
  console.error(context.path, error)
@@ -948,7 +997,11 @@ const restored = unflattenDiff(flat)
948
997
  ### Path-Based Utilities
949
998
 
950
999
  ```typescript
951
- import { diffContainsPath, extractDiffValue, createDiffAtPath } from '@hvakr/firestate'
1000
+ import {
1001
+ diffContainsPath,
1002
+ extractDiffValue,
1003
+ createDiffAtPath,
1004
+ } from '@hvakr/firestate'
952
1005
 
953
1006
  const diff = { building: { floors: 5 }, name: 'Test' }
954
1007
 
@@ -967,7 +1020,12 @@ createDiffAtPath('building.config.enabled', true)
967
1020
  ### General Utilities
968
1021
 
969
1022
  ```typescript
970
- import { isDeepEqual, deepClone, isDiffEmpty, mergeDiffs } from '@hvakr/firestate'
1023
+ import {
1024
+ isDeepEqual,
1025
+ deepClone,
1026
+ isDiffEmpty,
1027
+ mergeDiffs,
1028
+ } from '@hvakr/firestate'
971
1029
 
972
1030
  // Deep equality check (handles Timestamps, arrays, nested objects)
973
1031
  isDeepEqual(obj1, obj2)
@@ -1005,8 +1063,15 @@ const store = createStore({
1005
1063
  maxUndoLength: 50,
1006
1064
  onError: (error, context) => {
1007
1065
  // Send to error tracking service
1066
+ if (context.type === 'undo') {
1067
+ analytics.track('undo_error', { operation: context.operation })
1068
+ }
1008
1069
  Sentry.captureException(error, { extra: context })
1009
- }
1070
+ },
1071
+ onUndo: (action) =>
1072
+ analytics.track('undo', { description: action.description }),
1073
+ onRedo: (action) =>
1074
+ analytics.track('redo', { description: action.description }),
1010
1075
  })
1011
1076
 
1012
1077
  const subscription = createDocumentSubscription({
@@ -1035,13 +1100,17 @@ import { createUndoManager } from '@hvakr/firestate'
1035
1100
  const undoManager = createUndoManager({
1036
1101
  maxLength: 50,
1037
1102
  onNavigate: (path) => router.push(path),
1103
+ onUndo: (action) =>
1104
+ analytics.track('undo', { description: action.description }),
1105
+ onRedo: (action) =>
1106
+ analytics.track('redo', { description: action.description }),
1038
1107
  })
1039
1108
 
1040
1109
  undoManager.push({
1041
1110
  undo: () => restoreOldValue(),
1042
1111
  redo: () => applyNewValue(),
1043
1112
  groupId: 'myGroup',
1044
- path: '/projects/123', // Navigate here on undo/redo
1113
+ path: '/projects/123', // Navigate here on undo/redo
1045
1114
  description: 'Update project name',
1046
1115
  })
1047
1116
 
@@ -1210,8 +1279,14 @@ export const spacesCollection = defineCollection<Space>({
1210
1279
 
1211
1280
  // Component.tsx
1212
1281
  function ProjectEditor({ projectId }) {
1213
- const project = useDocument({ definition: projectDoc, params: { projectId } })
1214
- const spaces = useCollection({ definition: spacesCollection, params: { projectId } })
1282
+ const project = useDocument({
1283
+ definition: projectDoc,
1284
+ params: { projectId },
1285
+ })
1286
+ const spaces = useCollection({
1287
+ definition: spacesCollection,
1288
+ params: { projectId },
1289
+ })
1215
1290
  const isSynced = useIsSynced() // Automatic!
1216
1291
 
1217
1292
  // That's it. Undo/redo is automatic.
package/dist/index.d.mts CHANGED
@@ -153,8 +153,8 @@ interface CollectionHandle<T extends FirestoreObject> {
153
153
  * before using the id to navigate or persist references.
154
154
  */
155
155
  add: {
156
- (id: string, data: Omit<T, "id">, options?: UpdateOptions): string | undefined;
157
- (data: Omit<T, "id">, options?: UpdateOptions): string | undefined;
156
+ (id: string, data: Omit<T, 'id'>, options?: UpdateOptions): string | undefined;
157
+ (data: Omit<T, 'id'>, options?: UpdateOptions): string | undefined;
158
158
  };
159
159
  /** Remove a document from the collection */
160
160
  remove: (id: string, options?: UpdateOptions) => void;
@@ -179,8 +179,8 @@ interface CollectionHandle<T extends FirestoreObject> {
179
179
  ref: CollectionReference<T> | undefined;
180
180
  }
181
181
  /** Reactive status fields a selector drops unless it folds them into its slice. */
182
- type DocumentStatusKeys = "isLoaded" | "error";
183
- type CollectionStatusKeys = DocumentStatusKeys | "isActive";
182
+ type DocumentStatusKeys = 'isLoaded' | 'error';
183
+ type CollectionStatusKeys = DocumentStatusKeys | 'isActive';
184
184
  /**
185
185
  * A {@link DocumentHandle} reduced to a hook-level `selector`'s output. The
186
186
  * selector receives the full observable state ({@link DocumentState}) and
@@ -201,7 +201,7 @@ type CollectionStatusKeys = DocumentStatusKeys | "isActive";
201
201
  * to `set`, or you will overwrite every other field. Prefer `update` from a
202
202
  * narrowed handle; reach for `set` only when you hold the full document.
203
203
  */
204
- interface SelectedDocumentHandle<TData extends FirestoreObject, TSelected> extends Omit<DocumentHandle<TData>, "data" | DocumentStatusKeys> {
204
+ interface SelectedDocumentHandle<TData extends FirestoreObject, TSelected> extends Omit<DocumentHandle<TData>, 'data' | DocumentStatusKeys> {
205
205
  /** The slice produced by the hook's `selector`. */
206
206
  data: TSelected;
207
207
  }
@@ -214,7 +214,7 @@ interface SelectedDocumentHandle<TData extends FirestoreObject, TSelected> exten
214
214
  * folded into the slice. Writers stay typed against the full collection of
215
215
  * `TData`.
216
216
  */
217
- interface SelectedCollectionHandle<TData extends FirestoreObject, TSelected> extends Omit<CollectionHandle<TData>, "data" | CollectionStatusKeys> {
217
+ interface SelectedCollectionHandle<TData extends FirestoreObject, TSelected> extends Omit<CollectionHandle<TData>, 'data' | CollectionStatusKeys> {
218
218
  /** The slice produced by the hook's `selector`. */
219
219
  data: TSelected;
220
220
  }
@@ -347,6 +347,19 @@ interface FirestateConfig {
347
347
  * where a change occurred before reverting it.
348
348
  */
349
349
  onNavigate?: (path: string) => void;
350
+ /**
351
+ * Called when a handle write (`update`/`add`/`remove`) pushes an undo
352
+ * action, to stamp the current router path onto that action. The stamped
353
+ * `path` is what {@link FirestateConfig.onNavigate} later receives, so
354
+ * handle-driven undo can return the user to where the change happened
355
+ * before reverting it. Return `undefined` to leave the action pathless.
356
+ * Firestate can't know the router path itself — wire this to your router.
357
+ */
358
+ getUndoPath?: () => string | undefined;
359
+ /** Called after an undo action has been successfully applied. */
360
+ onUndo?: (action: UndoAction) => void;
361
+ /** Called after a redo action has been successfully applied. */
362
+ onRedo?: (action: UndoAction) => void;
350
363
  /** Custom error handler */
351
364
  onError?: (error: Error, context: ErrorContext) => void;
352
365
  }
@@ -354,9 +367,9 @@ interface FirestateConfig {
354
367
  * Context for error handling
355
368
  */
356
369
  interface ErrorContext {
357
- type: "document" | "collection";
370
+ type: 'document' | 'collection' | 'undo';
358
371
  path: string;
359
- operation: "read" | "write";
372
+ operation: 'read' | 'write' | 'undo' | 'redo';
360
373
  }
361
374
  /**
362
375
  * Subscriber callback type
@@ -462,6 +475,12 @@ interface UndoManagerConfig {
462
475
  maxLength?: number;
463
476
  /** Callback when navigation is requested (for path-aware undo) */
464
477
  onNavigate?: (path: string) => void;
478
+ /** Callback after an undo action has been successfully applied */
479
+ onUndo?: (action: UndoAction) => void;
480
+ /** Callback after a redo action has been successfully applied */
481
+ onRedo?: (action: UndoAction) => void;
482
+ /** Callback when an undo or redo action fails */
483
+ onError?: (error: Error, action: UndoAction, operation: 'undo' | 'redo') => void;
465
484
  }
466
485
  /**
467
486
  * Create an undo manager instance.
@@ -517,6 +536,22 @@ interface FirestateStore {
517
536
  * callback that changes reference on every render.
518
537
  */
519
538
  setOnNavigate: (handler?: (path: string) => void) => void;
539
+ /**
540
+ * Resolve the router path to stamp onto a handle-pushed undo action.
541
+ * Delegates to the config's `getUndoPath`; returns `undefined` when none
542
+ * is configured. Called by handle writers as they push undo actions.
543
+ */
544
+ getUndoPath: () => string | undefined;
545
+ /**
546
+ * Replace the undo-path resolver at runtime. Used by FirestateProvider to
547
+ * keep the store identity stable when consumers pass an inline
548
+ * `getUndoPath` callback that changes reference on every render.
549
+ */
550
+ setGetUndoPath: (handler?: () => string | undefined) => void;
551
+ /** Replace the successful-undo handler without recreating the store. */
552
+ setOnUndo: (handler?: (action: UndoAction) => void) => void;
553
+ /** Replace the successful-redo handler without recreating the store. */
554
+ setOnRedo: (handler?: (action: UndoAction) => void) => void;
520
555
  /** Subscribe to sync state changes */
521
556
  subscribeToSyncState: (fn: Subscriber<boolean>) => Unsubscribe;
522
557
  /** Report a document/collection sync state change */
@@ -1561,8 +1596,33 @@ interface FirestateProviderProps {
1561
1596
  * ```
1562
1597
  */
1563
1598
  onNavigate?: (path: string) => void;
1599
+ /**
1600
+ * Called when a handle write (`update`/`add`/`remove`) pushes an undo
1601
+ * action, to stamp the current router path onto it. That path is what
1602
+ * `onNavigate` later receives, so handle-driven undo can return users to
1603
+ * where a change occurred. Read the path from your router here.
1604
+ *
1605
+ * @example
1606
+ * ```tsx
1607
+ * import { useLocation } from 'react-router-dom'
1608
+ *
1609
+ * function App() {
1610
+ * const location = useLocation()
1611
+ * return (
1612
+ * <FirestateProvider getUndoPath={() => location.pathname}>
1613
+ * {children}
1614
+ * </FirestateProvider>
1615
+ * )
1616
+ * }
1617
+ * ```
1618
+ */
1619
+ getUndoPath?: () => string | undefined;
1564
1620
  /** Custom error handler */
1565
1621
  onError?: (error: Error, context: ErrorContext) => void;
1622
+ /** Called after an undo action has been successfully applied */
1623
+ onUndo?: (action: UndoAction) => void;
1624
+ /** Called after a redo action has been successfully applied */
1625
+ onRedo?: (action: UndoAction) => void;
1566
1626
  /** React children */
1567
1627
  children: React.ReactNode;
1568
1628
  }