diff --git a/CHANGELOG.md b/CHANGELOG.md index c3a455b..788c695 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to this project will be documented in this file. +## 2026-11-21 - version 1.4.4 + +- **Saved reading progress for the Angular guide**: every lesson ends with a "Mark lesson complete" toggle (a real `aria-pressed` button whose label changes too, so the state isn't colour alone). The series nav counts "N of M complete", and the Thoughts list badges completed lessons. Progress is kept in localStorage +- **Browser storage is an injection token now.** `BROWSER_STORAGE` is localStorage in the browser and `null` during prerendering, decided once in its factory. `SettingsService` used to check `isPlatformBrowser` and reach for the global itself, in two places. Reading progress would have been the third copy, so both now inject the token, and specs hand in an in-memory `Storage` instead of clearing the real one +- Saved progress that isn't a list of slugs throws with the bad value in the message, instead of quietly resetting someone's progress to nothing +- **Angular guide, lesson 05: dependency injection** (`/thoughts/angular-05-dependency-injection`). A live demo puts buttons under one shared provider and under one provider each, so the injector tree is something to click rather than a diagram. The demo's instance numbers come from a provider on the page, not a module-level counter. A counter would keep counting across requests on a long-running server, which is the exact SSR leak the lesson warns about +- Initial bundle 384.14 kB → 384.98 kB for the progress service and toggle. The lesson itself is a 14 kB lazy chunk + ## 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 diff --git a/package-lock.json b/package-lock.json index 9812255..5195c24 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.3", + "version": "1.4.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.3", + "version": "1.4.4", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index 1eeadac..db931f8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.3", + "version": "1.4.4", "scripts": { "ng": "ng", "start": "ng serve", diff --git a/src/app/shared/browser-storage.spec.ts b/src/app/shared/browser-storage.spec.ts new file mode 100644 index 0000000..48ab7a1 --- /dev/null +++ b/src/app/shared/browser-storage.spec.ts @@ -0,0 +1,14 @@ +import { PLATFORM_ID } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { BROWSER_STORAGE } from './browser-storage'; + +describe('BROWSER_STORAGE', () => { + it('is localStorage in the browser', () => { + expect(TestBed.inject(BROWSER_STORAGE)).toBe(localStorage); + }); + + it('is null on the server, so callers must handle there being no storage', () => { + TestBed.configureTestingModule({ providers: [{ provide: PLATFORM_ID, useValue: 'server' }] }); + expect(TestBed.inject(BROWSER_STORAGE)).toBeNull(); + }); +}); diff --git a/src/app/shared/browser-storage.ts b/src/app/shared/browser-storage.ts new file mode 100644 index 0000000..08e1db8 --- /dev/null +++ b/src/app/shared/browser-storage.ts @@ -0,0 +1,22 @@ +import { isPlatformBrowser } from '@angular/common'; +import { inject, InjectionToken, PLATFORM_ID } from '@angular/core'; + +// [ng-05 di] An InjectionToken is how you inject something that isn't a class: +// an interface, a config object, a browser global. Storage is an interface, so +// it can't be its own token; this constant is the key the injector looks up. +// +// providedIn: 'root' + factory makes it tree-shakable and self-providing: no +// one has to remember to add it to app.config.ts, and it's dropped from the +// bundle if nothing injects it. +// +// The factory runs in an injection context, so it can inject() too. It +// decides once, in one place, what "storage" means on each platform. The +// server has no localStorage, so it gets null and every caller has to deal +// with that, which the type makes them do. +// +// Specs and SSR swap it with { provide: BROWSER_STORAGE, useValue: ... }. +// That's the point: services depend on the token, never on the global. +export const BROWSER_STORAGE = new InjectionToken('BROWSER_STORAGE', { + providedIn: 'root', + factory: () => (isPlatformBrowser(inject(PLATFORM_ID)) ? localStorage : null), +}); diff --git a/src/app/shared/settings/settings.service.spec.ts b/src/app/shared/settings/settings.service.spec.ts index 5fa8052..55118d6 100644 --- a/src/app/shared/settings/settings.service.spec.ts +++ b/src/app/shared/settings/settings.service.spec.ts @@ -1,4 +1,6 @@ import { TestBed } from '@angular/core/testing'; +import { createMemoryStorage } from '../../../test/memory-storage'; +import { BROWSER_STORAGE } from '../browser-storage'; import { SettingsService } from './settings.service'; describe('SettingsService', () => { @@ -76,4 +78,27 @@ describe('SettingsService', () => { expect(restored.dockSize()).toBe(80); expect(restored.accentColor()).toBe('#ff0000'); }); + + it('reads and writes through BROWSER_STORAGE, so a spec or the server can swap it', () => { + const storage = createMemoryStorage({ settings: JSON.stringify({ theme: 'light' }) }); + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ providers: [{ provide: BROWSER_STORAGE, useValue: storage }] }); + const injected = TestBed.inject(SettingsService); + + expect(injected.theme()).toBe('light'); + injected.setDockSize(40); + TestBed.flushEffects(); + expect(JSON.parse(storage.getItem('settings')!).dockSize).toBe(40); + }); + + it('uses the defaults and saves nothing when there is no storage', () => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ providers: [{ provide: BROWSER_STORAGE, useValue: null }] }); + const serverSide = TestBed.inject(SettingsService); + + serverSide.setTheme('light'); + TestBed.flushEffects(); + expect(serverSide.theme()).toBe('light'); + expect(localStorage.getItem('settings')).toBeNull(); + }); }); diff --git a/src/app/shared/settings/settings.service.ts b/src/app/shared/settings/settings.service.ts index 730daf6..5e44d22 100644 --- a/src/app/shared/settings/settings.service.ts +++ b/src/app/shared/settings/settings.service.ts @@ -4,8 +4,8 @@ // business. It sat in apps/settings/ until architecture.spec.ts flagged three // shell files importing it. The *screen* that edits it (system-preferences.ts) // stays in the feature folder. The *state* moved down a layer. -import { effect, Injectable, PLATFORM_ID, inject, signal } from '@angular/core'; -import { isPlatformBrowser } from '@angular/common'; +import { effect, Injectable, inject, signal } from '@angular/core'; +import { BROWSER_STORAGE } from '../browser-storage'; export type Theme = 'dark' | 'light'; export type ClockFormat = '12h' | '24h'; @@ -31,7 +31,11 @@ const DEFAULTS: SettingsData = { @Injectable({ providedIn: 'root' }) export class SettingsService { - private readonly platformId = inject(PLATFORM_ID); + // [ng-05 di] This used to inject PLATFORM_ID and reach for the global + // localStorage behind an isPlatformBrowser() check, twice. Depending on the + // token instead means the platform decision lives in one factory, and a + // spec can hand in its own Storage instead of clearing the real one. + private readonly storage = inject(BROWSER_STORAGE); private readonly initial = this.loadFromStorage(); readonly theme = signal(this.initial.theme); @@ -74,9 +78,9 @@ export class SettingsService { } private loadFromStorage(): SettingsData { - if (!isPlatformBrowser(this.platformId)) return { ...DEFAULTS }; + if (!this.storage) return { ...DEFAULTS }; try { - const raw = localStorage.getItem(STORAGE_KEY); + const raw = this.storage.getItem(STORAGE_KEY); if (!raw) return { ...DEFAULTS }; return { ...DEFAULTS, ...JSON.parse(raw) }; } catch { @@ -85,7 +89,6 @@ export class SettingsService { } private saveToStorage(data: SettingsData) { - if (!isPlatformBrowser(this.platformId)) return; - localStorage.setItem(STORAGE_KEY, JSON.stringify(data)); + this.storage?.setItem(STORAGE_KEY, JSON.stringify(data)); } } diff --git a/src/app/thoughts-content/lessons/lesson-05-di.spec.ts b/src/app/thoughts-content/lessons/lesson-05-di.spec.ts new file mode 100644 index 0000000..11a4cfa --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-05-di.spec.ts @@ -0,0 +1,53 @@ +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 { Lesson05Di } from './lesson-05-di'; + +expect.extend(axeMatchers); + +describe('Lesson05Di', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + const tally = (name: string) => + el.querySelector(`.tally-button[data-name="${name}"]`)?.textContent?.replace(/\s+/g, ' ') ?? ''; + const press = async (name: string) => { + el.querySelector(`.tally-button[data-name="${name}"]`)!.click(); + await fixture.whenStable(); + }; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson05Di] }).compileComponents(); + fixture = TestBed.createComponent(Lesson05Di); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-05-dependency-injection']).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('buttons under one provider share an instance', async () => { + await press('A'); + expect(tally('A')).toContain('A: 1'); + expect(tally('B')).toContain('B: 1'); + }); + + it('buttons under their own provider each get a fresh instance', async () => { + await press('C'); + expect(tally('C')).toContain('C: 1'); + expect(tally('D')).toContain('D: 0'); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lesson-05-di.ts b/src/app/thoughts-content/lessons/lesson-05-di.ts new file mode 100644 index 0000000..41042f7 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-05-di.ts @@ -0,0 +1,298 @@ +import { Component, inject, Injectable, input, signal } 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'; + +/** + * Hands out instance numbers for the demo. Provided on the lesson component, + * so numbering starts at 1 on every render of the page. A module-level counter + * would keep counting across requests on a long-running server, and the + * numbers would disagree with the browser's after hydration (see the expert + * callout below). + */ +@Injectable() +export class TallyNumbering { + private last = 0; + + next(): number { + return ++this.last; + } +} + +// [ng-05 di] No providedIn here on purpose. A service without it only exists +// where something lists it in a providers array, and every such list creates a +// new instance for that part of the tree. That's what the demo shows. +@Injectable() +export class Tally { + readonly id = inject(TallyNumbering).next(); + readonly count = signal(0); + + increment(): void { + this.count.update((n) => n + 1); + } +} + +/** Provides a Tally for everything inside it, including projected content. */ +@Component({ + selector: 'app-tally-scope', + providers: [Tally], + template: `
`, + styles: ` + .tally-scope { + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 8px; + border: 1px dashed var(--border-primary, rgba(255, 255, 255, 0.3)); + border-radius: 8px; + } + `, +}) +export class TallyScope {} + +/** Asks for a Tally and gets whichever one the nearest scope above it provides. */ +@Component({ + selector: 'app-tally-button', + template: ` + + `, + styles: ` + .tally-instance { + font-size: 11px; + opacity: 0.75; + } + `, +}) +export class TallyButton { + readonly name = input.required(); + protected readonly tally = inject(Tally); +} + +@Component({ + selector: 'app-lesson-05-di', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions, TallyScope, TallyButton], + providers: [TallyNumbering], + template: ` + +

Simple

+

+ Dependency injection means a class asks for what it needs instead of building it. Call + inject(SomeService) in a field initialiser and Angular hands you an instance. + Mark the service @Injectable({ providedIn: 'root' }) and there is exactly one + instance for the whole app, created the first time something asks for it. +

+

+ The "Mark lesson complete" button at the bottom of this page is that pattern. The reader and + the Thoughts list both inject ReadingProgressService. Neither knows the other + exists, but they get the same instance, so marking a lesson here badges its card in the + list. +

+ + +

Intermediate

+

+ A provider is a recipe that tells an injector how to build the value for a + token. providedIn: 'root' is one recipe. A providers array is the + other place they go, and it has four shapes: useClass, + useValue, useFactory and useExisting (an alias). +

+ +

+ Tokens that aren't classes. Storage is an interface, and interfaces + disappear at runtime, so they can't be looked up. An InjectionToken is a + runtime key for those. This lesson added BROWSER_STORAGE: localStorage in the + browser, null during prerendering. Both the reading progress and the system + settings now read through it, so neither one checks the platform itself. +

+ +

The payoff is in the specs. They swap the token instead of touching the real localStorage:

+ + +

+ Injectors form a tree. Every component can have its own + providers. When something injects a token, Angular walks up from that element + and uses the first provider it finds. So listing a service on a component gives that + component, and everything under it, its own instance. +

+ +

A and B sit under one scope that provides Tally:

+ + + + +

C and D each sit under their own scope:

+
+ + +
+

+ Press A and B goes up too: same instance number, same count. Press C and D doesn't + move: two scopes, two instances. +

+
+ + +

Expert

+

+ Two trees, searched in order. First the element injectors, from + the component's own providers up through its ancestors in the DOM. Then the + environment injectors: a lazy route's injector, then root, then platform. Past + those is the NullInjector, which throws NG0201: No provider for X. +

+

+ Resolution modifiers change that walk. optional: true + returns null instead of throwing. self: true only looks at this + element, skipSelf: true starts at the parent (how a nested menu finds its + parent menu), and host: true stops at the host component. +

+ +

+ providers vs viewProviders. The demo's scope uses + providers, which is why projected buttons can see it. With + viewProviders, only the component's own template could, and the projected + buttons would throw NG0201. Libraries use that to keep internals private. +

+

+ Route providers on a lazy route get their own environment injector, created + when the route first loads. That's the modern replacement for a lazy NgModule's providers. + multi: true lets many providers add to one token as an array. + provideAppInitializer() and the old HTTP_INTERCEPTORS both work + that way. +

+ +

+ On the server, the root injector is created per request, so root services don't leak + between users. Module-level variables do: a top-level let cache in a file is + shared by every request the server handles. Put per-user state in a service, never in + module scope. +

+
+

+ The injection context. inject() only works while Angular is + constructing something: field initialisers, constructors, provider factories, route guards. + Outside that, use runInInjectionContext(injector, fn). +

+ +

Pitfalls

+ +

+ Listing a root service in a component's providers. It + compiles and runs, and that component now has a second, private instance. State + "randomly" stops syncing. A root service should appear in no providers array. +

+
+ +

+ Calling inject() in ngOnInit or a click + handler throws NG0203. Inject in a field and use it later. +

+
+ +

+ Reaching for globals like window, document or + localStorage directly. They don't exist during SSR and can't be swapped in + tests. Put them behind a token, or use Angular's DOCUMENT. +

+
+ +

+ Two services injecting each other fail with NG0200, a circular + dependency. Usually one of them is doing two jobs. Split out the shared part. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .demo-note { + font-size: 12px; + } + `, +}) +export class Lesson05Di { + protected readonly snippets = { + root: `@Injectable({ providedIn: 'root' }) // one instance, app-wide, tree-shakable +export class ReadingProgressService { + private readonly storage = inject(BROWSER_STORAGE); + private readonly completedState = signal>(this.load()); + readonly completedSlugs = this.completedState.asReadonly(); + + toggleComplete(slug: string): void { /* ... */ } +} + +// in the reader and the Thoughts list alike: +protected readonly progress = inject(ReadingProgressService);`, + shapes: `providers: [ + Logger, // shorthand for useClass: Logger + { provide: Logger, useClass: ConsoleLogger }, // a different class for the same token + { provide: API_URL, useValue: 'https://api.example.com' }, + { provide: Clock, useFactory: () => new Clock(inject(LOCALE_ID)) }, + { provide: OldLogger, useExisting: Logger }, // alias: same instance, two tokens +]`, + token: `export const BROWSER_STORAGE = new InjectionToken('BROWSER_STORAGE', { + providedIn: 'root', + factory: () => (isPlatformBrowser(inject(PLATFORM_ID)) ? localStorage : null), +}); + +// a consumer: +private readonly storage = inject(BROWSER_STORAGE); +this.storage?.setItem('reading-progress', JSON.stringify([...completed]));`, + spec: `TestBed.configureTestingModule({ + providers: [{ provide: BROWSER_STORAGE, useValue: createMemoryStorage() }], +}); +const progress = TestBed.inject(ReadingProgressService); + +// and the server case is just: +providers: [{ provide: BROWSER_STORAGE, useValue: null }]`, + tree: `@Injectable() // no providedIn: only exists where provided +export class Tally { readonly count = signal(0); } + +@Component({ selector: 'app-tally-scope', providers: [Tally], template: '' }) +export class TallyScope {} + +@Component({ selector: 'app-tally-button', /* ... */ }) +export class TallyButton { protected readonly tally = inject(Tally); } // nearest scope wins + + + + `, + modifiers: `// null instead of NG0201 when nothing provides it +private readonly analytics = inject(Analytics, { optional: true }); + +// a nested menu finding its parent menu, not itself +private readonly parentMenu = inject(Menu, { skipSelf: true, optional: true });`, + }; + + protected readonly interview = [ + { + q: 'What is dependency injection, and why does Angular use it?', + a: 'A class declares what it needs and the framework supplies it, instead of the class constructing its own dependencies. That decouples code from concrete implementations, so you can swap them per environment (browser vs server) or per test, and it lets Angular control lifetimes: one app-wide instance, or one per component subtree.', + }, + { + q: "What does providedIn: 'root' do, and how is it different from listing a service in providers?", + a: "providedIn: 'root' registers the service with the root environment injector: one instance for the app, created lazily, and dropped from the bundle if nothing injects it. Listing it in a component's providers creates a new instance for that component and its children. Doing both gives you two instances, a classic source of state that silently stops syncing.", + }, + { + q: 'When do you need an InjectionToken?', + a: 'When the thing you inject is not a class: an interface, a config object, a string or a browser global. Interfaces are erased at runtime, so they cannot be lookup keys. In this project BROWSER_STORAGE is a token for Storage, with a factory that returns localStorage in the browser and null on the server.', + }, + { + q: 'How does Angular resolve a dependency?', + a: 'It walks the element injector tree first, starting at the requesting element and going up through ancestor components. Then it walks the environment injectors: lazy route injectors, root, then platform. The first provider found wins. If none is found it throws NG0201, unless the request was optional. Modifiers like self, skipSelf and host change where the walk starts or stops.', + }, + { + q: 'inject() or constructor injection?', + a: 'They resolve the same way. inject() is the modern default: it works in field initialisers and functions (guards, interceptors, factories), plays well with inheritance because subclasses do not have to pass dependencies to super(), and does not depend on TypeScript decorator metadata. It must be called in an injection context.', + }, + { + q: 'How do you test a service that touches localStorage or the network?', + a: 'Put the dependency behind DI and override it in TestBed. Use { provide: TOKEN, useValue: fake } for a token, or provideHttpClientTesting() for HttpClient. The service code never changes between tests and production, and the tests never touch real global state.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index 127322c..64aeb86 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -15,4 +15,5 @@ export const LESSON_PAGES: Record Promise>> = { 'angular-03-templates': () => import('./lesson-03-templates').then((m) => m.Lesson03Templates), 'angular-04-signals': () => import('./lesson-04-signals').then((m) => m.Lesson04Signals), + 'angular-05-dependency-injection': () => import('./lesson-05-di').then((m) => m.Lesson05Di), }; diff --git a/src/app/thoughts-content/reading-progress.service.spec.ts b/src/app/thoughts-content/reading-progress.service.spec.ts new file mode 100644 index 0000000..d9f7169 --- /dev/null +++ b/src/app/thoughts-content/reading-progress.service.spec.ts @@ -0,0 +1,57 @@ +import { TestBed } from '@angular/core/testing'; +import { createMemoryStorage } from '../../test/memory-storage'; +import { BROWSER_STORAGE } from '../shared/browser-storage'; +import { ReadingProgressService } from './reading-progress.service'; + +const KEY = 'reading-progress'; + +function createService(storage: Storage | null) { + TestBed.configureTestingModule({ providers: [{ provide: BROWSER_STORAGE, useValue: storage }] }); + return TestBed.inject(ReadingProgressService); +} + +describe('ReadingProgressService', () => { + it('starts with nothing complete', () => { + const progress = createService(createMemoryStorage()); + expect(progress.isComplete('angular-01-project-structure')).toBe(false); + expect(progress.completedSlugs().size).toBe(0); + }); + + it('toggles a slug complete and back', () => { + const progress = createService(createMemoryStorage()); + + progress.toggleComplete('angular-01-project-structure'); + expect(progress.isComplete('angular-01-project-structure')).toBe(true); + + progress.toggleComplete('angular-01-project-structure'); + expect(progress.isComplete('angular-01-project-structure')).toBe(false); + }); + + it('saves through the injected storage, not the global localStorage', () => { + const storage = createMemoryStorage(); + const progress = createService(storage); + + progress.toggleComplete('angular-02-components'); + + expect(JSON.parse(storage.getItem(KEY)!)).toEqual(['angular-02-components']); + }); + + it('restores what was saved', () => { + const progress = createService( + createMemoryStorage({ [KEY]: JSON.stringify(['angular-03-templates']) }), + ); + expect(progress.isComplete('angular-03-templates')).toBe(true); + }); + + it('works without storage (on the server), keeping progress in memory', () => { + const progress = createService(null); + progress.toggleComplete('angular-04-signals'); + expect(progress.isComplete('angular-04-signals')).toBe(true); + }); + + it('throws on a saved value that is not a list of slugs, rather than silently resetting', () => { + expect(() => createService(createMemoryStorage({ [KEY]: '{"oops":true}' }))).toThrow( + /reading-progress/, + ); + }); +}); diff --git a/src/app/thoughts-content/reading-progress.service.ts b/src/app/thoughts-content/reading-progress.service.ts new file mode 100644 index 0000000..d53df7f --- /dev/null +++ b/src/app/thoughts-content/reading-progress.service.ts @@ -0,0 +1,46 @@ +import { inject, Injectable, signal } from '@angular/core'; +import { BROWSER_STORAGE } from '../shared/browser-storage'; + +const STORAGE_KEY = 'reading-progress'; + +/** + * Which lessons the reader has marked complete, saved across visits. + * + * [ng-05 di] providedIn: 'root' makes this one shared instance for the whole + * app, so the reader's toggle and the list's badges see the same state + * without either knowing about the other. It depends on BROWSER_STORAGE, not + * on localStorage, so it runs unchanged on the server and in specs. + */ +@Injectable({ providedIn: 'root' }) +export class ReadingProgressService { + private readonly storage = inject(BROWSER_STORAGE); + private readonly completedState = signal>(this.load()); + + readonly completedSlugs = this.completedState.asReadonly(); + + isComplete(slug: string): boolean { + return this.completedSlugs().has(slug); + } + + toggleComplete(slug: string): void { + const completed = new Set(this.completedSlugs()); + if (!completed.delete(slug)) completed.add(slug); + this.completedState.set(completed); + this.storage?.setItem(STORAGE_KEY, JSON.stringify([...completed])); + } + + private load(): ReadonlySet { + const raw = this.storage?.getItem(STORAGE_KEY); + if (raw == null) return new Set(); + let saved: unknown; + try { + saved = JSON.parse(raw); + } catch (cause) { + throw new Error(`Saved ${STORAGE_KEY} is not valid JSON: ${raw}`, { cause }); + } + if (!Array.isArray(saved) || !saved.every((slug) => typeof slug === 'string')) { + throw new Error(`Saved ${STORAGE_KEY} should be a list of slugs, got: ${raw}`); + } + return new Set(saved); + } +} diff --git a/src/app/thoughts-content/thought-detail.spec.ts b/src/app/thoughts-content/thought-detail.spec.ts index ec840c7..f209b0b 100644 --- a/src/app/thoughts-content/thought-detail.spec.ts +++ b/src/app/thoughts-content/thought-detail.spec.ts @@ -1,7 +1,10 @@ import { TestBed } from '@angular/core/testing'; import { provideRouter, Router } from '@angular/router'; import { RouterTestingHarness } from '@angular/router/testing'; +import { createMemoryStorage } from '../../test/memory-storage'; +import { BROWSER_STORAGE } from '../shared/browser-storage'; import { ThoughtDetailComponent } from './thought-detail'; +import { ReadingProgressService } from './reading-progress.service'; import { ThoughtsListComponent } from './thoughts-list'; /** @@ -16,6 +19,8 @@ async function openThought(slug: string) { { path: 'thoughts', component: ThoughtsListComponent }, { path: 'thoughts/:slug', component: ThoughtDetailComponent }, ]), + // A fresh store per test, so progress marked in one can't leak into the next. + { provide: BROWSER_STORAGE, useFactory: () => createMemoryStorage() }, ], }); const harness = await RouterTestingHarness.create(); @@ -66,6 +71,10 @@ describe('ThoughtDetailComponent', () => { expect(document.title).toContain('Why Angular Signals Changed Everything'); }); + it('offers no complete toggle on a prose-only thought', () => { + expect(el.querySelector('.lesson-complete')).toBeNull(); + }); + 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(); @@ -122,4 +131,27 @@ describe('ThoughtDetailComponent with an interactive lesson page', () => { expect(host.scrollTop).toBe(0); }); + + it('lets the reader mark a lesson complete, as a pressed toggle button', async () => { + const { harness, el } = await openThought('angular-02-components'); + const toggle = el.querySelector('button.lesson-complete')!; + + expect(toggle.getAttribute('aria-pressed')).toBe('false'); + expect(toggle.textContent).toContain('Mark lesson complete'); + + toggle.click(); + await harness.fixture.whenStable(); + + expect(toggle.getAttribute('aria-pressed')).toBe('true'); + expect(toggle.textContent).toContain('Completed'); + expect(TestBed.inject(ReadingProgressService).isComplete('angular-02-components')).toBe(true); + }); + + it('shows how much of the series is complete', async () => { + const { harness, el } = await openThought('angular-01-project-structure'); + el.querySelector('button.lesson-complete')!.click(); + await harness.fixture.whenStable(); + + expect(el.querySelector('.series-nav-position')?.textContent).toMatch(/1 of \d+ complete/); + }); }); diff --git a/src/app/thoughts-content/thought-detail.ts b/src/app/thoughts-content/thought-detail.ts index 35169ac..d73a2ad 100644 --- a/src/app/thoughts-content/thought-detail.ts +++ b/src/app/thoughts-content/thought-detail.ts @@ -5,6 +5,7 @@ import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { map } from 'rxjs'; import { SeoService } from '../shared/seo.service'; import { LESSON_PAGES } from './lessons/lessons'; +import { ReadingProgressService } from './reading-progress.service'; import { ReadingTimePipe } from './reading-time.pipe'; import { UtcDatePipe } from './utc-date.pipe'; import { ThoughtsService } from './thoughts.service'; @@ -36,7 +37,21 @@ import { ThoughtsService } from './thoughts.service'; } @if (series(); as series) {