From c1801f878724278e6d8193a8229b4f3b55520447 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:54:51 -0500 Subject: [PATCH 1/6] Add failing specs for series nav, reactive slugs, dock state and lesson 04 --- src/app/shared/dock.service.spec.ts | 16 ++ .../lessons/lesson-04-signals.spec.ts | 68 ++++++++ .../thoughts-content/thought-detail.spec.ts | 152 +++++++++--------- 3 files changed, 157 insertions(+), 79 deletions(-) create mode 100644 src/app/thoughts-content/lessons/lesson-04-signals.spec.ts diff --git a/src/app/shared/dock.service.spec.ts b/src/app/shared/dock.service.spec.ts index 5eea98c..6c3f796 100644 --- a/src/app/shared/dock.service.spec.ts +++ b/src/app/shared/dock.service.spec.ts @@ -9,6 +9,22 @@ describe('DockService', () => { service = TestBed.inject(DockService); }); + it('exposes its state read-only, so only the service can change it', () => { + expect('set' in service.runningApps).toBe(false); + expect('set' in service.pinnedApps).toBe(false); + expect('set' in service.transientApps).toBe(false); + }); + + it('minimizeApp marks a running app minimized', () => { + service.minimizeApp('finder'); + expect(service.getState('finder')).toBe('minimized'); + }); + + it('minimizeApp ignores an app that is not running', () => { + service.minimizeApp('terminal'); + expect(service.isRunning('terminal')).toBe(false); + }); + it('should be created', () => { expect(service).toBeTruthy(); }); diff --git a/src/app/thoughts-content/lessons/lesson-04-signals.spec.ts b/src/app/thoughts-content/lessons/lesson-04-signals.spec.ts new file mode 100644 index 0000000..3ba7663 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-04-signals.spec.ts @@ -0,0 +1,68 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../../test/a11y'; +import { LESSON_PAGES } from './lessons'; +import { Lesson04Signals } from './lesson-04-signals'; + +expect.extend(axeMatchers); + +describe('Lesson04Signals', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + const text = (selector: string) => el.querySelector(selector)?.textContent ?? ''; + const effectRuns = () => el.querySelectorAll('.effect-log li').length; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson04Signals] }).compileComponents(); + fixture = TestBed.createComponent(Lesson04Signals); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-04-signals']).toBeDefined(); + }); + + it('teaches at three levels, then pitfalls and interview questions', () => { + const headings = [...el.querySelectorAll('h2')].map((h) => h.textContent?.trim()); + expect(headings).toEqual( + expect.arrayContaining(['Simple', 'Intermediate', 'Expert', 'Pitfalls', 'Interview questions']), + ); + }); + + it('computed total follows its inputs', async () => { + expect(text('#signal-total')).toContain('$12'); + el.querySelector('#bump-one')!.click(); + await fixture.whenStable(); + expect(text('#signal-total')).toContain('$24'); + }); + + it('three synchronous writes run the effect once, with the final value', async () => { + const before = effectRuns(); + el.querySelector('#bump-three')!.click(); + await fixture.whenStable(); + + expect(effectRuns()).toBe(before + 1); + expect(text('.effect-log li:last-child')).toContain('$48'); + }); + + it('linkedSignal resets the shipping choice when the country changes, but stays writable', async () => { + const choose = async (selector: string, value: string) => { + const select = el.querySelector(selector)!; + select.value = value; + select.dispatchEvent(new Event('change')); + await fixture.whenStable(); + }; + + await choose('#shipping', 'Express'); + expect(text('#shipping-choice')).toContain('Express'); + + await choose('#country', 'US'); + expect(text('#shipping-choice')).toContain('Ground'); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/thought-detail.spec.ts b/src/app/thoughts-content/thought-detail.spec.ts index 3f154bf..d130f67 100644 --- a/src/app/thoughts-content/thought-detail.spec.ts +++ b/src/app/thoughts-content/thought-detail.spec.ts @@ -1,120 +1,114 @@ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute, provideRouter, Router } from '@angular/router'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter, Router } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; import { ThoughtDetailComponent } from './thought-detail'; import { ThoughtsListComponent } from './thoughts-list'; +/** + * Driven through the real router (RouterTestingHarness) rather than a mocked + * ActivatedRoute. A snapshot mock can't express "the same component instance + * receives a new :slug", which is exactly what prev/next navigation does. + */ +async function openThought(slug: string) { + TestBed.configureTestingModule({ + providers: [ + provideRouter([ + { path: 'thoughts', component: ThoughtsListComponent }, + { path: 'thoughts/:slug', component: ThoughtDetailComponent }, + ]), + ], + }); + const harness = await RouterTestingHarness.create(); + const component = await harness.navigateByUrl(`/thoughts/${slug}`, ThoughtDetailComponent); + await harness.fixture.whenStable(); + return { harness, component, el: harness.routeNativeElement as HTMLElement }; +} + describe('ThoughtDetailComponent', () => { - let fixture: ComponentFixture; - let nativeEl: HTMLElement; - let router: Router; + let el: HTMLElement; + let harness: RouterTestingHarness; beforeEach(async () => { - await TestBed.configureTestingModule({ - imports: [ThoughtDetailComponent], - providers: [ - provideRouter([ - { path: 'thoughts', component: ThoughtsListComponent }, - { path: 'thoughts/:slug', component: ThoughtDetailComponent }, - ]), - { - provide: ActivatedRoute, - useValue: { - snapshot: { paramMap: { get: (key: string) => (key === 'slug' ? 'signals' : null) } }, - }, - }, - ], - }).compileComponents(); - - router = TestBed.inject(Router); - fixture = TestBed.createComponent(ThoughtDetailComponent); - fixture.detectChanges(); - nativeEl = fixture.nativeElement as HTMLElement; + ({ el, harness } = await openThought('signals')); }); it('should render the full thought content for the given route param', () => { - const title = nativeEl.querySelector('.thought-detail-title'); - const content = nativeEl.querySelector('.thought-detail-content'); - - expect(title?.textContent?.trim()).toBe('Why Angular Signals Changed Everything'); - expect(content?.textContent).toContain('fine-grained reactivity'); + expect(el.querySelector('.thought-detail-title')?.textContent?.trim()).toBe( + 'Why Angular Signals Changed Everything', + ); + expect(el.querySelector('.thought-detail-content')?.textContent).toContain('fine-grained reactivity'); }); it('should show a back button that navigates to the list', async () => { - const backBtn = nativeEl.querySelector('.thought-detail-back') as HTMLElement; - expect(backBtn).toBeTruthy(); - - backBtn.click(); - await fixture.whenStable(); + el.querySelector('.thought-detail-back')!.click(); + await harness.fixture.whenStable(); - expect(router.url).toBe('/thoughts'); + expect(TestBed.inject(Router).url).toBe('/thoughts'); }); it('should render Angular feature tags as pills/badges', () => { - const tags = nativeEl.querySelectorAll('.thought-tag'); - expect(tags.length).toBeGreaterThan(0); - - const tagTexts = Array.from(tags).map((t) => t.textContent?.trim()); + const tagTexts = [...el.querySelectorAll('.thought-tag')].map((t) => t.textContent?.trim()); expect(tagTexts).toContain('signals'); expect(tagTexts).toContain('angular'); }); it('formats the date in UTC, so a YYYY-MM-DD never slips to the day before', () => { // 'signals' is dated 2026-06-15. JS parses that as UTC midnight, so without - // the 'UTC' argument any timezone west of UTC renders June 14. - expect(nativeEl.querySelector('.thought-detail-date')?.textContent).toContain('Jun 15, 2026'); + // UTC formatting any timezone west of UTC renders June 14. + expect(el.querySelector('.thought-detail-date')?.textContent).toContain('Jun 15, 2026'); }); it('shows a reading time for a prose thought', () => { - expect(nativeEl.querySelector('.thought-detail-date')?.textContent).toContain('min read'); + expect(el.querySelector('.thought-detail-date')?.textContent).toContain('min read'); }); it('should set SEO metadata for the thought', () => { expect(document.title).toContain('Why Angular Signals Changed Everything'); }); + + it('renders no lesson page or series nav for a prose-only thought', () => { + expect(el.querySelector('[class^="lesson"]')).toBeNull(); + expect(el.querySelector('.series-nav')).toBeNull(); + }); }); describe('ThoughtDetailComponent with an interactive lesson page', () => { it('renders the lazily loaded lesson page under the prose', async () => { - await TestBed.configureTestingModule({ - imports: [ThoughtDetailComponent], - providers: [ - provideRouter([]), - { - provide: ActivatedRoute, - useValue: { - snapshot: { - paramMap: { - get: (key: string) => (key === 'slug' ? 'angular-01-project-structure' : null), - }, - }, - }, - }, - ], - }).compileComponents(); - - const fixture = TestBed.createComponent(ThoughtDetailComponent); - await fixture.whenStable(); - const el = fixture.nativeElement as HTMLElement; + const { el } = await openThought('angular-01-project-structure'); expect(el.querySelector('.thought-detail-title')?.textContent).toContain('Project structure'); expect(el.querySelector('app-lesson-01-structure')).toBeTruthy(); }); - it('renders no lesson page for a prose-only thought', async () => { - await TestBed.configureTestingModule({ - imports: [ThoughtDetailComponent], - providers: [ - provideRouter([]), - { - provide: ActivatedRoute, - useValue: { snapshot: { paramMap: { get: () => 'signals' } } }, - }, - ], - }).compileComponents(); - - const fixture = TestBed.createComponent(ThoughtDetailComponent); - await fixture.whenStable(); - - expect((fixture.nativeElement as HTMLElement).querySelector('[class^="lesson"]')).toBeNull(); + it('links to the previous and next lessons in the series', async () => { + const { el } = await openThought('angular-02-components'); + const nav = el.querySelector('nav.series-nav')!; + + expect(nav.getAttribute('aria-label')).toBe('Angular guide'); + const links = [...nav.querySelectorAll('a')]; + expect(links.map((a) => a.getAttribute('href'))).toEqual([ + '/thoughts/angular-01-project-structure', + '/thoughts/angular-03-templates', + ]); + expect(nav.textContent).toContain('Part 2 of'); + }); + + it('has no previous link on the first lesson', async () => { + const { el } = await openThought('angular-01-project-structure'); + const hrefs = [...el.querySelectorAll('nav.series-nav a')].map((a) => a.getAttribute('href')); + + expect(hrefs).toEqual(['/thoughts/angular-02-components']); + }); + + it('follows a param change on the same component instance (no stale snapshot)', async () => { + const { harness, component, el } = await openThought('angular-01-project-structure'); + + const reused = await harness.navigateByUrl('/thoughts/angular-02-components', ThoughtDetailComponent); + await harness.fixture.whenStable(); + + expect(reused).toBe(component); + expect(el.querySelector('.thought-detail-title')?.textContent).toContain('Components'); + expect(el.querySelector('app-lesson-02-components')).toBeTruthy(); + expect(el.querySelector('app-lesson-01-structure')).toBeNull(); }); }); From cd5d5fdb17d62c5afe361de25e1d97e792ac510a Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:55:47 -0500 Subject: [PATCH 2/6] Add a failing spec for scrolling to the top between lessons --- src/app/thoughts-content/thought-detail.spec.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/app/thoughts-content/thought-detail.spec.ts b/src/app/thoughts-content/thought-detail.spec.ts index d130f67..ec840c7 100644 --- a/src/app/thoughts-content/thought-detail.spec.ts +++ b/src/app/thoughts-content/thought-detail.spec.ts @@ -111,4 +111,15 @@ describe('ThoughtDetailComponent with an interactive lesson page', () => { expect(el.querySelector('app-lesson-02-components')).toBeTruthy(); expect(el.querySelector('app-lesson-01-structure')).toBeNull(); }); + + it('scrolls back to the top when the slug changes, since the component is reused', async () => { + const { harness } = await openThought('angular-01-project-structure'); + const host = harness.routeNativeElement!.closest('app-thought-detail') as HTMLElement; + host.scrollTop = 500; + + await harness.navigateByUrl('/thoughts/angular-02-components', ThoughtDetailComponent); + await harness.fixture.whenStable(); + + expect(host.scrollTop).toBe(0); + }); }); From 6174aac403186978d1b0b63dca5824d34b28a95f Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:56:30 -0500 Subject: [PATCH 3/6] Make dock state read-only and give minimize one home --- src/app/app.ts | 7 +---- src/app/menu-bar/menu-bar.service.ts | 7 +---- src/app/shared/dock.service.ts | 39 +++++++++++++++++++++------- 3 files changed, 32 insertions(+), 21 deletions(-) diff --git a/src/app/app.ts b/src/app/app.ts index 708be3c..aa9a9ed 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -139,12 +139,7 @@ export class App { onWindowMinimized(windowId: string, appId: string): void { this.windowManager.minimizeWindow(windowId); - const running = this.dockService.runningApps(); - if (running.has(appId)) { - const map = new Map(running); - map.set(appId, 'minimized'); - this.dockService.runningApps.set(map); - } + this.dockService.minimizeApp(appId); } onWindowMaximized(windowId: string): void { diff --git a/src/app/menu-bar/menu-bar.service.ts b/src/app/menu-bar/menu-bar.service.ts index 775fc13..5e5ea39 100644 --- a/src/app/menu-bar/menu-bar.service.ts +++ b/src/app/menu-bar/menu-bar.service.ts @@ -204,12 +204,7 @@ export class MenuBarService { const win = this.activeWindow(); if (!win) return; this.windowManager.minimizeWindow(win.id); - const running = this.dock.runningApps(); - if (running.has(win.appId)) { - const map = new Map(running); - map.set(win.appId, 'minimized'); - this.dock.runningApps.set(map); - } + this.dock.minimizeApp(win.appId); } private zoomActiveWindow(): void { diff --git a/src/app/shared/dock.service.ts b/src/app/shared/dock.service.ts index 1be13ed..08cfffb 100644 --- a/src/app/shared/dock.service.ts +++ b/src/app/shared/dock.service.ts @@ -10,6 +10,15 @@ export interface DockItem { export type AppState = 'running' | 'focused' | 'minimized'; +/** + * [ng-04 signals] A signal store: private writable signals, public read-only + * views, and methods that are the only way to change state. + * + * runningApps used to be a public WritableSignal, and both app.ts and + * menu-bar.service.ts had grown their own copy of "minimize this app" that + * wrote the Map directly. asReadonly() makes that a compile error, and + * minimizeApp() is now the one place the rule lives. + */ @Injectable({ providedIn: 'root' }) export class DockService { readonly pinnedApps = signal([ @@ -20,13 +29,15 @@ export class DockService { { id: 'thoughts', label: 'Thoughts', icon: 'πŸ’­', color: '#FF9800', pinned: true }, { id: 'settings', label: 'Settings', icon: 'βš™οΈ', color: '#607D8B', pinned: true }, { id: 'contact', label: 'Contact', icon: 'βœ‰οΈ', color: '#03A9F4', pinned: true }, - ]); + ]).asReadonly(); + private readonly runningAppsState = signal>(new Map([['finder', 'focused']])); /** Map of app id β†’ current state */ - readonly runningApps = signal>(new Map([['finder', 'focused']])); + readonly runningApps = this.runningAppsState.asReadonly(); + private readonly transientAppsState = signal([]); /** Apps running but not pinned β€” shown after the separator */ - readonly transientApps = signal([]); + readonly transientApps = this.transientAppsState.asReadonly(); readonly focusedAppId = computed(() => { for (const [id, state] of this.runningApps()) { @@ -64,7 +75,7 @@ export class DockService { } else if (currentState === 'focused') { // Already focused β€” minimize all windows of this app running.set(app.id, 'minimized'); - this.runningApps.set(running); + this.runningAppsState.set(running); } else { // Running but not focused (minimized or background) β€” focus it this.focusApp(app.id, running); @@ -82,11 +93,11 @@ export class DockService { } map.set(app.id, 'focused'); - this.runningApps.set(map); + this.runningAppsState.set(map); // If app is not pinned and not already transient, add it if (!app.pinned && !this.transientApps().some((a) => a.id === app.id)) { - this.transientApps.update((apps) => [...apps, app]); + this.transientAppsState.update((apps) => [...apps, app]); } } @@ -100,15 +111,25 @@ export class DockService { } map.set(appId, 'focused'); - this.runningApps.set(map); + this.runningAppsState.set(map); + } + + /** Mark a running app minimized. An app that isn't running stays not running. */ + minimizeApp(appId: string): void { + if (!this.runningApps().has(appId)) return; + // A new Map, not running.set() on the current one: a signal compares by + // reference, so mutating in place would notify nobody. + const running = new Map(this.runningApps()); + running.set(appId, 'minimized'); + this.runningAppsState.set(running); } closeApp(appId: string): void { const running = new Map(this.runningApps()); running.delete(appId); - this.runningApps.set(running); + this.runningAppsState.set(running); // Remove from transient if present - this.transientApps.update((apps) => apps.filter((a) => a.id !== appId)); + this.transientAppsState.update((apps) => apps.filter((a) => a.id !== appId)); } } From aea96ebd7350c0837e3de686426eee43740de306 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:56:30 -0500 Subject: [PATCH 4/6] Drive the reader from a slug signal and add series navigation --- src/app/thoughts-content/lessons/lesson.ts | 2 +- src/app/thoughts-content/thought-detail.ts | 81 ++++++++++++++++--- .../thoughts-content/thoughts.service.spec.ts | 13 +++ src/app/thoughts-content/thoughts.service.ts | 17 +++- 4 files changed, 100 insertions(+), 13 deletions(-) diff --git a/src/app/thoughts-content/lessons/lesson.ts b/src/app/thoughts-content/lessons/lesson.ts index 01cdf94..0c4f75e 100644 --- a/src/app/thoughts-content/lessons/lesson.ts +++ b/src/app/thoughts-content/lessons/lesson.ts @@ -16,7 +16,7 @@ import { Component, input, ViewEncapsulation } from '@angular/core'; encapsulation: ViewEncapsulation.None, template: `
-

Angular guide Β· {{ part() }} of 13

+

Angular guide Β· Part {{ part() }}

`, diff --git a/src/app/thoughts-content/thought-detail.ts b/src/app/thoughts-content/thought-detail.ts index 21fa16b..35169ac 100644 --- a/src/app/thoughts-content/thought-detail.ts +++ b/src/app/thoughts-content/thought-detail.ts @@ -1,6 +1,8 @@ import { NgComponentOutlet } from '@angular/common'; -import { Component, inject, resource } from '@angular/core'; -import { ActivatedRoute, Router } from '@angular/router'; +import { Component, computed, effect, ElementRef, inject, resource } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { ActivatedRoute, Router, RouterLink } from '@angular/router'; +import { map } from 'rxjs'; import { SeoService } from '../shared/seo.service'; import { LESSON_PAGES } from './lessons/lessons'; import { ReadingTimePipe } from './reading-time.pipe'; @@ -9,9 +11,9 @@ import { ThoughtsService } from './thoughts.service'; @Component({ selector: 'app-thought-detail', - imports: [NgComponentOutlet, UtcDatePipe, ReadingTimePipe], + imports: [NgComponentOutlet, RouterLink, UtcDatePipe, ReadingTimePipe], template: ` - @if (thought) { + @if (thought(); as thought) {

{{ thought.title }}

@@ -19,7 +21,7 @@ import { ThoughtsService } from './thoughts.service'; that, and why not Angular's own DatePipe. -->
- @if (!hasLessonPage) { + @if (!hasLessonPage()) { Β· {{ thought.content | readingTime }} }
@@ -32,6 +34,17 @@ import { ThoughtsService } from './thoughts.service'; @if (lessonPage.value(); as page) { } + @if (series(); as series) { + + }
} @else {
Thought not found.
@@ -100,6 +113,27 @@ import { ThoughtsService } from './thoughts.service'; white-space: pre-wrap; } + .series-nav { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; + margin-top: 32px; + padding-top: 16px; + border-top: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); + font-size: 13px; + } + .series-nav-position { + flex-basis: 100%; + color: var(--text-secondary, rgba(255, 255, 255, 0.5)); + } + .series-nav a { + color: var(--accent-color, #007aff); + } + .series-nav-next { + margin-left: auto; + } + .thought-detail-not-found { padding: 32px; text-align: center; @@ -113,22 +147,47 @@ export class ThoughtDetailComponent { private readonly service = inject(ThoughtsService); private readonly seo = inject(SeoService); - readonly thought = this.service.getBySlug(this.route.snapshot.paramMap.get('slug') ?? ''); + private readonly host = inject>(ElementRef); + + // [ng-04 signals] The slug is a signal, and everything else derives from it. + // + // This used to read route.snapshot once. The router reuses this component + // when only :slug changes (lesson 01 β†’ Next β†’ lesson 02), so the snapshot + // went stale and the page kept showing lesson 01. paramMap is an Observable + // that emits on every change. toSignal() bridges it, and requireSync works + // because ActivatedRoute replays the current params synchronously. + private readonly slug = toSignal( + this.route.paramMap.pipe(map((params) => params.get('slug') ?? '')), + { requireSync: true }, + ); + // computed(): derived, memoised, recomputed only when slug() changes. + readonly thought = computed(() => this.service.getBySlug(this.slug())); + readonly series = computed(() => this.service.getSeriesPosition(this.slug(), 'angular-guide')); // Lesson pages are mostly interactive, so a word count of the intro would undersell them. - readonly hasLessonPage = !!this.thought && this.thought.slug in LESSON_PAGES; + readonly hasLessonPage = computed(() => this.slug() in LESSON_PAGES); // A resource rather than a bare promise: while it loads it holds a pending // task, so SSR prerendering waits for the lesson chunk and bakes the full // interactive page into the static HTML instead of an empty slot. + // `params` makes it reactive: a new slug aborts the old load and starts a new one. readonly lessonPage = resource({ - loader: () => LESSON_PAGES[this.thought?.slug ?? '']?.() ?? Promise.resolve(undefined), + params: () => this.slug(), + loader: ({ params: slug }) => LESSON_PAGES[slug]?.() ?? Promise.resolve(undefined), }); constructor() { - if (this.thought) { - this.seo.setThoughtMeta(this.thought); - } + // effect(): for side effects that leave the signal graph, here the + // document head and the DOM scroll position. Never use one to copy a + // signal into another signal; that's what computed() is for. + effect(() => { + const thought = this.thought(); + if (thought) this.seo.setThoughtMeta(thought); + }); + effect(() => { + this.slug(); + this.host.nativeElement.scrollTop = 0; + }); } goBack() { diff --git a/src/app/thoughts-content/thoughts.service.spec.ts b/src/app/thoughts-content/thoughts.service.spec.ts index 8de8271..9c579f4 100644 --- a/src/app/thoughts-content/thoughts.service.spec.ts +++ b/src/app/thoughts-content/thoughts.service.spec.ts @@ -46,6 +46,19 @@ describe('ThoughtsService', () => { } }); + it('getSeriesPosition places a lesson among its series, in publication order', () => { + const position = service.getSeriesPosition('angular-02-components', 'angular-guide'); + + expect(position?.index).toBe(1); + expect(position?.total).toBe(THOUGHTS.filter((t) => t.tags.includes('angular-guide')).length); + expect(position?.previous?.slug).toBe('angular-01-project-structure'); + expect(position?.next?.slug).toBe('angular-03-templates'); + }); + + it('getSeriesPosition is undefined for a thought outside the series', () => { + expect(service.getSeriesPosition('signals', 'angular-guide')).toBeUndefined(); + }); + it('getBySlug returns undefined for a non-existent slug', () => { const thought = service.getBySlug('does-not-exist'); diff --git a/src/app/thoughts-content/thoughts.service.ts b/src/app/thoughts-content/thoughts.service.ts index 802bd02..33552f6 100644 --- a/src/app/thoughts-content/thoughts.service.ts +++ b/src/app/thoughts-content/thoughts.service.ts @@ -5,7 +5,14 @@ import { THOUGHTS, ThoughtEntry } from './thoughts-data'; /** A thought with its prose joined back on, which is what the reader actually renders. */ export type ThoughtWithContent = ThoughtEntry & { content: string }; -const withBody = (entry: ThoughtEntry): ThoughtWithContent => ({ +export interface SeriesPosition { + index: number; + total: number; + previous?: ThoughtEntry; + next?: ThoughtEntry; +} + +const withBody =(entry: ThoughtEntry): ThoughtWithContent => ({ ...entry, content: THOUGHT_BODIES[entry.slug] ?? '', }); @@ -23,6 +30,14 @@ export class ThoughtsService { return entry && withBody(entry); } + /** Where a thought sits in a tagged series. THOUGHTS order is publication order. */ + getSeriesPosition(slug: string, seriesTag: string): SeriesPosition | undefined { + const series = THOUGHTS.filter((t) => t.tags.includes(seriesTag)); + const index = series.findIndex((t) => t.slug === slug); + if (index === -1) return undefined; + return { index, total: series.length, previous: series[index - 1], next: series[index + 1] }; + } + getByTag(tag: string): ThoughtWithContent[] { return THOUGHTS.filter((t) => t.tags.includes(tag)).map(withBody); } From 3125c5226a5f1a21ce46b6bbb894145ab75738ed Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:58:20 -0500 Subject: [PATCH 5/6] Write lesson 04 with effect-batching and linkedSignal demos --- .../lessons/lesson-04-signals.ts | 271 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 1 + src/app/thoughts-content/thoughts-bodies.ts | 3 + src/app/thoughts-content/thoughts-data.ts | 9 + 4 files changed, 284 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-04-signals.ts diff --git a/src/app/thoughts-content/lessons/lesson-04-signals.ts b/src/app/thoughts-content/lessons/lesson-04-signals.ts new file mode 100644 index 0000000..2d2c813 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-04-signals.ts @@ -0,0 +1,271 @@ +import { Component, computed, effect, linkedSignal, signal, untracked } from '@angular/core'; +import { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; + +const UNIT_PRICE = 12; + +type Country = 'CA' | 'US'; +const SHIPPING: Record = { + CA: ['Standard', 'Express'], + US: ['Ground', 'Express', 'Overnight'], +}; + +@Component({ + selector: 'app-lesson-04-signals', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions], + template: ` + +

Simple

+

+ A signal is a value that tells Angular when it changes. Create one with + signal(initial), read it by calling it, and change it with + .set() or .update(). Any template that reads a signal re-renders + when it changes. That's how this app runs without Zone.js: Angular knows exactly which + views read what. +

+

+ computed() derives a value from other signals. It's lazy and memoised: it + recalculates only when a signal it read has changed, and only when someone reads it. +

+ + +
+ Quantity: {{ quantity() }} Γ— \${{ unitPrice }} + + +
+

computed total: \${{ total() }}

+

Effect runs (newest last):

+
    + @for (entry of effectLog(); track $index) { +
  1. {{ entry }}
  2. + } +
+

+ Press the second button: three writes, one effect run. Effects are scheduled, not + synchronous, so they see the settled value. +

+
+ + +

Intermediate

+

+ Signals compare by reference. set() with the same object + notifies nobody, so state must be replaced, not mutated. This site's + DockService builds a new Map on every change for that reason. + This lesson also made the service a proper store: private writable signals, + public asReadonly() views, and methods as the only way in. Before that, two + other files had their own copy of the "minimize" logic and wrote its Map directly. +

+ +

+ linkedSignal() is a writable signal that resets whenever its source changes. + It's the answer to "derived, but the user can override it": +

+ + +
+ + + + +
+

Selected: {{ shipping() }}

+

Pick Express, then change country: the choice resets to that country's default.

+
+ + +

+ Interop. toSignal() turns an Observable into a signal and + toObservable() goes the other way. The thought reader you're in uses it. It + used to read route.snapshot once, and since the router reuses the component + when only :slug changes, the series links (Part N of M, below) would have + shown the old lesson. Now the slug is a signal and everything derives from it. +

+ + +

Expert

+

+ resource() is async state as signals: params + (reactive input), loader (returns a promise and gets an + abortSignal), and value(), status(), + error(), isLoading() out. When params change it aborts the old + load. It also registers a pending task, which is why SSR waits for the lesson chunk before + serialising this page. httpResource() is the same shape over HttpClient. +

+

+ Effect timing. Component effects run during change detection, before + the view that owns them is checked. Root effects run as their own task. Neither runs + synchronously on set(), which is what batches the demo above. For DOM work + after render, use afterRenderEffect() or afterNextRender(). +

+ +

+ Signals are glitch-free: a computed never observes a half-updated graph. Writes mark + dependents dirty (push), and values are recomputed only when read (pull). That's why + reading total() ten times costs one multiplication. +

+
+

+ Signals don't replace RxJS. They hold state; Observables model + events over time: debouncing, cancellation, websockets, retries. Lesson 06 is that + boundary. At scale, NgRx SignalStore formalises the store pattern above. +

+ +

Pitfalls

+ +

+ Mutating the value inside a signal. + items().push(x) changes the array and notifies nothing. Use + items.update((list) => [...list, x]). +

+
+ +

+ Using effect() to copy one signal into another. That's a + computed(), or a linkedSignal() if it must stay writable. + Effects are for leaving the signal world: DOM, storage, logging, analytics. +

+
+ +

+ Reading a signal inside setTimeout or a promise callback + in an effect doesn't track it. Only synchronous reads during the effect body count. +

+
+ +

+ toSignal(), effect() and inject() need an + injection context. Call them in a field initialiser or constructor, not in + ngOnInit or a click handler, or pass an injector explicitly. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .effect-log { + margin: 4px 0 8px; + font-size: 13px; + } + .demo-note { + font-size: 12px; + } + `, +}) +export class Lesson04Signals { + protected readonly unitPrice = UNIT_PRICE; + protected readonly quantity = signal(1); + protected readonly total = computed(() => this.quantity() * UNIT_PRICE); + protected readonly effectLog = signal([]); + + protected readonly country = signal('CA'); + protected readonly shippingOptions = computed(() => SHIPPING[this.country()]); + // Resets to the first option whenever shippingOptions changes; set() still works in between. + protected readonly shipping = linkedSignal(() => this.shippingOptions()[0]); + + constructor() { + effect(() => { + const total = this.total(); + // untracked: this effect depends on total only. Without it, reading the + // log while updating it would make the effect depend on its own output. + untracked(() => this.effectLog.update((log) => [...log, `effect ran: total is $${total}`])); + }); + } + + protected bumpOne(): void { + this.quantity.update((n) => n + 1); + } + + protected bumpThree(): void { + this.quantity.update((n) => n + 1); + this.quantity.update((n) => n + 1); + this.quantity.update((n) => n + 1); + } + + protected valueOf(event: Event): T { + return (event.target as HTMLSelectElement).value as T; + } + + protected readonly snippets = { + basics: `quantity = signal(1); +total = computed(() => this.quantity() * 12); + +constructor() { + effect(() => { + const total = this.total(); // tracked: re-runs when total changes + untracked(() => this.log.update((log) => [...log, \`total is $\${total}\`])); + }); +} + +bumpThree() { + this.quantity.update((n) => n + 1); // three writes... + this.quantity.update((n) => n + 1); + this.quantity.update((n) => n + 1); // ...one effect run, seeing 4 +}`, + store: `private readonly runningAppsState = signal>(new Map()); +readonly runningApps = this.runningAppsState.asReadonly(); // no .set() outside + +minimizeApp(appId: string): void { + if (!this.runningApps().has(appId)) return; + const running = new Map(this.runningApps()); // replace, never mutate + running.set(appId, 'minimized'); + this.runningAppsState.set(running); +}`, + linked: `country = signal<'CA' | 'US'>('CA'); +shippingOptions = computed(() => SHIPPING[this.country()]); +shipping = linkedSignal(() => this.shippingOptions()[0]); + +// shipping.set('Express') works; changing country resets it to the new first option`, + reader: `private readonly slug = toSignal( + this.route.paramMap.pipe(map((params) => params.get('slug') ?? '')), + { requireSync: true }, +); + +readonly thought = computed(() => this.service.getBySlug(this.slug())); +readonly series = computed(() => this.service.getSeriesPosition(this.slug(), 'angular-guide')); +readonly lessonPage = resource({ + params: () => this.slug(), + loader: ({ params: slug }) => LESSON_PAGES[slug]?.() ?? Promise.resolve(undefined), +});`, + }; + + protected readonly interview = [ + { + q: 'What problem do signals solve compared to Zone.js change detection?', + a: 'Zone.js patched every async API and re-checked the whole component tree after any event, because Angular could not know what changed. Signals record exactly which views read which values, so Angular can refresh only what depends on a change. That enables zoneless apps: smaller bundles, cleaner stack traces, less wasted work.', + }, + { + q: 'signal vs computed vs effect vs linkedSignal?', + a: 'signal holds writable state. computed derives read-only state, lazily and memoised. linkedSignal derives state that can also be written locally and resets when its source changes. effect runs side effects outside the signal graph, such as the DOM, storage or logging, and should not be used to sync signals.', + }, + { + q: 'Why does updating an array inside a signal sometimes not re-render?', + a: 'Signals use Object.is equality by default. Mutating the existing array keeps the same reference, so nothing is notified. Replace it instead, with update(list => [...list, item]), or supply a custom equal function if you really need one.', + }, + { + q: 'When would you still use RxJS?', + a: 'For events over time: debouncing input, cancelling in-flight requests with switchMap, websockets, retries and polling. Signals are for current state. toSignal and toObservable bridge the two at the edges.', + }, + { + q: 'How do you expose state from a service safely?', + a: 'Keep writable signals private and expose asReadonly() views plus methods that encode the allowed transitions. Consumers then get reactivity without being able to bypass the rules. Components get computed() views where they need derived data.', + }, + { + q: 'What is resource() and when is it better than subscribing?', + a: 'A signal-based async primitive. You give it reactive params and a loader, and it exposes value, status, error and isLoading as signals. It cancels stale loads when params change and registers as a pending task, so SSR waits for it. It replaces the subscribe-and-set-loading-flags boilerplate in most read-only data fetching.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index 74f93c6..127322c 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -14,4 +14,5 @@ export const LESSON_PAGES: Record Promise>> = { import('./lesson-02-components').then((m) => m.Lesson02Components), 'angular-03-templates': () => import('./lesson-03-templates').then((m) => m.Lesson03Templates), + 'angular-04-signals': () => import('./lesson-04-signals').then((m) => m.Lesson04Signals), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 2315cbe..818c0e5 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -253,4 +253,7 @@ That makes components the natural topic: what goes in through inputs, what comes 'angular-03-templates': `Templates are where most Angular bugs live, because a binding looks right whether or not it is. Writing this lesson turned up two in this site. The desktop's keydown handler called the shortcut service twice per event, so the Spotlight shortcut opened it and closed it again in the same keypress. And every thought date was printed raw. The obvious fix, the date pipe, would have shown the day before for anyone behind UTC, because a bare YYYY-MM-DD parses as UTC midnight. Both are fixed now, and both are in the lesson as the pitfalls they are.`, + 'angular-04-signals': `The series needed previous and next links, and adding them exposed a bug that had been waiting all along. The reader read its slug from the route snapshot once. The router reuses the component when only the slug changes, so clicking Next would have kept showing the lesson you were already on. The fix was to make the slug a signal and derive everything else from it, which is the whole idea of this lesson. + +The same pass turned the dock's state into a proper store. Two other files had each written their own copy of "minimize this app" straight into the dock's Map. Now that state is read-only from outside, and the rule lives in one method.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index 94337fd..ac66be6 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -215,4 +215,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'templates', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-04-signals', + title: 'Angular 04: Signals', + date: '2026-11-21', + summary: + 'signal, computed, effect, linkedSignal and resource, with demos of effect batching and a resettable selection. Built while making the reader follow its route and adding the previous/next links at the bottom of every lesson.', + tags: ['angular-guide', 'signals', 'angular'], + relatedApp: 'readme', + }, ]; From bba79c72b3ba92eb2ad44135c094f8b3ed4f0742 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:58:33 -0500 Subject: [PATCH 6/6] Bump to 1.4.3 with the lesson 04 changelog entry --- CHANGELOG.md | 10 ++++++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f242993..c3a455b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. +## 2026-11-21 - version 1.4.3 + +- **Series navigation in the reader**: every Angular guide lesson ends with "Part N of M" and links to the previous and next lessons. They're real `routerLink` anchors, so they prerender as `href`s and ⌘-click opens a new tab +- **fix: the reader went stale on reuse.** `thought-detail.ts` read `route.snapshot` once, and the router reuses the component when only `:slug` changes, so Next would have kept showing the lesson you were on. The slug is now a signal (`toSignal(route.paramMap)`), and the thought, series position and lazy lesson page are all `computed()`/`resource()` off it. The reader also scrolls back to the top when the slug changes +- The reader specs now drive the real router through `RouterTestingHarness` instead of mocking `ActivatedRoute.snapshot`. A snapshot mock can't express a reused component getting a new param, which is how the bug hid +- **Dock state is read-only from outside.** `DockService` keeps private writable signals and exposes `asReadonly()` views. `app.ts` and `menu-bar.service.ts` each had their own copy of "minimize this app" writing the Map directly; both now call `minimizeApp()` +- **Angular guide, lesson 04: signals** (`/thoughts/angular-04-signals`). Demos show three synchronous writes producing one effect run, and a `linkedSignal` shipping choice that resets when the country changes but stays writable +- The lesson kicker says "Part 04" instead of "04 of 13", so the page doesn't show two different totals now that the series nav counts what's actually published +- Initial bundle 377.25 kB β†’ 384.14 kB. I measured it rather than guessed: a build without `RouterLink` is 377.83 kB, so the router's link directive is the 6.3 kB. I'm keeping it, because real prerendered links and correct modifier-click handling are worth it and later lessons reuse it, but there's now 16 kB of headroom under the 400 kB budget + ## 2026-11-21 - version 1.4.2 - **fix: βŒƒβŒ₯Space never opened Spotlight.** `App.onKeydown` called `shortcuts.handleKeydown(event)` twice per keydown, so every toggle shortcut flipped and flipped straight back, and βŒƒβŒ₯Tab cycled two windows at a time. It's now bound once through `host: { '(document:keydown)': … }` instead of `@HostListener` diff --git a/package-lock.json b/package-lock.json index 13b79f9..9812255 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.2", + "version": "1.4.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.2", + "version": "1.4.3", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index bfb73ae..1eeadac 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.2", + "version": "1.4.3", "scripts": { "ng": "ng", "start": "ng serve",