Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "angular-paul",
"version": "1.4.3",
"version": "1.4.4",
"scripts": {
"ng": "ng",
"start": "ng serve",
Expand Down
14 changes: 14 additions & 0 deletions src/app/shared/browser-storage.spec.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
22 changes: 22 additions & 0 deletions src/app/shared/browser-storage.ts
Original file line number Diff line number Diff line change
@@ -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<Storage | null>('BROWSER_STORAGE', {
providedIn: 'root',
factory: () => (isPlatformBrowser(inject(PLATFORM_ID)) ? localStorage : null),
});
25 changes: 25 additions & 0 deletions src/app/shared/settings/settings.service.spec.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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();
});
});
17 changes: 10 additions & 7 deletions src/app/shared/settings/settings.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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<Theme>(this.initial.theme);
Expand Down Expand Up @@ -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 {
Expand All @@ -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));
}
}
53 changes: 53 additions & 0 deletions src/app/thoughts-content/lessons/lesson-05-di.spec.ts
Original file line number Diff line number Diff line change
@@ -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<Lesson05Di>;
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<HTMLButtonElement>(`.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();
});
});
Loading
Loading