@daltonr/pathwrite-core 0.2.1 → 0.4.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/README.md +373 -8
- package/dist/index.d.ts +112 -4
- package/dist/index.js +247 -33
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +330 -32
package/README.md
CHANGED
|
@@ -2,6 +2,39 @@
|
|
|
2
2
|
|
|
3
3
|
Headless path engine with zero dependencies. Manages step navigation, navigation guards, lifecycle hooks, and stack-based sub-path orchestration. Works equally well driving a UI wizard or a backend document lifecycle — no framework required.
|
|
4
4
|
|
|
5
|
+
## Quick Reference: Common Patterns
|
|
6
|
+
|
|
7
|
+
### ✅ Write Defensive Guards
|
|
8
|
+
```typescript
|
|
9
|
+
// Guards run BEFORE onEnter - always handle undefined data
|
|
10
|
+
canMoveNext: (ctx) => (ctx.data.name ?? "").trim().length > 0 // ✅ Safe
|
|
11
|
+
canMoveNext: (ctx) => ctx.data.name.trim().length > 0 // ❌ Crashes!
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
### ✅ Use `isFirstEntry` to Prevent Data Reset
|
|
15
|
+
```typescript
|
|
16
|
+
onEnter: (ctx) => {
|
|
17
|
+
if (ctx.isFirstEntry) {
|
|
18
|
+
return { items: [], status: "pending" }; // Initialize only on first visit
|
|
19
|
+
}
|
|
20
|
+
// Don't reset when user navigates back
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
### ✅ Correlate Sub-Paths with `meta`
|
|
25
|
+
```typescript
|
|
26
|
+
// Starting sub-path
|
|
27
|
+
engine.startSubPath(subPath, initialData, { itemIndex: i });
|
|
28
|
+
|
|
29
|
+
// In parent step
|
|
30
|
+
onSubPathComplete: (_id, subData, ctx, meta) => {
|
|
31
|
+
const index = meta?.itemIndex; // Correlate back to collection item
|
|
32
|
+
// ...
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
5
38
|
## Key types
|
|
6
39
|
|
|
7
40
|
```typescript
|
|
@@ -38,6 +71,7 @@ const path: PathDefinition<CourseData> = {
|
|
|
38
71
|
const engine = new PathEngine();
|
|
39
72
|
|
|
40
73
|
engine.start(definition, initialData?); // start or re-start a path
|
|
74
|
+
engine.restart(definition, initialData?); // tear down stack and start fresh (no hooks, no cancelled event)
|
|
41
75
|
engine.startSubPath(definition, data?); // push sub-path onto the stack (requires active path)
|
|
42
76
|
engine.next();
|
|
43
77
|
engine.previous();
|
|
@@ -47,6 +81,10 @@ engine.goToStep(stepId); // jump to step by ID; bypasses guard
|
|
|
47
81
|
engine.goToStepChecked(stepId); // jump to step by ID; checks canMoveNext / canMovePrevious first
|
|
48
82
|
engine.snapshot(); // returns PathSnapshot | null
|
|
49
83
|
|
|
84
|
+
// Serialization API (for persistence)
|
|
85
|
+
const state = engine.exportState(); // returns SerializedPathState | null
|
|
86
|
+
const restoredEngine = PathEngine.fromState(state, pathDefinitions);
|
|
87
|
+
|
|
50
88
|
const unsubscribe = engine.subscribe((event) => { ... });
|
|
51
89
|
unsubscribe(); // remove the listener
|
|
52
90
|
```
|
|
@@ -60,36 +98,318 @@ All hooks are optional. Hooks that want to update data **return a partial patch*
|
|
|
60
98
|
| `onEnter` | On arrival at a step (start, next, previous, resume) | ✅ |
|
|
61
99
|
| `onLeave` | On departure from a step (only when the guard allows) | ✅ |
|
|
62
100
|
| `onSubPathComplete` | On the parent step when a sub-path finishes | ✅ |
|
|
101
|
+
| `onSubPathCancel` | On the parent step when a sub-path is cancelled | ✅ |
|
|
63
102
|
| `canMoveNext` | Before advancing — return `false` to block | — |
|
|
64
103
|
| `canMovePrevious` | Before going back — return `false` to block | — |
|
|
65
104
|
| `validationMessages` | On every snapshot — return `string[]` explaining why the step is not yet valid | — |
|
|
66
105
|
|
|
106
|
+
### Using `isFirstEntry` to Avoid Data Reset
|
|
107
|
+
|
|
108
|
+
**Problem:** `onEnter` fires EVERY time you enter a step, including when navigating backward. If you initialize data in `onEnter`, you'll overwrite user input when they return to the step.
|
|
109
|
+
|
|
110
|
+
**Solution:** Use `ctx.isFirstEntry` to distinguish first visit from re-entry:
|
|
111
|
+
|
|
112
|
+
```typescript
|
|
113
|
+
{
|
|
114
|
+
id: "user-details",
|
|
115
|
+
onEnter: (ctx) => {
|
|
116
|
+
// Only initialize on first entry, not on re-entry
|
|
117
|
+
if (ctx.isFirstEntry) {
|
|
118
|
+
return {
|
|
119
|
+
name: "",
|
|
120
|
+
email: "",
|
|
121
|
+
preferences: { newsletter: true }
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// On re-entry (e.g., user pressed Back), keep existing data
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
**Common Patterns:**
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
// Initialize empty collection on first entry only
|
|
133
|
+
onEnter: (ctx) => {
|
|
134
|
+
if (ctx.isFirstEntry) {
|
|
135
|
+
return { approvals: [], comments: [] };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Fetch data from API only once
|
|
140
|
+
onEnter: async (ctx) => {
|
|
141
|
+
if (ctx.isFirstEntry) {
|
|
142
|
+
const userData = await fetchUserProfile(ctx.data.userId);
|
|
143
|
+
return { ...userData };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Set defaults but preserve user changes on re-entry
|
|
148
|
+
onEnter: (ctx) => {
|
|
149
|
+
if (ctx.isFirstEntry) {
|
|
150
|
+
return {
|
|
151
|
+
reviewStatus: "pending",
|
|
152
|
+
lastModified: new Date().toISOString()
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
67
158
|
### Snapshot guard booleans
|
|
68
159
|
|
|
69
160
|
The snapshot includes `canMoveNext` and `canMovePrevious` booleans — the evaluated results of the current step's guards. Use them to proactively disable navigation buttons. Sync guards reflect their real value; async guards default to `true` (optimistic). Both update automatically when data changes via `setData`.
|
|
70
161
|
|
|
71
|
-
###
|
|
162
|
+
### ⚠️ IMPORTANT: Guards Run Before `onEnter`
|
|
163
|
+
|
|
164
|
+
**Guards are evaluated BEFORE `onEnter` runs on first entry.** This is critical to understand:
|
|
165
|
+
|
|
166
|
+
1. When a path starts, the engine creates the first snapshot immediately
|
|
167
|
+
2. Guards (`canMoveNext`, `validationMessages`) are evaluated to populate that snapshot
|
|
168
|
+
3. Only THEN does `onEnter` run to initialize data
|
|
169
|
+
|
|
170
|
+
**This means guards see `initialData`, not data that `onEnter` would set.**
|
|
171
|
+
|
|
172
|
+
#### Defensive Guard Patterns
|
|
173
|
+
|
|
174
|
+
Always write guards defensively to handle undefined/missing data:
|
|
72
175
|
|
|
73
176
|
```typescript
|
|
177
|
+
// ❌ WRONG - Crashes on first snapshot when initialData = {}
|
|
74
178
|
{
|
|
75
|
-
id: "
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
179
|
+
id: "user-details",
|
|
180
|
+
canMoveNext: (ctx) => ctx.data.name.trim().length > 0, // TypeError!
|
|
181
|
+
onEnter: () => ({ name: "" }) // Too late - guard already ran
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ✅ CORRECT - Use nullish coalescing
|
|
185
|
+
{
|
|
186
|
+
id: "user-details",
|
|
187
|
+
canMoveNext: (ctx) => (ctx.data.name ?? "").trim().length > 0,
|
|
188
|
+
onEnter: () => ({ name: "" })
|
|
79
189
|
}
|
|
190
|
+
|
|
191
|
+
// ✅ ALSO CORRECT - Provide initialData so fields exist from the start
|
|
192
|
+
engine.start(path, { name: "", email: "" });
|
|
80
193
|
```
|
|
81
194
|
|
|
82
|
-
|
|
195
|
+
#### More Defensive Patterns
|
|
196
|
+
|
|
197
|
+
```typescript
|
|
198
|
+
// Arrays
|
|
199
|
+
canMoveNext: (ctx) => (ctx.data.items ?? []).length > 0
|
|
200
|
+
|
|
201
|
+
// Numbers
|
|
202
|
+
canMoveNext: (ctx) => (ctx.data.age ?? 0) >= 18
|
|
83
203
|
|
|
204
|
+
// Complex objects
|
|
205
|
+
canMoveNext: (ctx) => {
|
|
206
|
+
const address = ctx.data.address ?? {};
|
|
207
|
+
return (address.street ?? "").length > 0 && (address.city ?? "").length > 0;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Validation messages
|
|
211
|
+
validationMessages: (ctx) => {
|
|
212
|
+
const messages = [];
|
|
213
|
+
if (!(ctx.data.email ?? "").includes("@")) {
|
|
214
|
+
messages.push("Please enter a valid email");
|
|
215
|
+
}
|
|
216
|
+
return messages;
|
|
217
|
+
}
|
|
84
218
|
```
|
|
219
|
+
|
|
220
|
+
#### Error Handling
|
|
221
|
+
|
|
222
|
+
If a guard or `validationMessages` hook throws, Pathwrite catches the error, emits a `console.warn` (with the step ID and thrown value), and returns the safe default (`true` / `[]`) so the UI remains operable. However, **relying on error handling is not recommended** — write defensive guards instead.
|
|
223
|
+
|
|
224
|
+
### Sub-path example with meta correlation
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
{
|
|
228
|
+
id: "subjects-list",
|
|
229
|
+
onSubPathComplete: (_id, subData, ctx, meta) => {
|
|
230
|
+
// meta contains the correlation object passed to startSubPath
|
|
231
|
+
const index = meta?.index as number;
|
|
232
|
+
return {
|
|
233
|
+
subjects: [...(ctx.data.subjects ?? []), {
|
|
234
|
+
index,
|
|
235
|
+
name: subData.name,
|
|
236
|
+
teacher: subData.teacher
|
|
237
|
+
}]
|
|
238
|
+
};
|
|
239
|
+
},
|
|
240
|
+
onSubPathCancel: (_id, ctx, meta) => {
|
|
241
|
+
// Called when user cancels sub-path (e.g., Back on first step)
|
|
242
|
+
const index = meta?.index as number;
|
|
243
|
+
console.log(`User skipped subject ${index}`);
|
|
244
|
+
// Return patch to record the skip, or return nothing to ignore
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
## Sub-Paths: Comprehensive Guide
|
|
250
|
+
|
|
251
|
+
Sub-paths let you nest workflows — for example, running a mini-wizard for each item in a collection.
|
|
252
|
+
|
|
253
|
+
### Basic Flow
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
85
256
|
engine.start(mainPath) → stack: [] active: main
|
|
86
257
|
engine.startSubPath(subPath) → stack: [main] active: sub
|
|
87
258
|
engine.next() // sub finishes
|
|
88
259
|
→ onSubPathComplete fires on the parent step
|
|
89
|
-
→ stack: []
|
|
260
|
+
→ stack: [] active: main (resumed)
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
### Complete Example: Document Approval Workflow
|
|
264
|
+
|
|
265
|
+
```typescript
|
|
266
|
+
interface ApprovalData extends PathData {
|
|
267
|
+
documentTitle: string;
|
|
268
|
+
approvers: Array<{ name: string; email: string }>;
|
|
269
|
+
approvals: Array<{ approverIndex: number; decision: string; comments: string }>;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
interface ApproverReviewData extends PathData {
|
|
273
|
+
documentTitle: string; // Passed from parent
|
|
274
|
+
decision?: "approve" | "reject";
|
|
275
|
+
comments?: string;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Main path
|
|
279
|
+
const approvalPath: PathDefinition<ApprovalData> = {
|
|
280
|
+
id: "approval-workflow",
|
|
281
|
+
steps: [
|
|
282
|
+
{
|
|
283
|
+
id: "setup",
|
|
284
|
+
onEnter: (ctx) => {
|
|
285
|
+
if (ctx.isFirstEntry) {
|
|
286
|
+
return { approvers: [], approvals: [] };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
{
|
|
291
|
+
id: "run-approvals",
|
|
292
|
+
// Block next until all approvers have completed
|
|
293
|
+
canMoveNext: (ctx) => {
|
|
294
|
+
const approversCount = (ctx.data.approvers ?? []).length;
|
|
295
|
+
const approvalsCount = (ctx.data.approvals ?? []).length;
|
|
296
|
+
return approversCount > 0 && approvalsCount === approversCount;
|
|
297
|
+
},
|
|
298
|
+
validationMessages: (ctx) => {
|
|
299
|
+
const approversCount = (ctx.data.approvers ?? []).length;
|
|
300
|
+
const approvalsCount = (ctx.data.approvals ?? []).length;
|
|
301
|
+
const remaining = approversCount - approvalsCount;
|
|
302
|
+
if (remaining > 0) {
|
|
303
|
+
return [`${remaining} approver(s) still need to complete their review`];
|
|
304
|
+
}
|
|
305
|
+
return [];
|
|
306
|
+
},
|
|
307
|
+
// Called when each approver sub-path completes
|
|
308
|
+
onSubPathComplete: (_subPathId, subData, ctx, meta) => {
|
|
309
|
+
const reviewData = subData as ApproverReviewData;
|
|
310
|
+
const approverIndex = meta?.approverIndex as number;
|
|
311
|
+
|
|
312
|
+
return {
|
|
313
|
+
approvals: [
|
|
314
|
+
...(ctx.data.approvals ?? []),
|
|
315
|
+
{
|
|
316
|
+
approverIndex,
|
|
317
|
+
decision: reviewData.decision!,
|
|
318
|
+
comments: reviewData.comments ?? ""
|
|
319
|
+
}
|
|
320
|
+
]
|
|
321
|
+
};
|
|
322
|
+
},
|
|
323
|
+
// Called when approver cancels (presses Back on first step)
|
|
324
|
+
onSubPathCancel: (_subPathId, ctx, meta) => {
|
|
325
|
+
const approverIndex = meta?.approverIndex as number;
|
|
326
|
+
console.log(`Approver ${approverIndex} declined to review`);
|
|
327
|
+
// Could add to a "skipped" list or just ignore
|
|
328
|
+
}
|
|
329
|
+
},
|
|
330
|
+
{ id: "summary" }
|
|
331
|
+
]
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
// Sub-path for each approver
|
|
335
|
+
const approverReviewPath: PathDefinition<ApproverReviewData> = {
|
|
336
|
+
id: "approver-review",
|
|
337
|
+
steps: [
|
|
338
|
+
{ id: "review-document" },
|
|
339
|
+
{
|
|
340
|
+
id: "make-decision",
|
|
341
|
+
canMoveNext: (ctx) => ctx.data.decision !== undefined
|
|
342
|
+
},
|
|
343
|
+
{ id: "add-comments" }
|
|
344
|
+
]
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
// Usage in UI component
|
|
348
|
+
function ReviewStep() {
|
|
349
|
+
const approvers = snapshot.data.approvers ?? [];
|
|
350
|
+
const approvals = snapshot.data.approvals ?? [];
|
|
351
|
+
|
|
352
|
+
const startReview = (approverIndex: number) => {
|
|
353
|
+
const approver = approvers[approverIndex];
|
|
354
|
+
|
|
355
|
+
// Start sub-path with meta correlation
|
|
356
|
+
engine.startSubPath(
|
|
357
|
+
approverReviewPath,
|
|
358
|
+
{
|
|
359
|
+
documentTitle: snapshot.data.documentTitle, // Pass context from parent
|
|
360
|
+
// decision and comments will be filled during sub-path
|
|
361
|
+
},
|
|
362
|
+
{ approverIndex } // Meta: correlates completion back to this approver
|
|
363
|
+
);
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
return (
|
|
367
|
+
<div>
|
|
368
|
+
{approvers.map((approver, i) => (
|
|
369
|
+
<div key={i}>
|
|
370
|
+
{approver.name}
|
|
371
|
+
{approvals.some(a => a.approverIndex === i) ? (
|
|
372
|
+
<span>✓ Reviewed</span>
|
|
373
|
+
) : (
|
|
374
|
+
<button onClick={() => startReview(i)}>Start Review</button>
|
|
375
|
+
)}
|
|
376
|
+
</div>
|
|
377
|
+
))}
|
|
378
|
+
</div>
|
|
379
|
+
);
|
|
380
|
+
}
|
|
90
381
|
```
|
|
91
382
|
|
|
92
|
-
|
|
383
|
+
### Sub-Path Key Concepts
|
|
384
|
+
|
|
385
|
+
1. **Stack-based**: Sub-paths push onto a stack. Parent is paused while sub-path is active.
|
|
386
|
+
|
|
387
|
+
2. **Meta correlation**: Pass a `meta` object to `startSubPath()` to identify which collection item triggered the sub-path. It's passed back unchanged to `onSubPathComplete` and `onSubPathCancel`.
|
|
388
|
+
|
|
389
|
+
3. **Data isolation**: Sub-path data is separate from parent data. Pass needed context (like `documentTitle`) in `initialData`.
|
|
390
|
+
|
|
391
|
+
4. **Completion vs Cancellation**:
|
|
392
|
+
- **Complete**: User reaches the last step → `onSubPathComplete` fires
|
|
393
|
+
- **Cancel**: User presses Back on first step → `onSubPathCancel` fires
|
|
394
|
+
- `onSubPathComplete` is NOT called on cancellation
|
|
395
|
+
|
|
396
|
+
5. **Parent remains on same step**: After sub-path completes/cancels, parent resumes at the same step (not advanced automatically).
|
|
397
|
+
|
|
398
|
+
6. **Guards still apply**: Parent step's `canMoveNext` is evaluated when resuming. Use it to block until all sub-paths complete.
|
|
399
|
+
|
|
400
|
+
### What the Shell Renders During Sub-Paths
|
|
401
|
+
|
|
402
|
+
When a sub-path is active:
|
|
403
|
+
- Progress bar shows sub-path steps (parent steps disappear)
|
|
404
|
+
- Back button on sub-path's first step cancels the sub-path
|
|
405
|
+
- Completing the sub-path returns to parent (parent step re-renders)
|
|
406
|
+
|
|
407
|
+
### Nesting Levels
|
|
408
|
+
|
|
409
|
+
Sub-paths can themselves start sub-paths (unlimited nesting). Use `snapshot.nestingLevel` to determine depth:
|
|
410
|
+
- `0` = top-level path
|
|
411
|
+
- `1` = first-level sub-path
|
|
412
|
+
- `2+` = deeper nesting
|
|
93
413
|
|
|
94
414
|
## Events
|
|
95
415
|
|
|
@@ -103,3 +423,48 @@ engine.subscribe((event) => {
|
|
|
103
423
|
}
|
|
104
424
|
});
|
|
105
425
|
```
|
|
426
|
+
|
|
427
|
+
## State Persistence
|
|
428
|
+
|
|
429
|
+
The engine supports exporting and restoring state for persistence scenarios (e.g., saving wizard progress to a server or localStorage).
|
|
430
|
+
|
|
431
|
+
### exportState()
|
|
432
|
+
|
|
433
|
+
Returns a plain JSON-serializable object (`SerializedPathState`) containing the current state:
|
|
434
|
+
- Current path ID and step index
|
|
435
|
+
- Path data
|
|
436
|
+
- Visited step IDs
|
|
437
|
+
- Sub-path stack (if nested paths are active)
|
|
438
|
+
- Navigation flags
|
|
439
|
+
|
|
440
|
+
Returns `null` if no path is active.
|
|
441
|
+
|
|
442
|
+
```typescript
|
|
443
|
+
const state = engine.exportState();
|
|
444
|
+
if (state) {
|
|
445
|
+
const json = JSON.stringify(state);
|
|
446
|
+
// Save to localStorage, send to server, etc.
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
### PathEngine.fromState()
|
|
451
|
+
|
|
452
|
+
Restores a PathEngine from previously exported state. **Important:** You must provide the same path definitions that were active when the state was exported.
|
|
453
|
+
|
|
454
|
+
```typescript
|
|
455
|
+
const state = JSON.parse(savedJson);
|
|
456
|
+
const engine = PathEngine.fromState(state, {
|
|
457
|
+
"main-path": mainPathDefinition,
|
|
458
|
+
"sub-path": subPathDefinition
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
// Engine is restored to the exact step and state
|
|
462
|
+
const snapshot = engine.snapshot();
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
Throws if:
|
|
466
|
+
- State references a path ID not in `pathDefinitions`
|
|
467
|
+
- State version is unsupported
|
|
468
|
+
|
|
469
|
+
The restored engine is fully functional — you can continue navigation, modify data, complete or cancel paths normally.
|
|
470
|
+
```
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,32 @@
|
|
|
1
1
|
export type PathData = Record<string, unknown>;
|
|
2
|
+
export interface SerializedPathState {
|
|
3
|
+
version: 1;
|
|
4
|
+
pathId: string;
|
|
5
|
+
currentStepIndex: number;
|
|
6
|
+
data: PathData;
|
|
7
|
+
visitedStepIds: string[];
|
|
8
|
+
subPathMeta?: Record<string, unknown>;
|
|
9
|
+
pathStack: Array<{
|
|
10
|
+
pathId: string;
|
|
11
|
+
currentStepIndex: number;
|
|
12
|
+
data: PathData;
|
|
13
|
+
visitedStepIds: string[];
|
|
14
|
+
subPathMeta?: Record<string, unknown>;
|
|
15
|
+
}>;
|
|
16
|
+
_isNavigating: boolean;
|
|
17
|
+
}
|
|
2
18
|
export interface PathStepContext<TData extends PathData = PathData> {
|
|
3
19
|
readonly pathId: string;
|
|
4
20
|
readonly stepId: string;
|
|
5
21
|
readonly data: Readonly<TData>;
|
|
22
|
+
/**
|
|
23
|
+
* `true` the first time this step is entered within the current path
|
|
24
|
+
* instance. `false` on all subsequent re-entries (e.g. navigating back
|
|
25
|
+
* then forward again). Use inside `onEnter` to distinguish initialisation
|
|
26
|
+
* from re-entry so you don't accidentally overwrite data the user has
|
|
27
|
+
* already filled in.
|
|
28
|
+
*/
|
|
29
|
+
readonly isFirstEntry: boolean;
|
|
6
30
|
}
|
|
7
31
|
export interface PathStep<TData extends PathData = PathData> {
|
|
8
32
|
id: string;
|
|
@@ -20,7 +44,22 @@ export interface PathStep<TData extends PathData = PathData> {
|
|
|
20
44
|
validationMessages?: (ctx: PathStepContext<TData>) => string[] | Promise<string[]>;
|
|
21
45
|
onEnter?: (ctx: PathStepContext<TData>) => Partial<TData> | void | Promise<Partial<TData> | void>;
|
|
22
46
|
onLeave?: (ctx: PathStepContext<TData>) => Partial<TData> | void | Promise<Partial<TData> | void>;
|
|
23
|
-
|
|
47
|
+
/**
|
|
48
|
+
* Called on the parent step when a sub-path completes naturally (user
|
|
49
|
+
* reached the last step). Receives the sub-path ID, its final data, the
|
|
50
|
+
* parent step context, and the optional `meta` object that was passed to
|
|
51
|
+
* `startSubPath()` for correlation (e.g. a collection item index).
|
|
52
|
+
*/
|
|
53
|
+
onSubPathComplete?: (subPathId: string, subPathData: PathData, ctx: PathStepContext<TData>, meta?: Record<string, unknown>) => Partial<TData> | void | Promise<Partial<TData> | void>;
|
|
54
|
+
/**
|
|
55
|
+
* Called on the parent step when a sub-path is cancelled — either via an
|
|
56
|
+
* explicit `cancel()` call or by pressing Back on the sub-path's first step.
|
|
57
|
+
* Receives the sub-path ID, its data at time of cancellation, the parent
|
|
58
|
+
* step context, and the optional `meta` passed to `startSubPath()`.
|
|
59
|
+
* Return a patch to update the parent path's data (e.g. to record a
|
|
60
|
+
* "skipped" or "declined" outcome).
|
|
61
|
+
*/
|
|
62
|
+
onSubPathCancel?: (subPathId: string, subPathData: PathData, ctx: PathStepContext<TData>, meta?: Record<string, unknown>) => Partial<TData> | void | Promise<Partial<TData> | void>;
|
|
24
63
|
}
|
|
25
64
|
export interface PathDefinition<TData extends PathData = PathData> {
|
|
26
65
|
id: string;
|
|
@@ -78,13 +117,54 @@ export declare class PathEngine {
|
|
|
78
117
|
private readonly pathStack;
|
|
79
118
|
private readonly listeners;
|
|
80
119
|
private _isNavigating;
|
|
120
|
+
/**
|
|
121
|
+
* Restores a PathEngine from previously exported state.
|
|
122
|
+
*
|
|
123
|
+
* **Important:** You must provide the same path definitions that were
|
|
124
|
+
* active when the state was exported. The path IDs in `state` are used
|
|
125
|
+
* to match against the provided definitions.
|
|
126
|
+
*
|
|
127
|
+
* @param state The serialized state from `exportState()`.
|
|
128
|
+
* @param pathDefinitions A map of path ID → definition. Must include the
|
|
129
|
+
* active path and any paths in the stack.
|
|
130
|
+
* @returns A new PathEngine instance with the restored state.
|
|
131
|
+
* @throws If `state` references a path ID not present in `pathDefinitions`,
|
|
132
|
+
* or if the state format is invalid.
|
|
133
|
+
*/
|
|
134
|
+
static fromState(state: SerializedPathState, pathDefinitions: Record<string, PathDefinition>): PathEngine;
|
|
81
135
|
subscribe(listener: (event: PathEvent) => void): () => void;
|
|
82
136
|
start(path: PathDefinition<any>, initialData?: PathData): Promise<void>;
|
|
83
|
-
/**
|
|
84
|
-
|
|
137
|
+
/**
|
|
138
|
+
* Tears down any active path (and the entire sub-path stack) without firing
|
|
139
|
+
* lifecycle hooks or emitting `cancelled`, then immediately starts the given
|
|
140
|
+
* path from scratch.
|
|
141
|
+
*
|
|
142
|
+
* Safe to call at any time — whether a path is running, already completed,
|
|
143
|
+
* or has never been started. Use this to implement a "Start over" button or
|
|
144
|
+
* to retry a path after completion without remounting the host component.
|
|
145
|
+
*
|
|
146
|
+
* @param path The path definition to (re)start.
|
|
147
|
+
* @param initialData Data to seed the fresh path with. Defaults to `{}`.
|
|
148
|
+
*/
|
|
149
|
+
restart(path: PathDefinition<any>, initialData?: PathData): Promise<void>;
|
|
150
|
+
/**
|
|
151
|
+
* Starts a sub-path on top of the currently active path. Throws if no path
|
|
152
|
+
* is running.
|
|
153
|
+
*
|
|
154
|
+
* @param path The sub-path definition to start.
|
|
155
|
+
* @param initialData Data to seed the sub-path with.
|
|
156
|
+
* @param meta Optional correlation object returned unchanged to the
|
|
157
|
+
* parent step's `onSubPathComplete` / `onSubPathCancel`
|
|
158
|
+
* hooks. Use to identify which collection item triggered
|
|
159
|
+
* the sub-path without embedding that information in the
|
|
160
|
+
* sub-path's own data.
|
|
161
|
+
*/
|
|
162
|
+
startSubPath(path: PathDefinition<any>, initialData?: PathData, meta?: Record<string, unknown>): Promise<void>;
|
|
85
163
|
next(): Promise<void>;
|
|
86
164
|
previous(): Promise<void>;
|
|
87
|
-
/** Cancel is synchronous (no hooks).
|
|
165
|
+
/** Cancel is synchronous for top-level paths (no hooks). Sub-path cancellation
|
|
166
|
+
* is async when an `onSubPathCancel` hook is present. Returns a Promise for
|
|
167
|
+
* API consistency. */
|
|
88
168
|
cancel(): Promise<void>;
|
|
89
169
|
setData(key: string, value: unknown): Promise<void>;
|
|
90
170
|
/** Jumps directly to the step with the given ID. Does not check guards or shouldSkip. */
|
|
@@ -101,11 +181,24 @@ export declare class PathEngine {
|
|
|
101
181
|
*/
|
|
102
182
|
goToStepChecked(stepId: string): Promise<void>;
|
|
103
183
|
snapshot(): PathSnapshot | null;
|
|
184
|
+
/**
|
|
185
|
+
* Exports the current engine state as a plain JSON-serializable object.
|
|
186
|
+
* Use with storage adapters (e.g. `@daltonr/pathwrite-store-http`) to
|
|
187
|
+
* persist and restore wizard progress.
|
|
188
|
+
*
|
|
189
|
+
* Returns `null` if no path is active.
|
|
190
|
+
*
|
|
191
|
+
* **Important:** This only exports the _state_ (data, step position, etc.),
|
|
192
|
+
* not the path definition. When restoring, you must provide the same
|
|
193
|
+
* `PathDefinition` to `fromState()`.
|
|
194
|
+
*/
|
|
195
|
+
exportState(): SerializedPathState | null;
|
|
104
196
|
private _startAsync;
|
|
105
197
|
private _nextAsync;
|
|
106
198
|
private _previousAsync;
|
|
107
199
|
private _goToStepAsync;
|
|
108
200
|
private _goToStepCheckedAsync;
|
|
201
|
+
private _cancelSubPathAsync;
|
|
109
202
|
private finishActivePath;
|
|
110
203
|
private requireActivePath;
|
|
111
204
|
private assertPathHasSteps;
|
|
@@ -122,12 +215,27 @@ export declare class PathEngine {
|
|
|
122
215
|
* Evaluates a guard function synchronously for inclusion in the snapshot.
|
|
123
216
|
* If the guard is absent, returns `true`.
|
|
124
217
|
* If the guard returns a `Promise`, returns `true` (optimistic default).
|
|
218
|
+
*
|
|
219
|
+
* **Note:** Guards are evaluated on every snapshot, including the very first one
|
|
220
|
+
* emitted at the start of a path — _before_ `onEnter` has run on that step.
|
|
221
|
+
* This means `data` will still reflect the `initialData` passed to `start()`.
|
|
222
|
+
* Write guards defensively (e.g. `(data.name ?? "").trim().length > 0`) so they
|
|
223
|
+
* do not throw when optional fields are absent on first entry.
|
|
224
|
+
*
|
|
225
|
+
* If a guard throws, the error is caught, a `console.warn` is emitted, and the
|
|
226
|
+
* safe default (`true`) is returned so the UI remains operable.
|
|
125
227
|
*/
|
|
126
228
|
private evaluateGuardSync;
|
|
127
229
|
/**
|
|
128
230
|
* Evaluates a validationMessages function synchronously for inclusion in the snapshot.
|
|
129
231
|
* If the hook is absent, returns `[]`.
|
|
130
232
|
* If the hook returns a `Promise`, returns `[]` (async hooks are not supported in snapshots).
|
|
233
|
+
*
|
|
234
|
+
* **Note:** Like guards, `validationMessages` is evaluated before `onEnter` runs on first
|
|
235
|
+
* entry. Write it defensively so it does not throw when fields are absent.
|
|
236
|
+
*
|
|
237
|
+
* If the function throws, the error is caught, a `console.warn` is emitted, and `[]`
|
|
238
|
+
* is returned so validation messages do not block the UI unexpectedly.
|
|
131
239
|
*/
|
|
132
240
|
private evaluateValidationMessagesSync;
|
|
133
241
|
}
|