@daltonr/pathwrite-angular 0.10.0 → 0.11.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # @daltonr/pathwrite-angular
2
2
 
3
- Angular `@Injectable` facade over `@daltonr/pathwrite-core`. Exposes path state and events as RxJS observables that work seamlessly with Angular signals, the `async` pipe, and `takeUntilDestroyed`.
3
+ Angular adapter for `@daltonr/pathwrite-core` `PathFacade` injectable service with RxJS observables, Angular signals, and an optional `<pw-shell>` UI component.
4
4
 
5
5
  ## Installation
6
6
 
@@ -8,508 +8,133 @@ Angular `@Injectable` facade over `@daltonr/pathwrite-core`. Exposes path state
8
8
  npm install @daltonr/pathwrite-core @daltonr/pathwrite-angular
9
9
  ```
10
10
 
11
- ## Exported Types
11
+ Peer dependencies: Angular 17+, RxJS 7+.
12
12
 
13
- For convenience, this package re-exports core types so you don't need to import from `@daltonr/pathwrite-core`:
14
-
15
- ```typescript
16
- import {
17
- PathFacade, // Angular-specific
18
- PathEngine, // Re-exported from core (value + type)
19
- PathData, // Re-exported from core
20
- PathDefinition, // Re-exported from core
21
- PathEvent, // Re-exported from core
22
- PathSnapshot, // Re-exported from core
23
- PathStep, // Re-exported from core
24
- PathStepContext, // Re-exported from core
25
- SerializedPathState // Re-exported from core
26
- } from "@daltonr/pathwrite-angular";
27
- ```
28
-
29
- ---
30
-
31
- ## Setup
32
-
33
- Provide `PathFacade` at the component level so each component gets its own isolated path instance, and Angular handles cleanup automatically via `ngOnDestroy`.
34
-
35
- ```typescript
36
- @Component({
37
- // ...
38
- providers: [PathFacade]
39
- })
40
- export class MyComponent {
41
- protected readonly facade = inject(PathFacade);
42
-
43
- // Reactive snapshot — updates whenever the path state changes
44
- public readonly snapshot = toSignal(this.facade.state$, { initialValue: null });
45
-
46
- constructor() {
47
- // Automatically unsubscribes when the component is destroyed
48
- this.facade.events$.pipe(takeUntilDestroyed()).subscribe((event) => {
49
- console.log(event);
50
- });
51
- }
52
- }
53
- ```
54
-
55
- ## PathFacade API
56
-
57
- ### Observables and signals
58
-
59
- | Member | Type | Description |
60
- |--------|------|-------------|
61
- | `state$` | `Observable<PathSnapshot \| null>` | Current snapshot. `null` when no path is active. Backed by a `BehaviorSubject` — late subscribers receive the current value immediately. |
62
- | `stateSignal` | `Signal<PathSnapshot \| null>` | Signal version of `state$`. Same value, updated synchronously. Use directly in signal-based components without `toSignal()`. |
63
- | `events$` | `Observable<PathEvent>` | All engine events: `stateChanged`, `completed`, `cancelled`, `resumed`. |
64
-
65
- ### Methods
66
-
67
- | Method | Description |
68
- |--------|-------------|
69
- | `adoptEngine(engine)` | Adopt an externally-managed `PathEngine` (e.g. from `restoreOrStart()`). The facade immediately reflects the engine's current state and forwards all subsequent events. The caller is responsible for the engine's lifecycle. |
70
- | `start(definition, data?)` | Start or re-start a path. |
71
- | `restart(definition, data?)` | Tear down any active path (without firing hooks) and start the given path fresh. Safe to call at any time. Use for "Start over" / retry flows. |
72
- | `startSubPath(definition, data?, meta?)` | Push a sub-path. Requires an active path. `meta` is returned unchanged to `onSubPathComplete` / `onSubPathCancel`. |
73
- | `next()` | Advance one step. Completes the path on the last step. |
74
- | `previous()` | Go back one step. No-op when already on the first step of a top-level path. |
75
- | `cancel()` | Cancel the active path (or sub-path). |
76
- | `setData(key, value)` | Update a single data value; emits `stateChanged`. When `TData` is specified, `key` and `value` are type-checked against your data shape. |
77
- | `goToStep(stepId)` | Jump directly to a step by ID. Calls `onLeave`/`onEnter`; bypasses guards and `shouldSkip`. |
78
- | `goToStepChecked(stepId)` | Jump to a step by ID, checking `canMoveNext` (forward) or `canMovePrevious` (backward) first. Blocked if the guard returns false. |
79
- | `snapshot()` | Synchronous read of the current `PathSnapshot \| null`. |
80
-
81
- `PathFacade` accepts an optional generic `PathFacade<TData>`. Because Angular's DI cannot carry generics at runtime, narrow it with a cast at the injection site:
82
-
83
- ```typescript
84
- protected readonly facade = inject(PathFacade) as PathFacade<MyData>;
85
- facade.snapshot()?.data.name; // typed as string (or whatever MyData defines)
86
- ```
87
-
88
- ---
89
-
90
- ## `injectPath()` — Recommended API for Components
91
-
92
- **New in v0.6.0** — `injectPath()` provides an ergonomic, signal-based API for accessing the path engine inside Angular components. This is the **recommended approach** for step components and forms — it mirrors React's `usePathContext()` and Vue's `usePath()` for consistency across frameworks.
93
-
94
- ### Quick start
13
+ ## Quick start
95
14
 
96
15
  ```typescript
16
+ // job-application.component.ts
97
17
  import { Component } from "@angular/core";
98
- import { PathFacade, injectPath } from "@daltonr/pathwrite-angular";
18
+ import {
19
+ PathShellComponent,
20
+ PathStepDirective,
21
+ } from "@daltonr/pathwrite-angular/shell";
22
+ import { PathFacade } from "@daltonr/pathwrite-angular";
23
+ import type { PathData } from "@daltonr/pathwrite-angular";
24
+ import { applicationPath } from "./application-path";
25
+ import { DetailsStepComponent } from "./details-step.component";
26
+ import { ReviewStepComponent } from "./review-step.component";
99
27
 
100
28
  @Component({
101
- selector: "app-contact-step",
102
29
  standalone: true,
103
- providers: [PathFacade], // ← Required: provide at this component or a parent
104
- template: `
105
- @if (path.snapshot(); as s) {
106
- <h2>{{ s.activeStep?.title }}</h2>
107
- <input
108
- type="text"
109
- [value]="name"
110
- (input)="updateName($any($event.target).value)"
111
- />
112
- <button (click)="path.next()">Next</button>
113
- }
114
- `
115
- })
116
- export class ContactStepComponent {
117
- protected readonly path = injectPath<ContactData>();
118
- protected name = "";
119
-
120
- protected updateName(value: string): void {
121
- this.name = value;
122
- this.path.setData("name", value); // ← No facade or template ref needed
123
- }
124
- }
125
- ```
126
-
127
- ### API
128
-
129
- `injectPath()` returns an object with:
130
-
131
- | Member | Type | Description |
132
- |--------|------|-------------|
133
- | `snapshot` | `Signal<PathSnapshot \| null>` | Current path snapshot as a signal. `null` when no path is active. |
134
- | `start(path, data?)` | `Promise<void>` | Start or restart a path. |
135
- | `restart(path, data?)` | `Promise<void>` | Tear down and restart fresh. |
136
- | `startSubPath(path, data?, meta?)` | `Promise<void>` | Push a sub-path onto the stack. |
137
- | `next()` | `Promise<void>` | Advance one step. |
138
- | `previous()` | `Promise<void>` | Go back one step. |
139
- | `cancel()` | `Promise<void>` | Cancel the active path. |
140
- | `setData(key, value)` | `Promise<void>` | Update a single data field. Type-safe when `TData` is specified. |
141
- | `goToStep(stepId)` | `Promise<void>` | Jump to a step by ID (no guard checks). |
142
- | `goToStepChecked(stepId)` | `Promise<void>` | Jump to a step by ID (guard-checked). |
143
-
144
- ### Type safety
145
-
146
- Pass your data type as a generic to get full type checking:
147
-
148
- ```typescript
149
- interface ContactData {
150
- name: string;
151
- email: string;
152
- }
153
-
154
- const path = injectPath<ContactData>();
155
-
156
- path.setData("name", "Jane"); // ✅ OK
157
- path.setData("foo", 123); // ❌ Type error: "foo" not in ContactData
158
- path.snapshot()?.data.name; // ✅ Typed as string
159
- ```
160
-
161
- #### Typing `setData` key parameters
162
-
163
- `setData` is typed as `setData<K extends string & keyof TData>(key: K, value: TData[K])`.
164
- The `string &` intersection is necessary because `keyof T` includes `number` and `symbol`
165
- (all valid JavaScript property key types), but `setData` only accepts string keys.
166
-
167
- When writing a reusable update method that receives a field name as a parameter, use
168
- `string & keyof TData` — not just `keyof TData` — to match the constraint:
169
-
170
- ```typescript
171
- // ❌ Type error: keyof ContactData is string | number | symbol
172
- protected update(field: keyof ContactData, value: string): void {
173
- this.path.setData(field, value);
174
- }
175
-
176
- // ✅ Correct: string & keyof ensures the type matches setData's signature
177
- protected update(field: string & keyof ContactData, value: string): void {
178
- this.path.setData(field, value);
179
- }
180
- ```
181
-
182
- Inline string literals are always fine — this pattern only matters when passing a key as a variable.
183
-
184
- #### Reading step data without local state
185
-
186
- Rather than mirroring engine data into local component state, use a typed getter that reads
187
- directly from the snapshot signal. Angular tracks the signal read during template evaluation,
188
- so any engine update (including back-navigation) triggers a re-render automatically:
189
-
190
- ```typescript
191
- export class PersonalInfoStepComponent {
192
- protected readonly path = injectPath<OnboardingData>();
193
-
194
- // No local state, no ngOnInit, no dual-update event handlers.
195
- protected get data(): OnboardingData {
196
- return (this.path.snapshot()?.data ?? {}) as OnboardingData;
197
- }
198
- }
199
- ```
200
-
201
- Template reads from `data`; writes go directly to the engine:
202
-
203
- ```html
204
- <input [value]="data.firstName ?? ''"
205
- (input)="path.setData('firstName', $any($event.target).value.trim())" />
206
- ```
207
-
208
- ### Requirements
209
-
210
- - **Angular 16+** (signals required)
211
- - `PathFacade` must be provided in the injector tree (either at the component or a parent component)
212
-
213
- ### Compared to manual facade injection
214
-
215
- **Before** (manual facade injection + template reference):
216
- ```typescript
217
- @Component({
218
30
  providers: [PathFacade],
31
+ imports: [PathShellComponent, PathStepDirective, DetailsStepComponent, ReviewStepComponent],
219
32
  template: `
220
- <pw-shell #shell ...>
221
- <ng-template pwStep="contact">
222
- <input (input)="shell.facade.setData('name', $any($event.target).value)" />
33
+ <pw-shell
34
+ [path]="path"
35
+ [initialData]="{ name: '', email: '' }"
36
+ (complete)="onDone($event)"
37
+ >
38
+ <ng-template pwStep="details">
39
+ <app-details-step />
40
+ </ng-template>
41
+ <ng-template pwStep="review">
42
+ <app-review-step />
223
43
  </ng-template>
224
44
  </pw-shell>
225
45
  `
226
46
  })
227
- export class MyComponent {
228
- protected readonly facade = inject(PathFacade);
229
- }
230
- ```
231
-
232
- **After** (with `injectPath()`):
233
- ```typescript
234
- @Component({
235
- providers: [PathFacade],
236
- template: `
237
- <input (input)="updateName($any($event.target).value)" />
238
- <button (click)="path.next()">Next</button>
239
- `
240
- })
241
- export class MyStepComponent {
242
- protected readonly path = injectPath<MyData>();
243
-
244
- protected updateName(value: string): void {
245
- this.path.setData("name", value); // ← Clean, no template ref
47
+ export class JobApplicationComponent {
48
+ protected readonly path = applicationPath;
49
+ protected onDone(data: PathData): void {
50
+ console.log("Submitted:", data);
246
51
  }
247
52
  }
248
53
  ```
249
54
 
250
- The `injectPath()` approach:
251
- - **No template references** — access the engine directly from the component class
252
- - **Signal-native** — `path.snapshot()` returns the reactive signal directly
253
- - **Type-safe** — generic parameter flows through to all methods
254
- - **Framework-consistent** — matches React's `usePathContext()` and Vue's `usePath()`
255
- - **Less Angular-specific knowledge** — just `inject()` and signals, patterns Angular developers already know
256
-
257
- ---
258
-
259
- ## Angular Forms integration — `syncFormGroup`
260
-
261
- `syncFormGroup` eliminates the boilerplate of manually wiring an Angular
262
- `FormGroup` to the path engine. Call it once (typically in `ngOnInit`) and every
263
- form value change is automatically propagated to the engine via `setData`, keeping
264
- `canMoveNext` guards reactive without any manual plumbing.
265
-
266
55
  ```typescript
267
- import { PathFacade, syncFormGroup } from "@daltonr/pathwrite-angular";
56
+ // details-step.component.ts
57
+ import { Component } from "@angular/core";
58
+ import { injectPath } from "@daltonr/pathwrite-angular";
268
59
 
269
60
  @Component({
270
- providers: [PathFacade],
61
+ selector: "app-details-step",
62
+ standalone: true,
271
63
  template: `
272
- <form [formGroup]="form">
273
- <input formControlName="name" />
274
- <input formControlName="email" />
275
- </form>
276
- <button [disabled]="!(snapshot()?.canMoveNext)" (click)="facade.next()">Next</button>
64
+ @if (path.snapshot(); as s) {
65
+ <input
66
+ [value]="s.data['name'] ?? ''"
67
+ (input)="path.setData('name', $any($event.target).value)"
68
+ placeholder="Name"
69
+ />
70
+ <input
71
+ type="email"
72
+ [value]="s.data['email'] ?? ''"
73
+ (input)="path.setData('email', $any($event.target).value)"
74
+ placeholder="Email"
75
+ />
76
+ }
277
77
  `
278
78
  })
279
- export class DetailsStepComponent implements OnInit {
280
- protected readonly facade = inject(PathFacade);
281
- protected readonly snapshot = toSignal(this.facade.state$, { initialValue: null });
282
-
283
- protected readonly form = new FormGroup({
284
- name: new FormControl('', Validators.required),
285
- email: new FormControl('', [Validators.required, Validators.email]),
286
- });
287
-
288
- async ngOnInit() {
289
- await this.facade.start(myPath, { name: '', email: '' });
290
- // Immediately syncs current form values and keeps them in sync on every change.
291
- // Cleanup is automatic when the component is destroyed.
292
- syncFormGroup(this.facade, this.form, inject(DestroyRef));
293
- }
79
+ export class DetailsStepComponent {
80
+ protected readonly path = injectPath();
294
81
  }
295
82
  ```
296
83
 
297
- The corresponding path definition can now use a clean `canMoveNext` guard with no
298
- manual sync code in the template:
299
-
300
- ```typescript
301
- const myPath: PathDefinition = {
302
- id: 'registration',
303
- steps: [
304
- {
305
- id: 'details',
306
- canMoveNext: (ctx) =>
307
- typeof ctx.data.name === 'string' && ctx.data.name.trim().length > 0 &&
308
- typeof ctx.data.email === 'string' && ctx.data.email.includes('@'),
309
- },
310
- { id: 'review' },
311
- ],
312
- };
313
- ```
314
-
315
- ### `syncFormGroup` signature
316
-
317
- ```typescript
318
- function syncFormGroup(
319
- facade: PathFacade,
320
- formGroup: FormGroupLike,
321
- destroyRef?: DestroyRef
322
- ): () => void
323
- ```
324
-
325
- | Parameter | Type | Description |
326
- |-----------|------|-------------|
327
- | `facade` | `PathFacade` | The facade to write values into. |
328
- | `formGroup` | `FormGroupLike` | Any Angular `FormGroup` (or any object satisfying the duck interface). |
329
- | `destroyRef` | `DestroyRef` *(optional)* | Pass `inject(DestroyRef)` to auto-unsubscribe on component destroy. |
330
- | **returns** | `() => void` | Cleanup function — call manually if not using `DestroyRef`. |
331
-
332
- #### Behaviour details
333
-
334
- - **Immediate sync** — current `getRawValue()` is written on the first call, so
335
- guards evaluate against the real form state from the first snapshot.
336
- - **Disabled controls included** — uses `getRawValue()` (not `formGroup.value`)
337
- so disabled controls are always synced.
338
- - **Safe before `start()`** — if no path is active when a change fires, the call
339
- is silently ignored (no error).
340
- - **`FormGroupLike` duck interface** — `@angular/forms` is not a required import;
341
- any object with `getRawValue()` and `valueChanges` works.
342
-
343
- ### Lifecycle
344
-
345
- `PathFacade` implements `OnDestroy`. When Angular destroys the providing component, `ngOnDestroy` is called automatically, which:
346
- - Unsubscribes from the internal `PathEngine`
347
- - Completes `state$` and `events$`
348
-
349
- ## Using with signals (Angular 16+)
84
+ ## PathFacade
350
85
 
351
- `PathFacade` ships a pre-wired `stateSignal` so no manual `toSignal()` call is
352
- needed:
86
+ `PathFacade` must be provided at the **component level** (not root) so each wizard gets its own isolated engine instance and Angular destroys it automatically when the component is destroyed.
353
87
 
354
88
  ```typescript
355
89
  @Component({ providers: [PathFacade] })
356
- export class MyComponent {
357
- protected readonly facade = inject(PathFacade);
358
-
359
- // Use stateSignal directly — no toSignal() required
360
- protected readonly snapshot = this.facade.stateSignal;
361
-
362
- // Derive computed values
363
- public readonly isActive = computed(() => this.snapshot() !== null);
364
- public readonly currentStep = computed(() => this.snapshot()?.stepId ?? null);
365
- public readonly canAdvance = computed(() => this.snapshot()?.canMoveNext ?? false);
366
- }
367
- ```
368
-
369
- If you prefer the Observable-based approach, `toSignal()` still works as before:
370
-
371
- ```typescript
372
- public readonly snapshot = toSignal(this.facade.state$, { initialValue: null });
373
- ```
374
-
375
- ## Using with the async pipe
376
-
377
- ```html
378
- <ng-container *ngIf="facade.state$ | async as s">
379
- <p>{{ s.pathId }} / {{ s.stepId }}</p>
380
- </ng-container>
381
- ```
382
-
383
- ## Peer dependencies
384
-
385
- | Package | Version |
386
- |---------|---------|
387
- | `@angular/core` | `>=16.0.0` |
388
- | `rxjs` | `>=7.0.0` |
389
-
390
- ---
391
-
392
- ## Default UI — `<pw-shell>`
393
-
394
- The Angular adapter ships an optional shell component that renders a complete progress indicator, step content area, and navigation buttons out of the box. You only need to define the per-step content.
395
-
396
- The shell lives in a separate entry point so that headless-only usage does not pull in the Angular compiler:
397
-
398
- ```typescript
399
- import {
400
- PathShellComponent,
401
- PathStepDirective,
402
- PathShellHeaderDirective,
403
- PathShellFooterDirective,
404
- } from "@daltonr/pathwrite-angular/shell";
405
- ```
406
-
407
- ### Usage
408
-
409
- ```typescript
410
- @Component({
411
- imports: [PathShellComponent, PathStepDirective],
412
- template: `
413
- <pw-shell [path]="myPath" [initialData]="{ name: '' }" (complete)="onDone($event)">
414
- <ng-template pwStep="details"><app-details-form /></ng-template>
415
- <ng-template pwStep="review"><app-review-panel /></ng-template>
416
- </pw-shell>
417
- `
418
- })
419
- export class MyComponent {
420
- protected myPath = coursePath;
421
- protected onDone(data: PathData) { console.log("Done!", data); }
422
- }
90
+ export class MyWizardComponent { }
423
91
  ```
424
92
 
425
- Each `<ng-template pwStep="<stepId>">` is rendered when the active step matches `stepId`. The shell handles all navigation internally.
426
-
427
- > **⚠️ Important: `pwStep` Values Must Match Step IDs**
428
- >
429
- > The string value passed to the `pwStep` directive **must exactly match** the corresponding step's `id`:
430
- >
431
- > ```typescript
432
- > const myPath: PathDefinition = {
433
- > id: 'signup',
434
- > steps: [
435
- > { id: 'details' }, // ← Step ID
436
- > { id: 'review' } // ← Step ID
437
- > ]
438
- > };
439
- > ```
440
- >
441
- > ```html
442
- > <pw-shell [path]="myPath">
443
- > <ng-template pwStep="details"> <!-- ✅ Matches "details" step -->
444
- > <app-details-form />
445
- > </ng-template>
446
- > <ng-template pwStep="review"> <!-- ✅ Matches "review" step -->
447
- > <app-review-panel />
448
- > </ng-template>
449
- > <ng-template pwStep="foo"> <!-- ❌ No step with id "foo" -->
450
- > <app-foo-panel />
451
- > </ng-template>
452
- > </pw-shell>
453
- > ```
454
- >
455
- > If a `pwStep` value doesn't match any step ID, that template will never be rendered (silent — no error message).
456
- >
457
- > **💡 Tip:** Use your IDE's "Go to Definition" on the step ID in your path definition, then copy-paste the exact string when creating the `pwStep` directive. This ensures perfect matching and avoids typos.
93
+ ### Observables and signals
458
94
 
459
- ### Context sharing
95
+ | Member | Type | Description |
96
+ |--------|------|-------------|
97
+ | `state$` | `Observable<PathSnapshot \| null>` | Current snapshot. Backed by a `BehaviorSubject` — late subscribers receive the current value immediately. |
98
+ | `stateSignal` | `Signal<PathSnapshot \| null>` | Pre-wired signal version of `state$`. Use directly without `toSignal()`. |
99
+ | `events$` | `Observable<PathEvent>` | All engine events: `stateChanged`, `completed`, `cancelled`, `resumed`. |
460
100
 
461
- `PathShellComponent` provides a `PathFacade` instance in its own `providers` array
462
- and passes its component-level `Injector` to every step template via
463
- `ngTemplateOutletInjector`. Step components can therefore resolve the shell's
464
- `PathFacade` directly via `inject()` — no extra provider setup required:
101
+ ### Methods
465
102
 
466
- ```typescript
467
- // Step component — inject(PathFacade) resolves the shell's instance automatically
468
- @Component({
469
- template: `
470
- <input [value]="snapshot()?.data?.['name'] ?? ''"
471
- (input)="facade.setData('name', $event.target.value)" />
472
- `
473
- })
474
- export class DetailsFormComponent {
475
- protected readonly facade = inject(PathFacade);
476
- protected readonly snapshot = this.facade.stateSignal;
477
- }
478
- ```
103
+ | Method | Description |
104
+ |--------|-------------|
105
+ | `snapshot()` | Synchronous read of the current `PathSnapshot \| null`. |
106
+ | `start(definition, data?)` | Start or re-start a path. |
107
+ | `restart(definition, data?)` | Tear down any active path and start fresh. Safe to call at any time. |
108
+ | `next()` | Advance one step. Completes the path on the last step. |
109
+ | `previous()` | Go back one step. No-op on the first step of a top-level path. |
110
+ | `cancel()` | Cancel the active path (or sub-path). |
111
+ | `goToStep(stepId)` | Jump to a step by ID. Calls `onLeave`/`onEnter`; bypasses guards. |
112
+ | `goToStepChecked(stepId)` | Jump to a step by ID, checking the current step's guard first. |
113
+ | `setData(key, value)` | Update a single data field. Type-safe when `TData` is specified. |
114
+ | `startSubPath(definition, data?, meta?)` | Push a sub-path. `meta` is returned to `onSubPathComplete`/`onSubPathCancel`. |
115
+ | `adoptEngine(engine)` | Adopt an externally-managed `PathEngine` (e.g. from `restoreOrStart()`). |
479
116
 
480
- The parent component hosting `<pw-shell>` does **not** need its own
481
- `PathFacade` provider. To access the facade from the parent, use `@ViewChild`:
117
+ ## `<pw-shell>` inputs/outputs
482
118
 
483
- ```typescript
484
- @Component({
485
- imports: [PathShellComponent, PathStepDirective],
486
- template: `
487
- <pw-shell #shell [path]="myPath" (complete)="onDone($event)">
488
- <ng-template pwStep="details"><app-details-form /></ng-template>
489
- </pw-shell>
490
- `
491
- })
492
- export class MyComponent {
493
- @ViewChild('shell', { read: PathShellComponent }) shell!: PathShellComponent;
494
- protected onDone(data: PathData) { console.log('done', data); }
495
- }
496
- ```
119
+ Step content is provided via `<ng-template pwStep="stepId">` directives inside `<pw-shell>`. The `pwStep` string must exactly match the step's `id`.
497
120
 
498
121
  ### Inputs
499
122
 
500
123
  | Input | Type | Default | Description |
501
124
  |-------|------|---------|-------------|
502
- | `path` | `PathDefinition` | | The path definition to drive. Required unless `[engine]` is provided. |
503
- | `engine` | `PathEngine` | — | An externally-managed engine (e.g. from `restoreOrStart()`). When provided, `autoStart` is suppressed and the shell immediately reflects the engine's current state. Use `@if (engine)` in the parent template to gate mounting until the engine is ready. |
125
+ | `path` | `PathDefinition` | required | Path definition to drive. Mutually exclusive with `engine`. |
504
126
  | `initialData` | `PathData` | `{}` | Initial data passed to `facade.start()`. |
505
- | `autoStart` | `boolean` | `true` | Start the path automatically on `ngOnInit`. Ignored when `[engine]` is provided. |
127
+ | `engine` | `PathEngine` | | Externally-managed engine (e.g. from `restoreOrStart()`). Suppresses `autoStart`. |
128
+ | `autoStart` | `boolean` | `true` | Start the path on `ngOnInit`. Ignored when `engine` is provided. |
129
+ | `validationDisplay` | `"summary" \| "inline" \| "both"` | `"summary"` | Where `fieldErrors` are rendered. Use `"inline"` so step components render their own errors. |
130
+ | `loadingLabel` | `string` | — | Label shown while the path is navigating. |
131
+ | `footerLayout` | `"wizard" \| "form" \| "auto"` | `"auto"` | `"wizard"`: Back on left, Cancel+Submit on right. `"form"`: Cancel on left, Submit on right, no Back. `"auto"` picks `"form"` for single-step paths. |
132
+ | `hideProgress` | `boolean` | `false` | Hide the progress indicator. Also hidden automatically for single-step paths. |
506
133
  | `backLabel` | `string` | `"Previous"` | Previous button label. |
507
134
  | `nextLabel` | `string` | `"Next"` | Next button label. |
508
135
  | `completeLabel` | `string` | `"Complete"` | Complete button label (last step). |
509
136
  | `cancelLabel` | `string` | `"Cancel"` | Cancel button label. |
510
137
  | `hideCancel` | `boolean` | `false` | Hide the Cancel button. |
511
- | `hideProgress` | `boolean` | `false` | Hide the progress indicator. Also hidden automatically for single-step top-level paths. |
512
- | `footerLayout` | `"wizard" \| "form" \| "auto"` | `"auto"` | Footer button layout. `"auto"` uses `"form"` for single-step top-level paths, `"wizard"` otherwise. `"wizard"`: Back on left, Cancel+Submit on right. `"form"`: Cancel on left, Submit on right, no Back button. |
513
138
 
514
139
  ### Outputs
515
140
 
@@ -519,489 +144,27 @@ export class MyComponent {
519
144
  | `(cancel)` | `PathData` | Emitted when the path is cancelled. |
520
145
  | `(event)` | `PathEvent` | Emitted for every engine event. |
521
146
 
522
- ### Customising the header and footer
523
-
524
- Use `pwShellHeader` and `pwShellFooter` directives to replace the built-in progress bar or navigation buttons with your own templates. Both are declared on `<ng-template>` elements inside the shell.
147
+ ## `injectPath()`
525
148
 
526
- **`pwShellHeader`** receives the current `PathSnapshot` as the implicit template variable:
149
+ `injectPath()` is the preferred API for step components and forms rendered inside `<pw-shell>`. It resolves the `PathFacade` from the nearest injector in the tree and returns a signal-based interface typed with an optional `TData` generic — no `providers: [PathFacade]` needed in step components.
527
150
 
528
151
  ```typescript
529
- @Component({
530
- imports: [PathShellComponent, PathStepDirective, PathShellHeaderDirective],
531
- template: `
532
- <pw-shell [path]="myPath">
533
- <ng-template pwShellHeader let-s>
534
- <p>Step {{ s.stepIndex + 1 }} of {{ s.stepCount }} — {{ s.stepTitle }}</p>
535
- </ng-template>
536
- <ng-template pwStep="details"><app-details-form /></ng-template>
537
- <ng-template pwStep="review"><app-review-panel /></ng-template>
538
- </pw-shell>
539
- `
540
- })
541
- export class MyComponent { ... }
542
- ```
543
-
544
- **`pwShellFooter`** — receives the snapshot as the implicit variable and an `actions` variable with all navigation callbacks:
545
-
546
- ```typescript
547
- @Component({
548
- imports: [PathShellComponent, PathStepDirective, PathShellFooterDirective],
549
- template: `
550
- <pw-shell [path]="myPath">
551
- <ng-template pwShellFooter let-s let-actions="actions">
552
- <button (click)="actions.previous()" [disabled]="s.isFirstStep || s.isNavigating">Back</button>
553
- <button (click)="actions.next()" [disabled]="!s.canMoveNext || s.isNavigating">
554
- {{ s.isLastStep ? 'Complete' : 'Next' }}
555
- </button>
556
- </ng-template>
557
- <ng-template pwStep="details"><app-details-form /></ng-template>
558
- </pw-shell>
559
- `
560
- })
561
- export class MyComponent { ... }
562
- ```
563
-
564
- `actions` (`PathShellActions`) contains: `next`, `previous`, `cancel`, `goToStep`, `goToStepChecked`, `setData`, `restart`. All return `Promise<void>`.
565
-
566
- `restart()` restarts the shell's own `[path]` input with its own `[initialData]` input — useful for a "Start over" button in a custom footer.
567
-
568
- Both directives can be combined. Only the sections you override are replaced — a custom header still shows the default footer, and vice versa.
569
-
570
- ### Resetting the path
571
-
572
- There are two ways to reset `<pw-shell>` to step 1.
152
+ import { injectPath } from "@daltonr/pathwrite-angular";
573
153
 
574
- **Option 1 Toggle mount** (simplest, always correct)
575
-
576
- Toggle an `@if` flag to destroy and recreate the shell. Every child component resets from scratch:
577
-
578
- ```html
579
- @if (isActive) {
580
- <pw-shell [path]="myPath" (complete)="isActive = false" (cancel)="isActive = false">
581
- <ng-template pwStep="details"><app-details-form /></ng-template>
582
- </pw-shell>
583
- } @else {
584
- <button (click)="isActive = true">Try Again</button>
154
+ export class DetailsStepComponent {
155
+ protected readonly path = injectPath<ApplicationData>();
156
+ // path.snapshot() Signal<PathSnapshot | null>
157
+ // path.setData(key, value) — type-safe with TData
158
+ // path.next(), path.previous(), path.cancel(), etc.
585
159
  }
586
160
  ```
587
161
 
588
- **Option 2 — Call `restart()` on the shell ref** (in-place, no unmount)
589
-
590
- Use the existing `#shell` template reference — `restart()` is a public method:
591
-
592
- ```html
593
- <pw-shell #shell [path]="myPath" (complete)="onDone($event)">
594
- <ng-template pwStep="details"><app-details-form /></ng-template>
595
- </pw-shell>
596
-
597
- <button (click)="shell.restart()">Try Again</button>
598
- ```
162
+ ## Further reading
599
163
 
600
- `restart()` resets the path engine to step 1 with the original `[initialData]` without unmounting the component. Use this when you need to keep the shell mounted — for example, to preserve scroll position in a parent container or to drive a CSS transition.
164
+ - [Angular getting started guide](../../docs/getting-started/frameworks/angular.md)
165
+ - [Navigation & guards](../../docs/guides/navigation.md)
166
+ - [Full documentation](../../docs/README.md)
601
167
 
602
168
  ---
603
169
 
604
- ## Sub-Paths
605
-
606
- Sub-paths allow you to nest multi-step workflows. Common use cases include:
607
- - Running a child workflow per collection item (e.g., approve each document)
608
- - Conditional drill-down flows (e.g., "Add payment method" modal)
609
- - Reusable wizard components
610
-
611
- ### Basic Sub-Path Flow
612
-
613
- When a sub-path is active:
614
- - The shell switches to show the sub-path's steps
615
- - The progress bar displays sub-path steps (not main path steps)
616
- - Pressing Back on the first sub-path step **cancels** the sub-path and returns to the parent
617
- - The `PathFacade` (and thus `state$`, `stateSignal`) reflects the **sub-path** snapshot, not the parent's
618
-
619
- ### Complete Example: Approver Collection
620
-
621
- ```typescript
622
- import { PathData, PathDefinition, PathFacade } from "@daltonr/pathwrite-angular";
623
-
624
- // Sub-path data shape
625
- interface ApproverReviewData extends PathData {
626
- decision: "approve" | "reject" | "";
627
- comments: string;
628
- }
629
-
630
- // Main path data shape
631
- interface ApprovalWorkflowData extends PathData {
632
- documentTitle: string;
633
- approvers: string[];
634
- approvals: Array<{ approver: string; decision: string; comments: string }>;
635
- }
636
-
637
- // Define the sub-path (approver review wizard)
638
- const approverReviewPath: PathDefinition<ApproverReviewData> = {
639
- id: "approver-review",
640
- steps: [
641
- { id: "review", title: "Review Document" },
642
- {
643
- id: "decision",
644
- title: "Make Decision",
645
- canMoveNext: ({ data }) =>
646
- data.decision === "approve" || data.decision === "reject",
647
- validationMessages: ({ data }) =>
648
- !data.decision ? ["Please select Approve or Reject"] : []
649
- },
650
- { id: "comments", title: "Add Comments" }
651
- ]
652
- };
653
-
654
- // Define the main path
655
- const approvalWorkflowPath: PathDefinition<ApprovalWorkflowData> = {
656
- id: "approval-workflow",
657
- steps: [
658
- {
659
- id: "setup",
660
- title: "Setup Approval",
661
- canMoveNext: ({ data }) =>
662
- (data.documentTitle ?? "").trim().length > 0 &&
663
- data.approvers.length > 0
664
- },
665
- {
666
- id: "run-approvals",
667
- title: "Collect Approvals",
668
- // Block "Next" until all approvers have completed their reviews
669
- canMoveNext: ({ data }) =>
670
- data.approvals.length === data.approvers.length,
671
- validationMessages: ({ data }) => {
672
- const remaining = data.approvers.length - data.approvals.length;
673
- return remaining > 0
674
- ? [`${remaining} approver(s) pending review`]
675
- : [];
676
- },
677
- // When an approver finishes their sub-path, record the result
678
- onSubPathComplete(subPathId, subPathData, ctx, meta) {
679
- const approverName = meta?.approverName as string;
680
- const result = subPathData as ApproverReviewData;
681
- return {
682
- approvals: [
683
- ...ctx.data.approvals,
684
- {
685
- approver: approverName,
686
- decision: result.decision,
687
- comments: result.comments
688
- }
689
- ]
690
- };
691
- },
692
- // If an approver cancels (presses Back on first step), you can track it
693
- onSubPathCancel(subPathId, subPathData, ctx, meta) {
694
- console.log(`${meta?.approverName} cancelled their review`);
695
- // Optionally return data changes, or just log
696
- }
697
- },
698
- { id: "summary", title: "Summary" }
699
- ]
700
- };
701
-
702
- // Component
703
- @Component({
704
- selector: 'app-approval-workflow',
705
- standalone: true,
706
- imports: [PathShellComponent, PathStepDirective],
707
- providers: [PathFacade],
708
- template: `
709
- <pw-shell [path]="approvalWorkflowPath" [initialData]="initialData">
710
- <!-- Main path steps -->
711
- <ng-template pwStep="setup">
712
- <input [(ngModel)]="facade.snapshot()!.data.documentTitle" placeholder="Document title" />
713
- <!-- approver selection UI here -->
714
- </ng-template>
715
-
716
- <ng-template pwStep="run-approvals">
717
- <h3>Approvers</h3>
718
- <ul>
719
- @for (approver of facade.snapshot()!.data.approvers; track $index) {
720
- <li>
721
- {{ approver }}
722
- @if (!hasApproval(approver)) {
723
- <button (click)="launchReviewForApprover(approver, $index)">
724
- Start Review
725
- </button>
726
- } @else {
727
- <span>✓ {{ getApproval(approver)?.decision }}</span>
728
- }
729
- </li>
730
- }
731
- </ul>
732
- </ng-template>
733
-
734
- <ng-template pwStep="summary">
735
- <h3>All Approvals Collected</h3>
736
- <ul>
737
- @for (approval of facade.snapshot()!.data.approvals; track approval.approver) {
738
- <li>{{ approval.approver }}: {{ approval.decision }}</li>
739
- }
740
- </ul>
741
- </ng-template>
742
-
743
- <!-- Sub-path steps (must be co-located in the same pw-shell) -->
744
- <ng-template pwStep="review">
745
- <p>Review the document: "{{ facade.snapshot()!.data.documentTitle }}"</p>
746
- </ng-template>
747
-
748
- <ng-template pwStep="decision">
749
- <label><input type="radio" value="approve" [(ngModel)]="facade.snapshot()!.data.decision" /> Approve</label>
750
- <label><input type="radio" value="reject" [(ngModel)]="facade.snapshot()!.data.decision" /> Reject</label>
751
- </ng-template>
752
-
753
- <ng-template pwStep="comments">
754
- <textarea [(ngModel)]="facade.snapshot()!.data.comments" placeholder="Optional comments"></textarea>
755
- </ng-template>
756
- </pw-shell>
757
- `
758
- })
759
- export class ApprovalWorkflowComponent {
760
- protected readonly facade = inject(PathFacade) as PathFacade<ApprovalWorkflowData>;
761
- protected readonly approvalWorkflowPath = approvalWorkflowPath;
762
- protected readonly initialData = { documentTitle: '', approvers: [], approvals: [] };
763
-
764
- protected launchReviewForApprover(approverName: string, index: number): void {
765
- // Pass correlation data via `meta` — it's echoed back to onSubPathComplete
766
- void this.facade.startSubPath(
767
- approverReviewPath,
768
- { decision: "", comments: "" },
769
- { approverName, approverIndex: index }
770
- );
771
- }
772
-
773
- protected hasApproval(approver: string): boolean {
774
- return this.facade.snapshot()!.data.approvals.some(a => a.approver === approver);
775
- }
776
-
777
- protected getApproval(approver: string) {
778
- return this.facade.snapshot()!.data.approvals.find(a => a.approver === approver);
779
- }
780
- }
781
- ```
782
-
783
- ### Key Notes
784
-
785
- **1. Sub-path steps must be co-located with main path steps**
786
- All `pwStep` templates (main path + sub-path steps) live in the same `<pw-shell>`. When a sub-path is active, the shell renders the sub-path's step templates. This means:
787
- - Parent and sub-path step IDs **must not collide** (e.g., don't use `summary` in both)
788
- - The shell matches step IDs from the current path only (main or sub), but all templates are registered globally
789
-
790
- **2. The `meta` correlation field**
791
- `startSubPath` accepts an optional third argument (`meta`) that is returned unchanged to `onSubPathComplete` and `onSubPathCancel`. Use it to correlate which collection item triggered the sub-path:
792
-
793
- ```typescript
794
- facade.startSubPath(subPath, initialData, { itemIndex: 3, itemId: "abc" });
795
-
796
- // In the parent step:
797
- onSubPathComplete(subPathId, subPathData, ctx, meta) {
798
- const itemIndex = meta?.itemIndex; // 3
799
- }
800
- ```
801
-
802
- **3. Root progress bar persists during sub-paths**
803
- When `snapshot.nestingLevel > 0`, you're in a sub-path. The shell automatically renders a compact, muted **root progress bar** above the sub-path's own progress bar so users always see their place in the main flow. The `steps` array in the snapshot contains the sub-path's steps. Use `snapshot.rootProgress` (type `RootProgress`) in a custom `pwShellHeader` template to render your own persistent top-level indicator.
804
-
805
- **4. Accessing parent path data from sub-path components**
806
- There is currently no way to inject a "parent facade" in sub-path step components. If a sub-path step needs parent data (e.g., the document title), pass it via `initialData` when calling `startSubPath`:
807
-
808
- ```typescript
809
- facade.startSubPath(approverReviewPath, {
810
- decision: "",
811
- comments: "",
812
- documentTitle: facade.snapshot()!.data.documentTitle // copy from parent
813
- });
814
- ```
815
-
816
- ---
817
-
818
- ## Guards and Lifecycle Hooks
819
-
820
- ### Defensive Guards (Important!)
821
-
822
- **Guards and `validationMessages` are evaluated *before* `onEnter` runs on first entry.**
823
-
824
- If you access fields in a guard that `onEnter` is supposed to initialize, the guard will throw a `TypeError` on startup. Write guards defensively using nullish coalescing:
825
-
826
- ```typescript
827
- // ✗ Unsafe — crashes if data.name is undefined
828
- canMoveNext: ({ data }) => data.name.trim().length > 0
829
-
830
- // ✓ Safe — handles undefined gracefully
831
- canMoveNext: ({ data }) => (data.name ?? "").trim().length > 0
832
- ```
833
-
834
- Alternatively, pass `initialData` to `start()` / `<pw-shell>` so all fields are present from the first snapshot:
835
-
836
- ```typescript
837
- <pw-shell [path]="myPath" [initialData]="{ name: '', age: 0 }" />
838
- ```
839
-
840
- If a guard throws, the engine catches it, logs a warning, and returns `true` (allow navigation) as a safe default.
841
-
842
- ### Async Guards and Validation Messages
843
-
844
- Guards and `validationMessages` must be **synchronous** for inclusion in snapshots. Async functions are detected and warned about:
845
- - Async `canMoveNext` / `canMovePrevious` default to `true` (optimistic)
846
- - Async `validationMessages` default to `[]`
847
-
848
- The async version is still enforced during actual navigation (when you call `next()` / `previous()`), but the snapshot won't reflect the pending state. If you need async validation, perform it in the guard and store the result in `data` so the guard can read it synchronously.
849
-
850
- ### `isFirstEntry` Flag
851
-
852
- The `PathStepContext` passed to all hooks includes an `isFirstEntry: boolean` flag. It's `true` the first time a step is visited, `false` on re-entry (e.g., after navigating back then forward again).
853
-
854
- Use it to distinguish initialization from re-entry:
855
-
856
- ```typescript
857
- {
858
- id: "details",
859
- onEnter: ({ isFirstEntry, data }) => {
860
- if (isFirstEntry) {
861
- // Only pre-fill on first visit, not when returning via Back
862
- return { name: "Default Name" };
863
- }
864
- }
865
- }
866
- ```
867
-
868
- **Important:** `onEnter` fires every time you enter the step. If you want "initialize once" behavior, either:
869
- 1. Use `isFirstEntry` to conditionally return data
870
- 2. Provide `initialData` to `start()` instead of using `onEnter`
871
-
872
- ---
873
-
874
- ## Persistence
875
-
876
- Use with [@daltonr/pathwrite-store](../store) for automatic state persistence. The engine is created externally via `restoreOrStart()` and passed directly to `<pw-shell>` via the `[engine]` input.
877
-
878
- ### Simple persistence example
879
-
880
- ```typescript
881
- import { Component, OnInit } from '@angular/core';
882
- import { PathEngine } from '@daltonr/pathwrite-angular';
883
- import { PathShellComponent, PathStepDirective } from '@daltonr/pathwrite-angular/shell';
884
- import { HttpStore, restoreOrStart, persistence } from '@daltonr/pathwrite-store';
885
- import { signupPath } from './signup-path';
886
-
887
- @Component({
888
- selector: 'app-signup-wizard',
889
- standalone: true,
890
- imports: [PathShellComponent, PathStepDirective],
891
- template: `
892
- @if (engine) {
893
- <pw-shell [path]="path" [engine]="engine" (complete)="onComplete($event)">
894
- <ng-template pwStep="details"><app-details-form /></ng-template>
895
- <ng-template pwStep="review"><app-review-panel /></ng-template>
896
- </pw-shell>
897
- } @else {
898
- <p>Loading…</p>
899
- }
900
- `
901
- })
902
- export class SignupWizardComponent implements OnInit {
903
- path = signupPath;
904
- engine: PathEngine | null = null;
905
-
906
- async ngOnInit() {
907
- const store = new HttpStore({ baseUrl: '/api/wizard' });
908
- const key = 'user:signup';
909
-
910
- const { engine, restored } = await restoreOrStart({
911
- store,
912
- key,
913
- path: this.path,
914
- initialData: { name: '', email: '' },
915
- observers: [
916
- persistence({ store, key, strategy: 'onNext' })
917
- ]
918
- });
919
-
920
- this.engine = engine;
921
-
922
- if (restored) {
923
- console.log('Progress restored — resuming from', engine.snapshot()?.stepId);
924
- }
925
- }
926
-
927
- onComplete(data: any) {
928
- console.log('Wizard completed:', data);
929
- }
930
- }
931
- ```
932
-
933
- ### Key points
934
-
935
- - **`[engine]`** passes an externally-managed engine directly to the shell. The shell adopts it immediately and skips `autoStart`.
936
- - **`@if (engine)`** acts as the async gate — the shell only mounts once the engine is ready, so there is no timing window where `autoStart` could fire before the engine arrives.
937
- - **`restoreOrStart()`** handles the load-or-create logic: if saved state exists on the server, it restores the engine mid-flow; otherwise it starts fresh.
938
-
939
- ---
940
-
941
- ## Styling
942
-
943
- Import the optional stylesheet for sensible default styles. All visual values are CSS custom properties (`--pw-*`) so you can theme without overriding selectors.
944
-
945
- ### In `angular.json` (recommended)
946
-
947
- ```json
948
- "styles": [
949
- "src/styles.css",
950
- "node_modules/@daltonr/pathwrite-angular/dist/index.css"
951
- ]
952
- ```
953
-
954
- ### In a global stylesheet
955
-
956
- ```css
957
- @import "@daltonr/pathwrite-angular/styles.css";
958
- ```
959
-
960
- ### Theming
961
-
962
- Override any `--pw-*` variable to customise the appearance:
963
-
964
- ```css
965
- :root {
966
- --pw-color-primary: #8b5cf6;
967
- --pw-shell-radius: 12px;
968
- }
969
- ```
970
-
971
- ### Available CSS Custom Properties
972
-
973
- **Layout:**
974
- - `--pw-shell-max-width` — Maximum width of the shell (default: `720px`)
975
- - `--pw-shell-padding` — Internal padding (default: `24px`)
976
- - `--pw-shell-gap` — Gap between header, body, footer (default: `20px`)
977
- - `--pw-shell-radius` — Border radius for cards (default: `10px`)
978
-
979
- **Colors:**
980
- - `--pw-color-bg` — Background color (default: `#ffffff`)
981
- - `--pw-color-border` — Border color (default: `#dbe4f0`)
982
- - `--pw-color-text` — Primary text color (default: `#1f2937`)
983
- - `--pw-color-muted` — Muted text color (default: `#5b677a`)
984
- - `--pw-color-primary` — Primary/accent color (default: `#2563eb`)
985
- - `--pw-color-primary-light` — Light primary for backgrounds (default: `rgba(37, 99, 235, 0.12)`)
986
- - `--pw-color-btn-bg` — Button background (default: `#f8fbff`)
987
- - `--pw-color-btn-border` — Button border (default: `#c2d0e5`)
988
-
989
- **Validation:**
990
- - `--pw-color-error` — Error text color (default: `#dc2626`)
991
- - `--pw-color-error-bg` — Error background (default: `#fef2f2`)
992
- - `--pw-color-error-border` — Error border (default: `#fecaca`)
993
-
994
- **Progress Indicator:**
995
- - `--pw-dot-size` — Step dot size (default: `32px`)
996
- - `--pw-dot-font-size` — Font size inside dots (default: `13px`)
997
- - `--pw-track-height` — Progress track height (default: `4px`)
998
-
999
- **Buttons:**
1000
- - `--pw-btn-padding` — Button padding (default: `8px 16px`)
1001
- - `--pw-btn-radius` — Button border radius (default: `6px`)
1002
-
1003
-
1004
- ---
1005
-
1006
- © 2026 Devjoy Ltd. MIT License.
1007
-
170
+ MIT — © 2026 Devjoy Ltd.