From 82b2d3b46d75899fe2aa245bf8bddaf328b04f9a Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sun, 16 Aug 2026 22:28:32 -0400 Subject: [PATCH 01/74] Add a failing guard for the changelog going unwritten #26 shipped the shortcut remap with no changelog entry and nothing failed. I only caught it writing the 1.3.6 release note from commits instead of from the changelog, which is the wrong direction to read it in. The guard asserts the top entry is the version package.json is on, that it has bullets under it, that no version gets two headings, that versions and dates both run newest first, and that every heading parses in the one format. Red on purpose: package.json moves to 1.3.7 here with no entry to match, which is the exact shape of the thing that went missing. --- package.json | 2 +- src/changelog.spec.ts | 117 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 src/changelog.spec.ts diff --git a/package.json b/package.json index e53abd8..a289c92 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.3.6", + "version": "1.3.7", "scripts": { "ng": "ng", "start": "ng serve", diff --git a/src/changelog.spec.ts b/src/changelog.spec.ts new file mode 100644 index 0000000..88202d3 --- /dev/null +++ b/src/changelog.spec.ts @@ -0,0 +1,117 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +/** + * Whatever version package.json is on has to be written down. + * + * The shortcut remap in #26 shipped with no changelog entry at all, and nothing + * failed. It was only noticed while writing the 1.3.6 release note from commits + * instead of from the changelog, which is the wrong direction to read it in. + * + * This is deliberately the weakest useful check. It cannot tell whether an entry + * is any good, only that the version bump and the note about it happen together + * rather than the second one being left for later, which is where it was lost. + * It does not catch a change that bumps nothing at all -- see the note on the + * first test. + */ +const ROOT = process.cwd(); + +const read = (name: string): string => + readFileSync(join(ROOT, name), 'utf-8'); + +const changelog = (): string => read('CHANGELOG.md'); + +const packageVersion = (): string => + (JSON.parse(read('package.json')) as { version: string }).version; + +type Entry = { readonly date: string; readonly version: string }; + +/** Entries the changelog documents, in the order it lists them. */ +const documented = (source: string): readonly Entry[] => + [...source.matchAll(/^## (\d{4}-\d{2}-\d{2}) - version (\d+\.\d+\.\d+)\s*$/gm)].map( + (m) => ({ date: m[1], version: m[2] }), + ); + +/** Every second-level heading, well formed or not, so a malformed one shows up. */ +const headings = (source: string): readonly string[] => + source.split('\n').filter((line) => line.startsWith('## ')); + +const bulletsUnder = (source: string, version: string): readonly string[] => { + const start = source.indexOf(`version ${version}`); + const next = source.indexOf('\n## ', start); + const body = source.slice(start, next === -1 ? undefined : next); + return body.split('\n').filter((line) => line.trim().startsWith('- ')); +}; + +const order = (a: string, b: string): number => { + const left = a.split('.').map(Number); + const right = b.split('.').map(Number); + const differs = left.findIndex((n, i) => n !== right[i]); + return differs === -1 ? 0 : left[differs] - right[differs]; +}; + +describe('changelog', () => { + /** + * The top entry, not just any entry. A release that bumps package.json and + * leaves the note for later lands the new version above nothing, and this is + * what fails. + * + * Worth being honest about the hole: a change that bumps neither the version + * nor the changelog leaves the two agreeing with each other, and this passes. + * That is exactly what #26 did. Catching that one needs the PR diff, not a + * unit test. + */ + it('leads with the version package.json is on', () => { + expect(documented(changelog())[0].version).toBe(packageVersion()); + }); + + it('gives that entry something to say', () => { + // A heading with nothing under it satisfies the check above while + // documenting nothing, which is the obvious way to game it. + expect(bulletsUnder(changelog(), packageVersion()).length).toBeGreaterThan(0); + }); + + it('gives every version exactly one heading', () => { + const versions = documented(changelog()).map((e) => e.version); + const repeated = versions.filter((v, i) => versions.indexOf(v) !== i); + + expect(repeated).toEqual([]); + }); + + /** + * Reading the log top to bottom should walk backwards through releases. An + * entry inserted in the wrong place still documents itself, but it stops the + * file answering "what shipped most recently", which is the only question + * anyone opens it to ask. + */ + it('lists versions newest first', () => { + const versions = documented(changelog()).map((e) => e.version); + const misplaced = versions.filter((v, i) => i > 0 && order(v, versions[i - 1]) >= 0); + + expect(misplaced).toEqual([]); + }); + + it('lists dates newest first', () => { + const entries = documented(changelog()); + const misplaced = entries.filter((e, i) => i > 0 && e.date > entries[i - 1].date); + + expect(misplaced).toEqual([]); + }); + + /** + * Every heading has to parse. Without this a heading that loses its date, or + * gains a stray bracket, silently drops out of every check above rather than + * failing one of them. + */ + it('writes every heading in the one format', () => { + expect(headings(changelog()).length).toBe(documented(changelog()).length); + }); + + it('actually reads entries out, so a rotted regex fails rather than passes', () => { + expect(documented('## 2026-08-14 - version 4.5.6\n\n- a note\n')).toEqual([ + { date: '2026-08-14', version: '4.5.6' }, + ]); + expect(documented('## not a version heading\n')).toEqual([]); + expect(documented('## 4.5.6\n')).toEqual([]); + }); +}); From 0c2f13d931dc617855e0c177743d6f3aaabcf1de Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sun, 16 Aug 2026 22:30:04 -0400 Subject: [PATCH 02/74] Write the 1.3.7 entry the guard is asking for Green: the top entry is the version package.json is on, and it has something under it. All 46 existing entries already satisfied every assertion, so nothing older had to be rewritten to get here. --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f65295e..c68c412 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to this project will be documented in this file. +## 2026-08-16 - version 1.3.7 + +- **Changelog guard**: `src/changelog.spec.ts` asserts the top entry is the version `package.json` is on, that it has bullets under it, that no version gets two headings, that versions and dates both run newest first, and that every `## ` heading parses as `YYYY-MM-DD - version X.Y.Z`. Ported from the `changelogEntry.test.ts` in `paul-explore` and `portfolio_api`, which have had this for a while — this repo was the one without it +- All 46 existing entries already satisfied every assertion, so nothing had to be rewritten to go green. The parser is exercised against known input too, so a rotted regex fails rather than quietly matching nothing and passing +- The gap that prompted it: the shortcut remap shipped in 1.3.4 with no changelog entry, and nothing failed. I caught it writing the 1.3.6 release note from commits instead of from the changelog, which is the wrong direction to read it in +- Being straight about what this does not catch: the remap bumped neither the version nor the changelog, which leaves the two agreeing with each other, and a top-entry-matches-`package.json` assertion passes on that. It catches a version that moves without its note. Catching a behaviour change that moves neither needs the PR diff, so it belongs in `ci.yml` rather than in a spec, and that check would need `fetch-depth: 0` on the checkout +- **Backfill**: the 1.3.4 entry now documents the shortcut remap it actually shipped, alongside the design-token bump it already described + ## 2026-08-16 - version 1.3.6 - **Design tokens**: `@paul-portfolio/tokens` `^0.3.0` → `^0.4.0`. Below 1.0 the caret is minor-locked, so `^0.3.0` could never resolve 0.4.0 — the range had to move for the new version to install at all From 3b07017261cafe88a5fb0083f683381c2bdb4fec Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sun, 16 Aug 2026 22:30:48 -0400 Subject: [PATCH 03/74] Backfill the shortcut remap into 1.3.4 The remap shipped in 1.3.4 with no entry. Reconstructed from the four commits on #26 and checked against the source, not just the commit subjects. Added to the existing 1.3.4 entry rather than opening a second heading dated the day it merged. It genuinely shipped in 1.3.4, and a duplicate heading would break both the one-heading-per-version and the date-ordering assertions. Version-accurate beat date-accurate. Documentation repair. No past commits touched. --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c68c412..875b536 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,12 @@ All notable changes to this project will be documented in this file. ## 2026-08-15 - version 1.3.4 +- **Desktop shortcuts are reachable again**: the five live chords moved from ⌘ to ⌃⌥ — close window (⌘W → ⌃⌥W), quit app (⌘Q → ⌃⌥Q), minimize (⌘H → ⌃⌥H), Spotlight (⌘Space → ⌃⌥Space) and cycle windows (⌘Tab → ⌃⌥Tab). The browser and macOS reserve those ⌘ chords and will not hand them over, so `preventDefault()` on them does nothing and the simulation silently did nothing either +- `keyboard-shortcut.service.ts` gates on `ctrlKey && altKey && !metaKey` instead of `metaKey`, and each handled case calls `preventDefault()` for itself rather than relying on the one ad-hoc call for ⌘Space that used to sit in `app.ts` +- The other ⌘ glyphs left in the menus are decoration — nothing ever listened for those chords — so they stay as macOS chrome. Only the five that actually fire were remapped +- The menu-bar hints and the Shortcuts list in the README app were updated to the real chords, so the UI stops advertising bindings that never worked +- TDD: specs assert each ⌃⌥ chord fires, and that the reserved ⌘ chords are ignored and left un-`preventDefault()`ed for the browser to handle +- Backfilled after the fact. This shipped in 1.3.4 without an entry, which is what prompted the changelog guard in 1.3.7 - **Design tokens**: `@paul-portfolio/tokens` `^0.1.3` → `^0.3.0`, picking up the "Verdigris & Ember" design language — teal-green primary (`#219b84`), ember secondary (`#d97e1f`), warm ink-on-paper neutrals, warm semantic surfaces, a new `violet` ramp, `--paul-font-family-display`, and the AA contrast fixes - The span crosses the spacing-token rename (`--paul-spacing-0.5` → `--paul-spacing-0_5`), which is the only hard break in it. Nothing here referenced the dotted names in CSS — the only mentions are in the Thoughts entry that documents the gotcha — so no call sites moved - All 43 `--paul-*` tokens this app consumes still exist in 0.3.0, and only one changed value: `--paul-color-background` (`#ffffff` → `#fbfaf7`), which nothing references in CSS. The desktop chrome deliberately keeps its own palette in `desktop-theme.scss`, so the recolour is inert here by design — the token bridge only maps typography, motion, radii and z-index From a312a4d7887b5a6f6e065ebf8b0181254f58edee Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:36:56 -0500 Subject: [PATCH 04/74] Add a failing architecture spec for shell-to-feature imports --- src/app/architecture.spec.ts | 73 ++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/app/architecture.spec.ts diff --git a/src/app/architecture.spec.ts b/src/app/architecture.spec.ts new file mode 100644 index 0000000..066fc78 --- /dev/null +++ b/src/app/architecture.spec.ts @@ -0,0 +1,73 @@ +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative, resolve, dirname, sep } from 'node:path'; + +/** + * [ng-01 structure] Architecture fitness tests. + * + * Folder conventions only hold while someone enforces them. In a team, "we put + * shared state in shared/" lives in a wiki nobody reads, and six months later a + * feature folder is quietly a dependency of the whole app. These tests make the + * convention executable: break the rule and CI goes red with the file name. + * + * The layering this repo uses (see docs/angular-guide/01-project-structure.md): + * + * shell app.ts, menu-bar/, dock/, desktop/, window-manager/, ... + * shared/ services and building blocks anyone may use + * apps/ feature folders — one per desktop "app", lazy loaded + * + * Arrows only point down: shell → shared, apps → shared. Nothing outside + * apps/ may *statically* import from apps/. A static import drags the feature + * into the initial bundle and couples the shell to its internals. Dynamic + * `import()` is allowed — that IS the lazy-loading seam. + */ +const APP_ROOT = resolve(process.cwd(), 'src/app'); + +function sourceFiles(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const full = join(dir, name); + if (statSync(full).isDirectory()) return sourceFiles(full); + return full.endsWith('.ts') && !full.endsWith('.spec.ts') ? [full] : []; + }); +} + +/** Static `import … from './x'` / `export … from './x'` specifiers, never `import('./x')`. */ +function staticRelativeImports(file: string): string[] { + const source = readFileSync(file, 'utf-8'); + const specifiers = [...source.matchAll(/^\s*(?:import|export)\b[^;]*?\bfrom\s+'(\.[^']+)'/gm)]; + return specifiers.map((match) => resolve(dirname(file), match[1])); +} + +const isInside = (file: string, folder: string) => + relative(join(APP_ROOT, folder), file).split(sep)[0] !== '..'; + +describe('[ng-01] architecture', () => { + const files = sourceFiles(APP_ROOT); + + it('finds the source tree (guards against the walker silently matching nothing)', () => { + expect(files.length).toBeGreaterThan(30); + }); + + it('the parser sees static imports and ignores dynamic import()', () => { + const app = join(APP_ROOT, 'app.routes.ts'); + // app.routes.ts only has lazy `import()` calls into features plus one package import. + expect(staticRelativeImports(app)).toEqual([]); + }); + + it('nothing outside apps/ statically imports from apps/', () => { + const violations = files + .filter((file) => !isInside(file, 'apps')) + .flatMap((file) => + staticRelativeImports(file) + .filter((target) => isInside(target, 'apps')) + .map((target) => `${relative(APP_ROOT, file)} → ${relative(APP_ROOT, target)}`), + ); + expect(violations).toEqual([]); + }); + + it('has no NgModules — every component, directive and pipe is standalone', () => { + const withNgModule = files + .filter((file) => /@NgModule\s*\(/.test(readFileSync(file, 'utf-8'))) + .map((file) => relative(APP_ROOT, file)); + expect(withNgModule).toEqual([]); + }); +}); From 60202e7847602d08f291aabe978cd6b64f3831b8 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:37:44 -0500 Subject: [PATCH 05/74] Move app-wide settings state from apps/ into shared/ --- src/app/app.ts | 2 +- src/app/apps/settings/system-preferences.spec.ts | 2 +- src/app/apps/settings/system-preferences.ts | 2 +- src/app/dock/dock.ts | 2 +- src/app/menu-bar/menu-bar.spec.ts | 2 +- src/app/menu-bar/menu-bar.ts | 2 +- .../{apps => shared}/settings/appearance.service.spec.ts | 0 src/app/{apps => shared}/settings/appearance.service.ts | 0 src/app/{apps => shared}/settings/settings.service.spec.ts | 0 src/app/{apps => shared}/settings/settings.service.ts | 6 ++++++ 10 files changed, 12 insertions(+), 6 deletions(-) rename src/app/{apps => shared}/settings/appearance.service.spec.ts (100%) rename src/app/{apps => shared}/settings/appearance.service.ts (100%) rename src/app/{apps => shared}/settings/settings.service.spec.ts (100%) rename src/app/{apps => shared}/settings/settings.service.ts (83%) diff --git a/src/app/app.ts b/src/app/app.ts index d824d79..f4f3c93 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -8,7 +8,7 @@ import { Desktop } from './desktop/desktop'; import { DesktopIconsComponent } from './desktop-icons/desktop-icons'; import { Dock } from './dock/dock'; import { MenuBar } from './menu-bar/menu-bar'; -import { AppearanceService } from './apps/settings/appearance.service'; +import { AppearanceService } from './shared/settings/appearance.service'; import { AppLauncherService } from './shared/app-launcher.service'; import { DockService } from './shared/dock.service'; import { KeyboardShortcutService } from './shared/keyboard-shortcut.service'; diff --git a/src/app/apps/settings/system-preferences.spec.ts b/src/app/apps/settings/system-preferences.spec.ts index 0e33564..4062001 100644 --- a/src/app/apps/settings/system-preferences.spec.ts +++ b/src/app/apps/settings/system-preferences.spec.ts @@ -1,7 +1,7 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { vi } from 'vitest'; import { SystemPreferencesApp } from './system-preferences'; -import { SettingsService } from './settings.service'; +import { SettingsService } from '../../shared/settings/settings.service'; describe('SystemPreferencesApp', () => { let fixture: ComponentFixture; diff --git a/src/app/apps/settings/system-preferences.ts b/src/app/apps/settings/system-preferences.ts index 2f788d1..5253700 100644 --- a/src/app/apps/settings/system-preferences.ts +++ b/src/app/apps/settings/system-preferences.ts @@ -1,5 +1,5 @@ import { Component, inject, signal } from '@angular/core'; -import { SettingsService } from './settings.service'; +import { SettingsService } from '../../shared/settings/settings.service'; type Pane = 'appearance' | 'dock' | 'general'; diff --git a/src/app/dock/dock.ts b/src/app/dock/dock.ts index e806575..eaab3cd 100644 --- a/src/app/dock/dock.ts +++ b/src/app/dock/dock.ts @@ -1,5 +1,5 @@ import { Component, computed, inject, signal } from '@angular/core'; -import { SettingsService } from '../apps/settings/settings.service'; +import { SettingsService } from '../shared/settings/settings.service'; import { AppLauncherService } from '../shared/app-launcher.service'; import { DockItem, DockService } from '../shared/dock.service'; diff --git a/src/app/menu-bar/menu-bar.spec.ts b/src/app/menu-bar/menu-bar.spec.ts index 745bb1c..ab50f77 100644 --- a/src/app/menu-bar/menu-bar.spec.ts +++ b/src/app/menu-bar/menu-bar.spec.ts @@ -1,6 +1,6 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { vi } from 'vitest'; -import { SettingsService } from '../apps/settings/settings.service'; +import { SettingsService } from '../shared/settings/settings.service'; import { MenuBar } from './menu-bar'; import { MenuBarService } from './menu-bar.service'; diff --git a/src/app/menu-bar/menu-bar.ts b/src/app/menu-bar/menu-bar.ts index f41a135..4f27389 100644 --- a/src/app/menu-bar/menu-bar.ts +++ b/src/app/menu-bar/menu-bar.ts @@ -10,7 +10,7 @@ import { PLATFORM_ID, signal, } from '@angular/core'; -import { SettingsService } from '../apps/settings/settings.service'; +import { SettingsService } from '../shared/settings/settings.service'; import { MenuBarItem, MenuBarService } from './menu-bar.service'; @Component({ diff --git a/src/app/apps/settings/appearance.service.spec.ts b/src/app/shared/settings/appearance.service.spec.ts similarity index 100% rename from src/app/apps/settings/appearance.service.spec.ts rename to src/app/shared/settings/appearance.service.spec.ts diff --git a/src/app/apps/settings/appearance.service.ts b/src/app/shared/settings/appearance.service.ts similarity index 100% rename from src/app/apps/settings/appearance.service.ts rename to src/app/shared/settings/appearance.service.ts diff --git a/src/app/apps/settings/settings.service.spec.ts b/src/app/shared/settings/settings.service.spec.ts similarity index 100% rename from src/app/apps/settings/settings.service.spec.ts rename to src/app/shared/settings/settings.service.spec.ts diff --git a/src/app/apps/settings/settings.service.ts b/src/app/shared/settings/settings.service.ts similarity index 83% rename from src/app/apps/settings/settings.service.ts rename to src/app/shared/settings/settings.service.ts index f976068..730daf6 100644 --- a/src/app/apps/settings/settings.service.ts +++ b/src/app/shared/settings/settings.service.ts @@ -1,3 +1,9 @@ +// [ng-01 structure] Why this lives in shared/ and not apps/settings/: +// the dock (icon size), the menu bar (clock format) and the root shell (theme) +// all read it. State that the whole app depends on is not a feature's private +// 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'; From d636f76ab9c4274b51a0c6d6a2a7a4d45d0ca0a6 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:37:44 -0500 Subject: [PATCH 06/74] Annotate the bootstrap files for the structure lesson --- src/app/app.config.server.ts | 4 ++++ src/app/app.config.ts | 17 +++++++++++++++++ src/main.ts | 10 ++++++++++ 3 files changed, 31 insertions(+) diff --git a/src/app/app.config.server.ts b/src/app/app.config.server.ts index 41031f1..39e80db 100644 --- a/src/app/app.config.server.ts +++ b/src/app/app.config.server.ts @@ -1,3 +1,7 @@ +// [ng-01 structure] Server-only providers, merged over the browser config. +// mergeApplicationConfig keeps one source of truth (app.config.ts) and layers +// the server bits on top, so the two configs can't drift apart. +// main.server.ts bootstraps with this; main.ts bootstraps with appConfig. import { mergeApplicationConfig, ApplicationConfig } from '@angular/core'; import { provideServerRendering, withRoutes } from '@angular/ssr'; import { appConfig } from './app.config'; diff --git a/src/app/app.config.ts b/src/app/app.config.ts index c37b8d1..963c9f5 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -1,3 +1,14 @@ +// [ng-01 structure] Application-wide providers. This file replaces what an +// AppModule's `imports: [...]` and `providers: [...]` used to do. +// +// Simple: every `provideX()` registers a feature for the whole app. +// Intermediate: the order mostly doesn't matter, but each provider is +// app-scoped (root injector). Anything you add here is created once and +// shared — put per-feature providers on routes or components instead. +// Expert: `provideX(withY(), withZ())` is the "feature function" pattern. +// The with* functions are tree-shakable options: if you never call +// withIncrementalHydration(), that code never ships. Prefer this shape when +// you design your own library's providers too. import { ApplicationConfig, provideBrowserGlobalErrorListeners, @@ -15,10 +26,16 @@ import { export const appConfig: ApplicationConfig = { providers: [ + // Routes uncaught errors and unhandled rejections to Angular's ErrorHandler. provideBrowserGlobalErrorListeners(), + // No Zone.js: change detection runs off signals and template events. + // Covered properly in lesson 09. provideZonelessChangeDetection(), + // HttpClient backed by fetch() instead of XHR — required for good SSR. provideHttpClient(withFetch()), provideRouter(routes), + // SSR hydration: reuse server-rendered DOM instead of re-creating it. + // Lesson 12. provideClientHydration(withEventReplay(), withIncrementalHydration()), ], }; diff --git a/src/main.ts b/src/main.ts index 5df75f9..8e212b3 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,6 +1,16 @@ +// [ng-01 structure] The browser entry point. angular.json points +// `architect.build.options.browser` here, so this is the first app code to run. +// +// Simple: bootstrapApplication(RootComponent, config) is the whole startup in +// a standalone app. No AppModule, no platformBrowserDynamic().bootstrapModule(). +// Pitfall: you may still see `platformBrowserDynamic().bootstrapModule(AppModule)` +// in older codebases. That's the NgModule-era equivalent, same job. import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from './app/app.config'; import { App } from './app/app'; +// Expert: a bootstrap failure (a provider throws, a template fails to compile +// in JIT) rejects this promise. Logging it is the minimum. Without the catch +// you get a blank page and an "uncaught (in promise)" with no context. bootstrapApplication(App, appConfig) .catch((err) => console.error(err)); From 66863847b5b4a60ebd1cf44209b23b0c4aa76c49 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:40:01 -0500 Subject: [PATCH 07/74] Add failing specs for an interactive lesson page in Thoughts --- .../lessons/lesson-01-structure.spec.ts | 66 +++++++++++++++++++ .../thoughts-content/thought-detail.spec.ts | 46 +++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-01-structure.spec.ts diff --git a/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts b/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts new file mode 100644 index 0000000..e5bc6d9 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts @@ -0,0 +1,66 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../../test/a11y'; +import { checkImport, Lesson01Structure } from './lesson-01-structure'; + +expect.extend(axeMatchers); + +describe('checkImport — the layering rules the lesson demonstrates', () => { + it('lets the shell and features depend on shared/', () => { + expect(checkImport('shell', 'shared', false).allowed).toBe(true); + expect(checkImport('feature', 'shared', false).allowed).toBe(true); + }); + + it('forbids shared/ reaching up into the shell or a feature', () => { + expect(checkImport('shared', 'shell', false).allowed).toBe(false); + expect(checkImport('shared', 'feature', false).allowed).toBe(false); + }); + + it('forbids the shell statically importing a feature, but allows lazy import()', () => { + expect(checkImport('shell', 'feature', false).allowed).toBe(false); + expect(checkImport('shell', 'feature', true).allowed).toBe(true); + }); + + it('forbids one feature importing another', () => { + expect(checkImport('feature', 'other-feature', false).allowed).toBe(false); + }); +}); + +describe('Lesson01Structure', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson01Structure] }).compileComponents(); + fixture = TestBed.createComponent(Lesson01Structure); + fixture.detectChanges(); + el = fixture.nativeElement as HTMLElement; + }); + + 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('shows real code in code blocks', () => { + expect(el.querySelector('app-code-block pre code')?.textContent).toContain('bootstrapApplication'); + }); + + it('updates the verdict live when the import checker changes', async () => { + const from = el.querySelector('#import-from')!; + const to = el.querySelector('#import-to')!; + from.value = 'shared'; + from.dispatchEvent(new Event('change')); + to.value = 'feature'; + to.dispatchEvent(new Event('change')); + await fixture.whenStable(); + + expect(el.querySelector('[role="status"]')?.textContent).toContain('Not allowed'); + }); + + 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 a2d7ac7..2d244f0 100644 --- a/src/app/thoughts-content/thought-detail.spec.ts +++ b/src/app/thoughts-content/thought-detail.spec.ts @@ -62,3 +62,49 @@ describe('ThoughtDetailComponent', () => { expect(document.title).toContain('Why Angular Signals Changed Everything'); }); }); + +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; + + 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(); + }); +}); From 0e12fb8606bd84d7f999aa44afa7096dfc3d3544 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:42:29 -0500 Subject: [PATCH 08/74] Write lesson 01 with a live import checker --- .../thoughts-content/lessons/code-block.ts | 52 +++ .../lessons/lesson-01-structure.ts | 321 ++++++++++++++++++ 2 files changed, 373 insertions(+) create mode 100644 src/app/thoughts-content/lessons/code-block.ts create mode 100644 src/app/thoughts-content/lessons/lesson-01-structure.ts diff --git a/src/app/thoughts-content/lessons/code-block.ts b/src/app/thoughts-content/lessons/code-block.ts new file mode 100644 index 0000000..f4ac75d --- /dev/null +++ b/src/app/thoughts-content/lessons/code-block.ts @@ -0,0 +1,52 @@ +import { Component, input } from '@angular/core'; + +/** + * A labelled, scrollable code sample for lesson pages. + * + * The code arrives as a string input rather than as template text on purpose: + * Angular would try to compile `{{ }}`, `@if` and `` inside a template, + * so a code sample has to be data, not markup. Interpolating a string is also + * safe by default — Angular escapes it, so nothing in a sample can inject HTML. + */ +@Component({ + selector: 'app-code-block', + template: ` +
+
{{ label() }}
+ +
{{ code() }}
+
+ `, + styles: ` + .code-block { + margin: 12px 0 16px; + border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); + border-radius: 8px; + overflow: hidden; + background: var(--surface-secondary, rgba(0, 0, 0, 0.25)); + } + .code-block-label { + padding: 4px 12px; + font-size: 11px; + color: var(--text-secondary, rgba(255, 255, 255, 0.6)); + border-bottom: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); + } + pre { + margin: 0; + padding: 12px; + overflow-x: auto; + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 12.5px; + line-height: 1.55; + color: var(--text-primary, #fff); + } + pre:focus-visible { + outline: 2px solid var(--focus-ring, #4da3ff); + outline-offset: -2px; + } + `, +}) +export class CodeBlock { + readonly code = input.required(); + readonly label = input('TypeScript'); +} diff --git a/src/app/thoughts-content/lessons/lesson-01-structure.ts b/src/app/thoughts-content/lessons/lesson-01-structure.ts new file mode 100644 index 0000000..3d553c9 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-01-structure.ts @@ -0,0 +1,321 @@ +import { Component, computed, signal } from '@angular/core'; +import { CodeBlock } from './code-block'; + +export type Layer = 'shell' | 'shared' | 'feature' | 'other-feature'; + +export interface ImportVerdict { + allowed: boolean; + reason: string; +} + +/** + * [ng-01 structure] The same layering rules src/app/architecture.spec.ts + * enforces, as a pure function so the lesson can let you poke at them. + */ +export function checkImport(from: Layer, to: Layer, lazy: boolean): ImportVerdict { + if (from === to) return { allowed: true, reason: 'Imports inside one layer are fine.' }; + if (to === 'shared') { + return { allowed: true, reason: 'Everyone may depend on shared/. That is what it is for.' }; + } + if (from === 'shared') { + return { + allowed: false, + reason: 'shared/ must not know who uses it. Reaching up creates a cycle sooner or later.', + }; + } + if (from === 'shell' && (to === 'feature' || to === 'other-feature')) { + return lazy + ? { allowed: true, reason: 'A dynamic import() is the lazy-loading seam. The feature stays its own chunk.' } + : { + allowed: false, + reason: 'A static import pulls the feature into the initial bundle and couples the shell to its internals.', + }; + } + if (to === 'shell') { + return { allowed: false, reason: 'Features never import the shell. Move what they need down into shared/.' }; + } + return { + allowed: false, + reason: 'Features never import each other. Promote the shared piece into shared/ instead.', + }; +} + +const LAYER_LABELS: Record = { + shell: 'shell (app.ts, dock/, menu-bar/)', + shared: 'shared/', + feature: 'apps/settings/', + 'other-feature': 'apps/finder/', +}; + +@Component({ + selector: 'app-lesson-01-structure', + imports: [CodeBlock], + template: ` +
+

Angular guide · 01 of 13

+ +

Simple

+

+ An Angular app starts in src/main.ts, which hands one root component and one + config object to bootstrapApplication. There's no AppModule. + Since v17 new projects are standalone, and since v19 standalone: true is the + default, so you don't even write it. +

+ +

+ The config is a flat list of providers: functions that switch features on for the + whole app. Router, HttpClient, hydration and change detection all live here. +

+ +

+ The other files you'll see in every project: angular.json (build targets, + budgets, assets), tsconfig*.json (keep strict and + strictTemplates on), and app.routes.ts. Since the v20 style guide, + new files drop the type suffix: app.ts, not app.component.ts. +

+ +

Intermediate

+

+ Group by feature, not by file type. components/, + services/ and models/ folders look tidy at ten files and turn into + a scavenger hunt at two hundred. This repo uses three layers: +

+ +

+ Dependencies only point down. The interesting one is shell → feature. That's + forbidden as a static import but fine as a dynamic import(), because that's + how a feature becomes a lazy chunk. +

+ +
+

Try it: may this file import that one?

+
+ + +
+
+ + +
+
+ + +
+

+ {{ verdict().allowed ? '✓ Allowed' : '✗ Not allowed' }}. + {{ verdict().reason }} +

+
+ +

Expert

+

+ Conventions decay unless something fails when you break them. This repo has a spec that + walks src/app and fails CI on a forbidden import. It caught three real + violations: the dock, menu bar and root shell all reached into + apps/settings/ for app-wide state. The fix was to move the state down + to shared/settings/ and leave the screen in the feature. +

+ +

+ At scale the same idea shows up as ESLint's no-restricted-imports or Nx + module-boundary tags, where each library gets a type:feature/type:ui + tag plus rules about which tags may depend on which. Two more expert-level points: providers + in app.config.ts are app-wide singletons, so scope feature-only providers to a + route's providers array; and provideX(withY()) feature functions + tree-shake, so options you never call never ship. +

+ +

Pitfalls

+
    +
  • + Barrel files (index.ts re-exporting a folder) make imports + pretty and quietly create circular dependencies. One stray import of a barrel can also + pull a lazy feature back into the main bundle. +
  • +
  • + shared/ as a junk drawer. If only one feature uses it, it belongs in that + feature. +
  • +
  • + State inside a feature folder that the whole app reads. That's the bug + this lesson fixed. +
  • +
  • + Turning off strictTemplates to silence errors. Those errors + are real bugs in your bindings. +
  • +
  • + Ignoring bundle budgets. angular.json warns at 400 kB + initial here. Treat the warning as a failing test, not noise. +
  • +
+ +

Interview questions

+ @for (qa of interview; track qa.q) { +
+ {{ qa.q }} +

{{ qa.a }}

+
+ } +
+ `, + styles: ` + .lesson { + margin-top: 24px; + font-size: 14px; + line-height: 1.7; + color: var(--text-secondary, rgba(255, 255, 255, 0.8)); + } + .lesson-kicker { + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--accent-color, #007aff); + } + h2 { + margin: 28px 0 8px; + font-size: 17px; + color: var(--text-primary, #fff); + } + h3 { + margin: 0 0 10px; + font-size: 14px; + color: var(--text-primary, #fff); + } + code { + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.92em; + } + .lesson-demo { + margin: 16px 0; + padding: 16px; + border: 1px solid var(--accent-color, #007aff); + border-radius: 10px; + } + .lesson-demo-row { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 8px; + } + .lesson-demo-row label:first-child { + min-width: 96px; + } + select { + font: inherit; + padding: 4px 6px; + border-radius: 6px; + } + .lesson-verdict { + margin: 12px 0 0; + padding: 8px 12px; + border-radius: 6px; + border-left: 4px solid; + } + .lesson-verdict--ok { + border-color: #34c759; + } + .lesson-verdict--bad { + border-color: #ff6b6b; + } + .lesson-qa { + margin-bottom: 8px; + padding: 8px 12px; + border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); + border-radius: 8px; + } + .lesson-qa summary { + cursor: pointer; + color: var(--text-primary, #fff); + } + `, +}) +export class Lesson01Structure { + protected readonly layers: Layer[] = ['shell', 'shared', 'feature', 'other-feature']; + protected readonly layerLabels = LAYER_LABELS; + + protected readonly from = signal('shell'); + protected readonly to = signal('feature'); + protected readonly lazy = signal(false); + protected readonly verdict = computed(() => checkImport(this.from(), this.to(), this.lazy())); + + protected asLayer(event: Event): Layer { + return (event.target as HTMLSelectElement).value as Layer; + } + + protected readonly snippets = { + main: `import { bootstrapApplication } from '@angular/platform-browser'; +import { appConfig } from './app/app.config'; +import { App } from './app/app'; + +bootstrapApplication(App, appConfig) + .catch((err) => console.error(err));`, + config: `export const appConfig: ApplicationConfig = { + providers: [ + provideBrowserGlobalErrorListeners(), + provideZonelessChangeDetection(), + provideHttpClient(withFetch()), + provideRouter(routes), + provideClientHydration(withEventReplay(), withIncrementalHydration()), + ], +};`, + tree: `app.ts, app.routes.ts shell: the desktop chrome +dock/ menu-bar/ window-manager/ spotlight/ +shared/ used by anyone + settings/ app-wide settings state + app-launcher.service.ts +apps/ one folder per desktop app, lazy loaded + settings/ finder/ ...`, + fitness: `it('nothing outside apps/ statically imports from apps/', () => { + const violations = files + .filter((file) => !isInside(file, 'apps')) + .flatMap((file) => + staticRelativeImports(file) + .filter((target) => isInside(target, 'apps')) + .map((target) => \`\${file} → \${target}\`), + ); + expect(violations).toEqual([]); +});`, + }; + + protected readonly interview = [ + { + q: 'How would you structure a large Angular app?', + a: 'By feature, with three layers: a thin shell, shared building blocks, and lazy-loaded feature folders. Dependencies point one way: features and shell depend on shared, never on each other. I enforce that with a lint rule or a fitness test, because a convention nobody checks decays.', + }, + { + q: 'What replaced AppModule?', + a: 'bootstrapApplication(RootComponent, appConfig). appConfig holds the providers an AppModule used to import, as provideRouter, provideHttpClient and so on. Components declare their own dependencies in imports: [] instead of a module doing it for them.', + }, + { + q: "What's the difference between providers in app.config.ts and in a route?", + a: "app.config.ts providers live in the root environment injector: one instance for the whole app. A route's providers array creates a child environment injector, so the service exists only for that route subtree and can be lazy loaded with it.", + }, + { + q: 'Why are barrel files risky in Angular?', + a: 'They hide the real dependency graph. Circular imports appear easily, and importing one symbol from a barrel can drag in the whole folder, including a feature you meant to lazy load, which defeats code splitting.', + }, + { + q: 'Which tsconfig and compiler flags would you insist on?', + a: 'strict for TypeScript, and strictTemplates in angularCompilerOptions so bindings are type-checked in templates. Turning them off hides real bugs, such as passing a possibly-undefined value to an input.', + }, + ]; +} From 80da41edce3a2d41ff2d5df78cc803a850e79bbc Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:42:29 -0500 Subject: [PATCH 09/74] Load a thought's interactive lesson page lazily under its prose --- src/app/thoughts-content/lessons/lessons.ts | 13 +++++++++++++ src/app/thoughts-content/thought-detail.ts | 15 ++++++++++++++- src/app/thoughts-content/thoughts-bodies.ts | 3 +++ src/app/thoughts-content/thoughts-data.ts | 9 +++++++++ 4 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/app/thoughts-content/lessons/lessons.ts diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts new file mode 100644 index 0000000..a22a574 --- /dev/null +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -0,0 +1,13 @@ +import { Type } from '@angular/core'; + +/** + * Thoughts that come with an interactive lesson page, keyed by slug. + * + * Each page is a loader, not a component reference, so every lesson becomes + * its own lazy chunk. This file is only imported by the thought reader, which + * is itself lazy, so none of it reaches the initial bundle. + */ +export const LESSON_PAGES: Record Promise>> = { + 'angular-01-project-structure': () => + import('./lesson-01-structure').then((m) => m.Lesson01Structure), +}; diff --git a/src/app/thoughts-content/thought-detail.ts b/src/app/thoughts-content/thought-detail.ts index c60f2e7..ab807c0 100644 --- a/src/app/thoughts-content/thought-detail.ts +++ b/src/app/thoughts-content/thought-detail.ts @@ -1,10 +1,13 @@ -import { Component, inject } from '@angular/core'; +import { NgComponentOutlet } from '@angular/common'; +import { Component, inject, resource } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { SeoService } from '../shared/seo.service'; +import { LESSON_PAGES } from './lessons/lessons'; import { ThoughtsService } from './thoughts.service'; @Component({ selector: 'app-thought-detail', + imports: [NgComponentOutlet], template: ` @if (thought) {
@@ -17,6 +20,9 @@ import { ThoughtsService } from './thoughts.service'; }
{{ thought.content }}
+ @if (lessonPage.value(); as page) { + + } } @else {
Thought not found.
@@ -100,6 +106,13 @@ export class ThoughtDetailComponent { readonly thought = this.service.getBySlug(this.route.snapshot.paramMap.get('slug') ?? ''); + // 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. + readonly lessonPage = resource({ + loader: () => LESSON_PAGES[this.thought?.slug ?? '']?.() ?? Promise.resolve(undefined), + }); + constructor() { if (this.thought) { this.seo.setThoughtMeta(this.thought); diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index cd392b0..74c2ad0 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -244,4 +244,7 @@ The sharpest infrastructure detail was TLS depth at the edge. develop.angular.pa A few deliberate compromises. Canonical and og:url are pinned to the production origin even when the page is served from staging — I do not want staging indexed under its own URL, and pointing canonical at production is the honest signal to a crawler that the real page lives elsewhere. The essay bodies ship in the initial bundle, which nudges it just past the warning budget; I am keeping that number visible rather than raising the threshold, because the correct fix is lazy-loading the content, not hiding the metric. And I wrote a config-guard test that pins allowedHosts and trustProxyHeaders — the failure mode of both is a silent 400 in production, and the cheapest place to catch that is a unit test that goes red the instant someone edits them out. The payoff is measurable, which is the entire reason to reach for SSR. curl the deployed URL with JavaScript disabled and you get the whole article in the first response: the title, the Open Graph tags a social card reads, the canonical link, and a JSON-LD BlogPosting block — all generated at build time. The desktop shell stays a client app because it should; the content stays static HTML because it should. Two rendering strategies, chosen per route, both proven on a live domain behind a CDN. That is the version of "we use SSR" that survives someone opening the network tab.`, + 'angular-01-project-structure': `I am writing an Angular guide I can learn from and point to: thirteen short lessons, each one tied to a real change in this site. Every lesson goes simple, then intermediate, then expert, then the pitfalls, then the questions I would expect in an interview. The code samples are the actual code from this repo, not toy examples. + +This first one is about the shape of a project: what boots it, where things go, and how to keep the layering honest once there are more files than anyone can hold in their head.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index fb430eb..7e00a56 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -188,4 +188,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['ssr', 'deployment', 'railway', 'cloudflare'], relatedApp: 'readme', }, + { + slug: 'angular-01-project-structure', + title: 'Angular 01: Project structure', + date: '2026-11-21', + summary: + 'The first lesson in my Angular guide: how an app boots, how to lay out folders by feature, and how I enforce the layering with a test instead of a wiki page. Includes a live import checker.', + tags: ['angular-guide', 'architecture', 'angular'], + relatedApp: 'readme', + }, ]; From 1ead8865aa87fbebf3c4b5dbb3d86f7653929245 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:42:45 -0500 Subject: [PATCH 10/74] Bump to 1.4.0 with the lesson 01 changelog entry --- CHANGELOG.md | 8 ++++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 875b536..bb61e5a 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.0 + +- **Interactive lessons in Thoughts**: a thought can now carry a lazily loaded lesson page under its prose. `thoughts-content/lessons/lessons.ts` maps slugs to loaders, and the reader loads the page through a `resource()` so SSR waits for it. The prerendered `/thoughts/angular-01-project-structure` HTML contains the whole lesson, demo included, not an empty slot. Each lesson is its own lazy chunk (lesson 01 is 13 kB), and the initial bundle is unchanged at 372.98 kB +- **Angular guide, lesson 01: project structure**. The first of thirteen lessons I'm writing so I can learn Angular properly and talk about it in depth. Each goes simple → intermediate → expert → pitfalls → interview questions, and the code samples are real code from this repo. This one has a live "may this file import that one?" checker built on the same rules the architecture spec enforces +- **Architecture fitness spec**: `src/app/architecture.spec.ts` fails if anything outside `apps/` statically imports from `apps/` (lazy `import()` is allowed, since that is the code-splitting seam), or if an `@NgModule` appears. It found three real violations on its first run +- **Settings state moved to `shared/settings/`**: `app.ts`, `dock/dock.ts` and `menu-bar/menu-bar.ts` were all importing `SettingsService`/`AppearanceService` out of the `apps/settings/` feature folder. State the whole desktop reads isn't a feature's private business. The System Preferences screen stays in `apps/settings/`; only the services moved +- Bootstrap files (`main.ts`, `app.config.ts`, `app.config.server.ts`) are annotated with `[ng-01]` comments, so `grep -rn "ng-01" src` finds every example the lesson refers to + ## 2026-08-16 - version 1.3.7 - **Changelog guard**: `src/changelog.spec.ts` asserts the top entry is the version `package.json` is on, that it has bullets under it, that no version gets two headings, that versions and dates both run newest first, and that every `## ` heading parses as `YYYY-MM-DD - version X.Y.Z`. Ported from the `changelogEntry.test.ts` in `paul-explore` and `portfolio_api`, which have had this for a while — this repo was the one without it diff --git a/package-lock.json b/package-lock.json index 99de6e1..2257790 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.3.6", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.3.6", + "version": "1.4.0", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index a289c92..f3f100f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.3.7", + "version": "1.4.0", "scripts": { "ng": "ng", "start": "ng serve", From 8d29817de41584bcd359f25b9b98e0a08c1fad71 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:44:34 -0500 Subject: [PATCH 11/74] Add failing specs for lesson building blocks and lesson 02 --- .../lessons/lesson-02-components.spec.ts | 57 ++++++++++++++ .../lessons/lesson-blocks.spec.ts | 78 +++++++++++++++++++ 2 files changed, 135 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-02-components.spec.ts create mode 100644 src/app/thoughts-content/lessons/lesson-blocks.spec.ts diff --git a/src/app/thoughts-content/lessons/lesson-02-components.spec.ts b/src/app/thoughts-content/lessons/lesson-02-components.spec.ts new file mode 100644 index 0000000..130f299 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-02-components.spec.ts @@ -0,0 +1,57 @@ +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 { Lesson02Components } from './lesson-02-components'; + +expect.extend(axeMatchers); + +describe('Lesson02Components', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson02Components] }).compileComponents(); + fixture = TestBed.createComponent(Lesson02Components); + fixture.detectChanges(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-02-components']).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('demo: typing a label flows into the child through input()', async () => { + const label = el.querySelector('#badge-label')!; + label.value = 'Shipped'; + label.dispatchEvent(new Event('input')); + await fixture.whenStable(); + + expect(el.querySelector('app-demo-badge')?.textContent).toContain('Shipped'); + }); + + it('demo: the child increments a model() and the parent sees it', async () => { + el.querySelector('app-demo-badge .demo-badge-bump')!.click(); + await fixture.whenStable(); + + expect(el.querySelector('#badge-count-readout')?.textContent).toContain('1'); + }); + + it('demo: the child emits through output() and the parent logs it', async () => { + el.querySelector('app-demo-badge .demo-badge-dismiss')!.click(); + await fixture.whenStable(); + + expect(el.querySelector('.demo-log')?.textContent).toContain('dismissed'); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lesson-blocks.spec.ts b/src/app/thoughts-content/lessons/lesson-blocks.spec.ts new file mode 100644 index 0000000..0fb04e5 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-blocks.spec.ts @@ -0,0 +1,78 @@ +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../../test/a11y'; +import { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { LessonDemo } from './lesson-demo'; + +expect.extend(axeMatchers); + +@Component({ + imports: [Callout, LessonDemo, InterviewQuestions, CodeBlock], + template: ` +

Mutating an input array

+

Prefer input()

+ + + + `, +}) +class Host { + questions = [ + { q: 'What is a standalone component?', a: 'One that declares its own imports.' }, + { q: 'input() vs @Input()?', a: 'input() returns a signal.' }, + ]; + copiedCount = 0; +} + +describe('lesson building blocks', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + let writeText: ReturnType; + + beforeEach(async () => { + writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + await TestBed.configureTestingModule({ imports: [Host] }).compileComponents(); + fixture = TestBed.createComponent(Host); + fixture.detectChanges(); + el = fixture.nativeElement as HTMLElement; + }); + + it('Callout projects its content and labels the kind in text, not only colour', () => { + const [pitfall, tip] = [...el.querySelectorAll('app-callout')]; + expect(pitfall.getAttribute('role')).toBe('note'); + expect(pitfall.classList).toContain('callout--pitfall'); + expect(pitfall.textContent).toContain('Pitfall'); + expect(pitfall.textContent).toContain('Mutating an input array'); + expect(tip.textContent).toContain('Tip'); + }); + + it('LessonDemo wraps projected controls in a labelled region', () => { + const demo = el.querySelector('app-lesson-demo section')!; + const headingId = demo.getAttribute('aria-labelledby')!; + expect(el.querySelector(`#${headingId}`)?.textContent).toContain('Try it'); + expect(demo.querySelector('button')?.textContent).toContain('poke'); + }); + + it('InterviewQuestions renders one disclosure per question', () => { + const details = el.querySelectorAll('app-interview-questions details'); + expect(details.length).toBe(2); + expect(details[1].querySelector('summary')?.textContent).toContain('input() vs @Input()?'); + }); + + it('CodeBlock copies its code, announces it, and emits copied', async () => { + el.querySelector('app-code-block button')!.click(); + await fixture.whenStable(); + + expect(writeText).toHaveBeenCalledWith('const answer = 42;'); + expect(el.querySelector('app-code-block [role="status"]')?.textContent).toContain('Copied'); + expect(fixture.componentInstance.copiedCount).toBe(1); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); From 228ba10ee18f87291cafc38314a3e499054c35d0 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:47:11 -0500 Subject: [PATCH 12/74] Extract lesson building blocks and a copy button for code samples --- src/app/thoughts-content/lessons/callout.ts | 59 +++++++++++++++++ .../thoughts-content/lessons/code-block.ts | 56 ++++++++++++++--- .../lessons/interview-questions.ts | 38 +++++++++++ .../thoughts-content/lessons/lesson-demo.ts | 38 +++++++++++ src/app/thoughts-content/lessons/lesson.ts | 63 +++++++++++++++++++ 5 files changed, 246 insertions(+), 8 deletions(-) create mode 100644 src/app/thoughts-content/lessons/callout.ts create mode 100644 src/app/thoughts-content/lessons/interview-questions.ts create mode 100644 src/app/thoughts-content/lessons/lesson-demo.ts create mode 100644 src/app/thoughts-content/lessons/lesson.ts diff --git a/src/app/thoughts-content/lessons/callout.ts b/src/app/thoughts-content/lessons/callout.ts new file mode 100644 index 0000000..30a3bff --- /dev/null +++ b/src/app/thoughts-content/lessons/callout.ts @@ -0,0 +1,59 @@ +import { Component, input } from '@angular/core'; + +export type CalloutKind = 'tip' | 'pitfall' | 'expert'; + +const LABELS: Record = { + tip: 'Tip', + pitfall: 'Pitfall', + expert: 'Expert note', +}; + +/** + * [ng-02 components] A presentational component: data in through inputs, + * markup in through content projection, no services, no side effects. + * + *

…

+ * + * `host` metadata binds attributes and classes onto itself, so + * there's no extra wrapper div. It's the modern replacement for @HostBinding. + */ +@Component({ + selector: 'app-callout', + host: { + role: 'note', + '[class]': '"callout callout--" + kind()', + }, + template: ` + + {{ labels[kind()] }} + + `, + styles: ` + :host { + display: block; + margin: 12px 0; + padding: 10px 14px; + border-radius: 8px; + border-left: 4px solid var(--callout-colour); + background: var(--surface-secondary, rgba(255, 255, 255, 0.04)); + } + :host(.callout--tip) { + --callout-colour: #34c759; + } + :host(.callout--pitfall) { + --callout-colour: #ff6b6b; + } + :host(.callout--expert) { + --callout-colour: #bf5af2; + } + .callout-label { + display: block; + font-size: 12px; + color: var(--text-primary, #fff); + } + `, +}) +export class Callout { + readonly kind = input.required(); + protected readonly labels = LABELS; +} diff --git a/src/app/thoughts-content/lessons/code-block.ts b/src/app/thoughts-content/lessons/code-block.ts index f4ac75d..c26b03c 100644 --- a/src/app/thoughts-content/lessons/code-block.ts +++ b/src/app/thoughts-content/lessons/code-block.ts @@ -1,4 +1,4 @@ -import { Component, input } from '@angular/core'; +import { Component, input, output, signal } from '@angular/core'; /** * A labelled, scrollable code sample for lesson pages. @@ -7,12 +7,20 @@ import { Component, input } from '@angular/core'; * Angular would try to compile `{{ }}`, `@if` and `` inside a template, * so a code sample has to be data, not markup. Interpolating a string is also * safe by default — Angular escapes it, so nothing in a sample can inject HTML. + * + * [ng-02 components] The whole public API is three members: two inputs and one + * output. Keep a component's surface that small and it stays reusable. */ @Component({ selector: 'app-code-block', template: `
-
{{ label() }}
+
+ {{ label() }} + + {{ status() }} + +
{{ code() }}
@@ -25,12 +33,32 @@ import { Component, input } from '@angular/core'; overflow: hidden; background: var(--surface-secondary, rgba(0, 0, 0, 0.25)); } - .code-block-label { - padding: 4px 12px; + .code-block-bar { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 6px 4px 12px; font-size: 11px; color: var(--text-secondary, rgba(255, 255, 255, 0.6)); border-bottom: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); } + .code-block-status { + margin-left: auto; + } + button { + font: inherit; + padding: 2px 8px; + border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.15)); + border-radius: 5px; + background: none; + color: var(--text-primary, #fff); + cursor: pointer; + } + button:focus-visible, + pre:focus-visible { + outline: 2px solid var(--focus-ring, #4da3ff); + outline-offset: -2px; + } pre { margin: 0; padding: 12px; @@ -40,13 +68,25 @@ import { Component, input } from '@angular/core'; line-height: 1.55; color: var(--text-primary, #fff); } - pre:focus-visible { - outline: 2px solid var(--focus-ring, #4da3ff); - outline-offset: -2px; - } `, }) export class CodeBlock { readonly code = input.required(); readonly label = input('TypeScript'); + /** Emits the copied text, so a parent can react without reaching into this component. */ + readonly copied = output(); + + protected readonly status = signal(''); + + protected async copy(): Promise { + try { + await navigator.clipboard.writeText(this.code()); + this.status.set('Copied'); + this.copied.emit(this.code()); + } catch { + // Clipboard access is denied on insecure origins and in some iframes. + // Say so rather than pretending it worked. + this.status.set('Copy failed. Select the code instead'); + } + } } diff --git a/src/app/thoughts-content/lessons/interview-questions.ts b/src/app/thoughts-content/lessons/interview-questions.ts new file mode 100644 index 0000000..99e4d73 --- /dev/null +++ b/src/app/thoughts-content/lessons/interview-questions.ts @@ -0,0 +1,38 @@ +import { Component, input } from '@angular/core'; + +export interface InterviewQuestion { + q: string; + a: string; +} + +/** + * [ng-02 components] Native
/ gives a keyboard-operable, + * screen-reader-announced disclosure for free. No open/closed state to manage, + * no ARIA to get wrong. Reach for the platform before writing a toggle. + */ +@Component({ + selector: 'app-interview-questions', + template: ` + @for (item of questions(); track item.q) { +
+ {{ item.q }} +

{{ item.a }}

+
+ } + `, + styles: ` + .qa { + margin-bottom: 8px; + padding: 8px 12px; + border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); + border-radius: 8px; + } + summary { + cursor: pointer; + color: var(--text-primary, #fff); + } + `, +}) +export class InterviewQuestions { + readonly questions = input.required(); +} diff --git a/src/app/thoughts-content/lessons/lesson-demo.ts b/src/app/thoughts-content/lessons/lesson-demo.ts new file mode 100644 index 0000000..94fab4d --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-demo.ts @@ -0,0 +1,38 @@ +import { Component, input } from '@angular/core'; + +let nextDemoId = 0; + +/** + * [ng-02 components] A frame for a lesson's live demo. It owns the chrome + * (border, heading, landmark); the lesson projects whatever controls it needs. + * + * The id counter is per-module rather than random so the server and the + * browser generate the same ids in the same order. A random id would differ + * on hydration and break aria-labelledby. + */ +@Component({ + selector: 'app-lesson-demo', + template: ` +
+

{{ heading() }}

+ +
+ `, + styles: ` + .lesson-demo { + margin: 16px 0; + padding: 16px; + border: 1px solid var(--accent-color, #007aff); + border-radius: 10px; + } + h3 { + margin: 0 0 10px; + font-size: 14px; + color: var(--text-primary, #fff); + } + `, +}) +export class LessonDemo { + readonly heading = input.required(); + protected readonly headingId = `lesson-demo-${nextDemoId++}`; +} diff --git a/src/app/thoughts-content/lessons/lesson.ts b/src/app/thoughts-content/lessons/lesson.ts new file mode 100644 index 0000000..01cdf94 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson.ts @@ -0,0 +1,63 @@ +import { Component, input, ViewEncapsulation } from '@angular/core'; + +/** + * [ng-02 components] The shared typography for every lesson page. + * + * Expert: this is the one component in the app with ViewEncapsulation.None. + * Emulated encapsulation (the default) rewrites selectors so styles only hit + * this component's own template. The

s and s here, though, live in + * each *lesson's* template and are projected in. Encapsulated styles can't + * reach projected content without the deprecated ::ng-deep, so this component + * opts out of encapsulation and scopes itself by hand under `.lesson`. + * Without that prefix, `h2 {}` would restyle every h2 on the site. + */ +@Component({ + selector: 'app-lesson', + encapsulation: ViewEncapsulation.None, + template: ` +
+

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

+ +
+ `, + styles: ` + .lesson { + margin-top: 24px; + font-size: 14px; + line-height: 1.7; + color: var(--text-secondary, rgba(255, 255, 255, 0.8)); + } + .lesson .lesson-kicker { + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--accent-color, #007aff); + } + .lesson h2 { + margin: 28px 0 8px; + font-size: 17px; + color: var(--text-primary, #fff); + } + .lesson code { + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.92em; + } + .lesson .demo-row { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 8px; + } + .lesson select, + .lesson input[type='text'] { + font: inherit; + padding: 4px 6px; + border-radius: 6px; + } + `, +}) +export class Lesson { + /** Two-digit part number, e.g. "02". */ + readonly part = input.required(); +} From 4d585d1fc17a7c2294fb5c6f61b9c76934b3bdf8 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:47:11 -0500 Subject: [PATCH 13/74] Rebuild lesson 01 on the shared lesson blocks --- .../lessons/lesson-01-structure.spec.ts | 2 +- .../lessons/lesson-01-structure.ts | 83 +++---------------- 2 files changed, 14 insertions(+), 71 deletions(-) diff --git a/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts b/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts index e5bc6d9..f983953 100644 --- a/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts +++ b/src/app/thoughts-content/lessons/lesson-01-structure.spec.ts @@ -57,7 +57,7 @@ describe('Lesson01Structure', () => { to.dispatchEvent(new Event('change')); await fixture.whenStable(); - expect(el.querySelector('[role="status"]')?.textContent).toContain('Not allowed'); + expect(el.querySelector('.lesson-verdict[role="status"]')?.textContent).toContain('Not allowed'); }); it('has no axe violations', async () => { diff --git a/src/app/thoughts-content/lessons/lesson-01-structure.ts b/src/app/thoughts-content/lessons/lesson-01-structure.ts index 3d553c9..8286414 100644 --- a/src/app/thoughts-content/lessons/lesson-01-structure.ts +++ b/src/app/thoughts-content/lessons/lesson-01-structure.ts @@ -1,5 +1,8 @@ import { Component, computed, signal } from '@angular/core'; import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; export type Layer = 'shell' | 'shared' | 'feature' | 'other-feature'; @@ -49,10 +52,9 @@ const LAYER_LABELS: Record = { @Component({ selector: 'app-lesson-01-structure', - imports: [CodeBlock], + imports: [Lesson, LessonDemo, CodeBlock, InterviewQuestions], template: ` -
-

Angular guide · 01 of 13

+

Simple

@@ -87,9 +89,8 @@ const LAYER_LABELS: Record = { how a feature becomes a lazy chunk.

-
-

Try it: may this file import that one?

-
+ +
-
+
-
+
= { {{ verdict().allowed ? '✓ Allowed' : '✗ Not allowed' }}. {{ verdict().reason }}

-
+

Expert

@@ -169,61 +170,13 @@ const LAYER_LABELS: Record = {

Interview questions

- @for (qa of interview; track qa.q) { -
- {{ qa.q }} -

{{ qa.a }}

-
- } -
+ + `, styles: ` - .lesson { - margin-top: 24px; - font-size: 14px; - line-height: 1.7; - color: var(--text-secondary, rgba(255, 255, 255, 0.8)); - } - .lesson-kicker { - font-size: 12px; - text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--accent-color, #007aff); - } - h2 { - margin: 28px 0 8px; - font-size: 17px; - color: var(--text-primary, #fff); - } - h3 { - margin: 0 0 10px; - font-size: 14px; - color: var(--text-primary, #fff); - } - code { - font-family: var(--font-mono, ui-monospace, monospace); - font-size: 0.92em; - } - .lesson-demo { - margin: 16px 0; - padding: 16px; - border: 1px solid var(--accent-color, #007aff); - border-radius: 10px; - } - .lesson-demo-row { - display: flex; - align-items: center; - gap: 8px; - margin-bottom: 8px; - } - .lesson-demo-row label:first-child { + .demo-row label:first-child { min-width: 96px; } - select { - font: inherit; - padding: 4px 6px; - border-radius: 6px; - } .lesson-verdict { margin: 12px 0 0; padding: 8px 12px; @@ -236,16 +189,6 @@ const LAYER_LABELS: Record = { .lesson-verdict--bad { border-color: #ff6b6b; } - .lesson-qa { - margin-bottom: 8px; - padding: 8px 12px; - border: 1px solid var(--border-primary, rgba(255, 255, 255, 0.1)); - border-radius: 8px; - } - .lesson-qa summary { - cursor: pointer; - color: var(--text-primary, #fff); - } `, }) export class Lesson01Structure { From 3ac6ed3b2dac85c4d17cad9b149151a8f65502f4 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:47:11 -0500 Subject: [PATCH 14/74] Write lesson 02 with a live input/output/model demo --- .../lessons/lesson-02-components.ts | 285 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 2 + src/app/thoughts-content/thoughts-bodies.ts | 3 + src/app/thoughts-content/thoughts-data.ts | 9 + 4 files changed, 299 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-02-components.ts diff --git a/src/app/thoughts-content/lessons/lesson-02-components.ts b/src/app/thoughts-content/lessons/lesson-02-components.ts new file mode 100644 index 0000000..b896649 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-02-components.ts @@ -0,0 +1,285 @@ +import { Component, input, model, output, 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'; + +type Tone = 'info' | 'warn'; + +/** + * [ng-02 components] The demo child. Every way data crosses a component + * boundary is here in one place: + * input() parent → child, read-only signal + * model() parent ⇄ child, two-way with [(count)] + * output() child → parent, an event + * parent's markup rendered inside the child + */ +@Component({ + selector: 'app-demo-badge', + host: { '[class.demo-badge--warn]': 'tone() === "warn"' }, + template: ` + + {{ label() }} + {{ count() }} + + + `, + styles: ` + :host { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 4px 6px 4px 12px; + border-radius: 999px; + border: 2px solid #0a84ff; + color: var(--text-primary, #fff); + } + :host(.demo-badge--warn) { + border-color: #ff9f0a; + border-style: dashed; + } + .demo-badge-count { + font-variant-numeric: tabular-nums; + } + button { + font: inherit; + border: none; + border-radius: 999px; + padding: 0 8px; + cursor: pointer; + } + `, +}) +export class DemoBadge { + readonly label = input.required(); + readonly tone = input('info'); + readonly count = model(0); + readonly dismissed = output(); + + protected bump(): void { + // Writing a model() updates the parent's signal through [(count)]. + // Writing an input() isn't possible at all: InputSignal has no set(). + this.count.update((n) => n + 1); + } +} + +@Component({ + selector: 'app-lesson-02-components', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions, DemoBadge], + template: ` + +

Simple

+

+ A component is a TypeScript class with a @Component decorator: a + selector (the tag you write), a template, and styles. In a standalone + component, imports lists every component, directive and pipe its template + uses. Forget one and the compiler tells you the tag is unknown. +

+ +

+ Data goes in through input() and events come out through + output(). Both are plain class fields. input() gives you a + signal, so you read it by calling it: kind(). +

+ +

Intermediate

+

+ Two-way binding is model(): the child can write it and the parent's signal + updates through [(count)]. Content projection (<ng-content>) + lets the parent pass markup rather than data, and select routes + pieces into named slots. Every lesson on this site is built that way: the layout, the demo + frame and the callouts are all projection. +

+ + +
+ + +
+
+ Tone (input) + @for (option of tones; track option) { + + } +
+
+ + + +
+

Parent's signal, via [(count)]: {{ count() }}

+
    + @for (entry of log(); track $index) { +
  1. {{ entry }}
  2. + } @empty { +
  3. No events yet. Press ✕ on the badge.
  4. + } +
+
+ + +

+ Lifecycle: with signals you rarely need hooks. Derive with computed() instead + of ngOnChanges, and clean up with inject(DestroyRef).onDestroy() + instead of ngOnDestroy. The hooks still matter for reading existing code: + ngOnInit is the first point where inputs are set, and + ngAfterViewInit is the first point where view queries resolve. +

+ +

Expert

+

+ Dynamic components. The page you are reading is one. The thought reader + doesn't know this lesson exists at compile time: it looks up a loader by slug, awaits the + import(), and hands the class to NgComponentOutlet. For + imperative cases there's ViewContainerRef.createComponent(), which takes + input bindings since v20. +

+ + +

+ app-lesson is the only component here with + ViewEncapsulation.None. Emulated encapsulation can't style projected + content, so it opts out and prefixes every selector with .lesson by hand. + That's the honest alternative to ::ng-deep, which is deprecated. +

+
+

+ Split container components (inject services, own state) from + presentational ones (inputs in, outputs out). Callout and + CodeBlock are presentational: no services, trivially reusable, trivially + testable. +

+ +

Pitfalls

+ +

+ Mutating an input object. this.user().name = 'x' changes + the parent's data behind its back, and OnPush/signals won't notice. Emit an output and + let the owner change it. +

+
+ +

+ Reading a required input in the constructor throws NG0950: inputs + aren't set yet. Read them in templates, computed() or effect(). +

+
+ +

+ Naming an output after a DOM event (click, + change): the native event bubbles too, and the handler fires twice. +

+
+ +

+ Wrapping <ng-content> in @if doesn't + lazily create the content. The parent creates projected content whether it's shown or + not. Use an ng-template input when content should be lazy. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .demo-tones { + border: none; + padding: 0; + margin: 0 0 8px; + } + .demo-tones legend { + float: left; + margin-right: 8px; + } + .demo-log { + font-size: 13px; + margin: 8px 0 0; + } + `, +}) +export class Lesson02Components { + protected readonly tones: Tone[] = ['info', 'warn']; + protected readonly label = signal('Angular'); + protected readonly tone = signal('info'); + protected readonly count = signal(0); + protected readonly log = signal([]); + + protected valueOf(event: Event): string { + return (event.target as HTMLInputElement).value; + } + + protected logEvent(label: string): void { + // A new array, not push(): signals compare by reference, so mutating in + // place would leave the list on screen stale. + this.log.update((entries) => [...entries, `dismissed → "${label}"`]); + } + + protected readonly snippets = { + callout: `@Component({ + selector: 'app-callout', + host: { role: 'note', '[class]': '"callout callout--" + kind()' }, + template: \` + {{ labels[kind()] }} + + \`, +}) +export class Callout { + readonly kind = input.required<'tip' | 'pitfall' | 'expert'>(); +}`, + parent: ` + + + ⭐ +`, + dynamic: `readonly lessonPage = resource({ + loader: () => LESSON_PAGES[this.thought?.slug ?? '']?.() ?? Promise.resolve(undefined), +}); + +// template +@if (lessonPage.value(); as page) { + +}`, + }; + + protected readonly interview = [ + { + q: 'What makes a component standalone, and why did Angular move to it?', + a: 'It declares its own dependencies in imports: [] instead of belonging to an NgModule. The dependency graph is explicit per component, lazy loading works at component granularity, and there is one fewer concept to learn. Standalone has been the default since v19.', + }, + { + q: 'input() vs @Input()?', + a: 'input() returns a read-only signal, so you derive from it with computed() and there is no need for ngOnChanges. It supports required inputs and transforms, and the compiler type-checks it. @Input() is a decorated mutable field and still everywhere in older code.', + }, + { + q: 'How does two-way binding work?', + a: 'It is sugar. [(x)]="v" expands to [x]="v" (xChange)="v = $event". model() declares both halves at once. With a signal you pass the signal itself, [(count)]="count", and Angular writes to it.', + }, + { + q: 'What is content projection and when would you use multi-slot?', + a: 'Passing markup from parent into a child through . Multi-slot uses select with a CSS selector to route parts, for example a card with header, body and footer slots. The parent still owns the projected content: it is created and change-detected as part of the parent.', + }, + { + q: 'How do you create a component dynamically?', + a: 'Declaratively with NgComponentOutlet (inputs via ngComponentOutletInputs), or imperatively with ViewContainerRef.createComponent(). Combine either with a dynamic import() so the component is its own lazy chunk. This site loads every lesson page that way.', + }, + { + q: 'What are the view encapsulation modes?', + a: 'Emulated (default) rewrites selectors with generated attributes so styles stay scoped. None makes them global. ShadowDom uses native shadow roots. Use None sparingly and scope selectors by hand. ::ng-deep is deprecated.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index a22a574..cf6f854 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -10,4 +10,6 @@ import { Type } from '@angular/core'; export const LESSON_PAGES: Record Promise>> = { 'angular-01-project-structure': () => import('./lesson-01-structure').then((m) => m.Lesson01Structure), + 'angular-02-components': () => + import('./lesson-02-components').then((m) => m.Lesson02Components), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 74c2ad0..231e80e 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -247,4 +247,7 @@ The payoff is measurable, which is the entire reason to reach for SSR. curl the 'angular-01-project-structure': `I am writing an Angular guide I can learn from and point to: thirteen short lessons, each one tied to a real change in this site. Every lesson goes simple, then intermediate, then expert, then the pitfalls, then the questions I would expect in an interview. The code samples are the actual code from this repo, not toy examples. This first one is about the shape of a project: what boots it, where things go, and how to keep the layering honest once there are more files than anyone can hold in their head.`, + 'angular-02-components': `Lesson one's page had all its layout, demo frame and Q&A markup inline. Copying that twelve more times would have been the wrong move, so this lesson is the refactor: the page is now built from small components (a layout, a demo frame, callouts, an interview-question list, and a code block that copies to the clipboard), and lesson one was rebuilt on them. + +That makes components the natural topic: what goes in through inputs, what comes out through outputs, what gets projected, and when a component should own nothing at all.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index 7e00a56..db38826 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -197,4 +197,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'architecture', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-02-components', + title: 'Angular 02: Components', + date: '2026-11-21', + summary: + 'Standalone components, input(), output(), model() and content projection, with a live demo of data crossing a component boundary. Built while extracting the reusable blocks every lesson page now uses.', + tags: ['angular-guide', 'components', 'angular'], + relatedApp: 'readme', + }, ]; From 1baa3e4d42976f595b2145340876b4b7d09913a3 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:47:24 -0500 Subject: [PATCH 15/74] Bump to 1.4.1 with the lesson 02 changelog entry --- CHANGELOG.md | 8 ++++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb61e5a..78f34fe 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.1 + +- **Angular guide, lesson 02: components** (`/thoughts/angular-02-components`). Covers standalone components, `input()`, `output()`, `model()`, content projection, dynamic components and view encapsulation. The live demo is a badge whose label and tone flow in through inputs, whose count is two-way through `[(count)]`, and whose dismiss button emits an output into an event log +- **Lesson building blocks**: the layout, demo frame, callouts and interview questions that lesson 01 had inline are now components (`Lesson`, `LessonDemo`, `Callout`, `InterviewQuestions`), and lesson 01 is rebuilt on them. `Lesson` is the only `ViewEncapsulation.None` component in the app, because it has to style projected content. It scopes every selector under `.lesson` by hand +- **Copy button on code samples**: `CodeBlock` copies to the clipboard and announces "Copied" through a live region. If clipboard access is denied it says so instead of failing silently +- Callouts name their kind in text ("Pitfall", "Tip", "Expert note"), so the colour bar is never the only signal +- Initial bundle 372.98 kB → 375.71 kB. Nothing lesson-specific is eager; the growth is the `@angular/core` code behind `model()` and `output()`, which esbuild hoists into the shared core chunk once a lazy chunk uses it + ## 2026-11-21 - version 1.4.0 - **Interactive lessons in Thoughts**: a thought can now carry a lazily loaded lesson page under its prose. `thoughts-content/lessons/lessons.ts` maps slugs to loaders, and the reader loads the page through a `resource()` so SSR waits for it. The prerendered `/thoughts/angular-01-project-structure` HTML contains the whole lesson, demo included, not an empty slot. Each lesson is its own lazy chunk (lesson 01 is 13 kB), and the initial bundle is unchanged at 372.98 kB diff --git a/package-lock.json b/package-lock.json index 2257790..6b91475 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.0", + "version": "1.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.0", + "version": "1.4.1", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index f3f100f..93975e5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.0", + "version": "1.4.1", "scripts": { "ng": "ng", "start": "ng serve", From 375d607e8726f37008b915b9fa6db5646fbfec00 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:49:09 -0500 Subject: [PATCH 16/74] Add failing specs for the double keydown, thought dates and lesson 03 --- src/app/app.spec.ts | 28 +++++++ .../lessons/lesson-03-templates.spec.ts | 75 +++++++++++++++++++ .../reading-time.pipe.spec.ts | 16 ++++ .../thoughts-content/thought-detail.spec.ts | 10 +++ 4 files changed, 129 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-03-templates.spec.ts create mode 100644 src/app/thoughts-content/reading-time.pipe.spec.ts diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index 85c63b9..0817da7 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -2,6 +2,7 @@ import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { provideRouter, Router } from '@angular/router'; import { App } from './app'; +import { KeyboardShortcutService } from './shared/keyboard-shortcut.service'; @Component({ template: '' }) class StubThought {} @@ -65,4 +66,31 @@ describe('App', () => { expect(reader.classList.contains('thoughts-reader--open')).toBe(false); }); }); + + describe('global keyboard shortcuts', () => { + const press = (init: KeyboardEventInit) => { + const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }); + document.dispatchEvent(event); + return event; + }; + + it('opens Spotlight on one ⌃⌥Space (each keydown is handled exactly once)', () => { + const fixture = TestBed.createComponent(App); + fixture.detectChanges(); + const shortcuts = TestBed.inject(KeyboardShortcutService); + + press({ code: 'Space', key: ' ', ctrlKey: true, altKey: true }); + + expect(shortcuts.spotlightOpen()).toBe(true); + }); + + it('leaves ⌘Space to the browser and macOS', () => { + const fixture = TestBed.createComponent(App); + fixture.detectChanges(); + + const event = press({ code: 'Space', key: ' ', metaKey: true }); + + expect(event.defaultPrevented).toBe(false); + }); + }); }); diff --git a/src/app/thoughts-content/lessons/lesson-03-templates.spec.ts b/src/app/thoughts-content/lessons/lesson-03-templates.spec.ts new file mode 100644 index 0000000..521efe1 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-03-templates.spec.ts @@ -0,0 +1,75 @@ +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 { Lesson03Templates } from './lesson-03-templates'; + +expect.extend(axeMatchers); + +describe('Lesson03Templates', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + const click = async (selector: string) => { + el.querySelector(selector)!.click(); + await fixture.whenStable(); + }; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson03Templates] }).compileComponents(); + fixture = TestBed.createComponent(Lesson03Templates); + fixture.detectChanges(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-03-templates']).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']), + ); + }); + + describe('property vs attribute demo', () => { + let probe: HTMLInputElement; + + beforeEach(() => { + probe = el.querySelector('#binding-probe')!; + probe.value = 'typed by hand'; + probe.dispatchEvent(new Event('input')); + }); + + it('[attr.value] changes the attribute but not what the box shows once typed in', async () => { + await click('#set-attribute'); + expect(probe.getAttribute('value')).toContain('attribute'); + expect(probe.value).toBe('typed by hand'); + }); + + it('[value] changes what the box shows', async () => { + await click('#set-property'); + expect(probe.value).toContain('property'); + }); + }); + + describe('control flow demo', () => { + it('removes a tag and switches the summary as the count changes', async () => { + const summary = () => el.querySelector('#tag-summary')?.textContent ?? ''; + expect(summary()).toContain('3 tags'); + + await click('.tag-remove'); + await click('.tag-remove'); + expect(summary()).toContain('One tag'); + + await click('.tag-remove'); + expect(summary()).toContain('No tags'); + expect(el.querySelector('.tag-list')?.textContent).toContain('All gone'); + }); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/reading-time.pipe.spec.ts b/src/app/thoughts-content/reading-time.pipe.spec.ts new file mode 100644 index 0000000..c0de59d --- /dev/null +++ b/src/app/thoughts-content/reading-time.pipe.spec.ts @@ -0,0 +1,16 @@ +import { ReadingTimePipe } from './reading-time.pipe'; + +describe('ReadingTimePipe', () => { + const pipe = new ReadingTimePipe(); + const words = (count: number) => Array.from({ length: count }, () => 'word').join(' '); + + it('rounds up at 200 words a minute', () => { + expect(pipe.transform(words(200))).toBe('1 min read'); + expect(pipe.transform(words(201))).toBe('2 min read'); + }); + + it('never reports zero, and ignores extra whitespace', () => { + expect(pipe.transform('')).toBe('1 min read'); + expect(pipe.transform(' one \n\n two ')).toBe('1 min read'); + }); +}); diff --git a/src/app/thoughts-content/thought-detail.spec.ts b/src/app/thoughts-content/thought-detail.spec.ts index 2d244f0..3f154bf 100644 --- a/src/app/thoughts-content/thought-detail.spec.ts +++ b/src/app/thoughts-content/thought-detail.spec.ts @@ -58,6 +58,16 @@ describe('ThoughtDetailComponent', () => { 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'); + }); + + it('shows a reading time for a prose thought', () => { + expect(nativeEl.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'); }); From 3d5d569a38e07bee795f12c0137c312701cec911 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:49:48 -0500 Subject: [PATCH 17/74] Add a failing spec for formatted dates on thought cards --- src/app/thoughts-content/thoughts-list.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/app/thoughts-content/thoughts-list.spec.ts b/src/app/thoughts-content/thoughts-list.spec.ts index 0f946ff..c665c6e 100644 --- a/src/app/thoughts-content/thoughts-list.spec.ts +++ b/src/app/thoughts-content/thoughts-list.spec.ts @@ -25,6 +25,11 @@ describe('ThoughtsListComponent', () => { nativeEl = fixture.nativeElement as HTMLElement; }); + it('formats card dates in UTC, like the reader does', () => { + const dates = [...nativeEl.querySelectorAll('.thought-card-date')].map((d) => d.textContent); + expect(dates).toContain('Jun 15, 2026'); + }); + it('should render a card for each thought entry', () => { const service = TestBed.inject(ThoughtsService); const cards = nativeEl.querySelectorAll('.thought-card'); From 447f9c4cc20841362ace72e2057c37dda76b924e Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:52:47 -0500 Subject: [PATCH 18/74] Handle each desktop keydown once and stop swallowing Cmd+Space --- src/app/app.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/app/app.ts b/src/app/app.ts index f4f3c93..708be3c 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,5 +1,5 @@ import { NgComponentOutlet } from '@angular/common'; -import { Component, effect, HostListener, inject, viewChild } from '@angular/core'; +import { Component, effect, inject, viewChild } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; import { NavigationEnd, Router, RouterOutlet } from '@angular/router'; import { filter, map } from 'rxjs'; @@ -32,6 +32,10 @@ import { WindowManagerService } from './window-manager/window-manager.service'; ], templateUrl: './app.html', styleUrl: './app.css', + // [ng-03 templates] Event binding on the host, or here on `document`. + // Preferred over @HostListener: it's plain metadata, it's type-checked + // against the class, and it's the style the Angular team now recommends. + host: { '(document:keydown)': 'onKeydown($event)' }, }) export class App { protected readonly launcher = inject(AppLauncherService); @@ -76,17 +80,17 @@ export class App { }); } - @HostListener('document:keydown', ['$event']) + // [ng-03 templates] Bound through `host: { '(document:keydown)': … }` above. + // This used to call handleKeydown twice, so every toggle shortcut flipped + // and flipped back: ⌃⌥Space never opened Spotlight. It also still + // preventDefault()ed ⌘Space, which the 1.3.4 remap meant to hand back to + // the browser. One event, one handler call. onKeydown(event: KeyboardEvent): void { if (event.key === 'Escape' && this.onThoughtsRoute()) { this.closeThoughts(); return; } this.shortcuts.handleKeydown(event); - if (event.metaKey && event.code === 'Space') { - event.preventDefault(); - } - this.shortcuts.handleKeydown(event); } toggleSpotlight(): void { From 46a5bd554f2ef9584c882e6166473e68075452ff Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:52:47 -0500 Subject: [PATCH 19/74] Format thought dates in UTC and show reading time --- src/app/thoughts-content/reading-time.pipe.ts | 19 +++++++++++++ src/app/thoughts-content/thought-detail.ts | 16 +++++++++-- src/app/thoughts-content/thoughts-list.ts | 7 ++++- .../thoughts-content/utc-date.pipe.spec.ts | 14 ++++++++++ src/app/thoughts-content/utc-date.pipe.ts | 28 +++++++++++++++++++ 5 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 src/app/thoughts-content/reading-time.pipe.ts create mode 100644 src/app/thoughts-content/utc-date.pipe.spec.ts create mode 100644 src/app/thoughts-content/utc-date.pipe.ts diff --git a/src/app/thoughts-content/reading-time.pipe.ts b/src/app/thoughts-content/reading-time.pipe.ts new file mode 100644 index 0000000..1541012 --- /dev/null +++ b/src/app/thoughts-content/reading-time.pipe.ts @@ -0,0 +1,19 @@ +import { Pipe, PipeTransform } from '@angular/core'; + +const WORDS_PER_MINUTE = 200; + +/** + * [ng-03 templates] A custom pipe: `{{ thought.content | readingTime }}`. + * + * Pipes are pure by default, so Angular only re-runs transform() when the + * input reference changes. That makes a pipe the right place for a derivation + * that's called from a template. A method call like `{{ readingTime(text) }}` + * re-runs on every change detection pass that touches this view. + */ +@Pipe({ name: 'readingTime' }) +export class ReadingTimePipe implements PipeTransform { + transform(text: string): string { + const words = text.split(/\s+/).filter(Boolean).length; + return `${Math.max(1, Math.ceil(words / WORDS_PER_MINUTE))} min read`; + } +} diff --git a/src/app/thoughts-content/thought-detail.ts b/src/app/thoughts-content/thought-detail.ts index ab807c0..21fa16b 100644 --- a/src/app/thoughts-content/thought-detail.ts +++ b/src/app/thoughts-content/thought-detail.ts @@ -3,17 +3,26 @@ import { Component, inject, resource } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { SeoService } from '../shared/seo.service'; import { LESSON_PAGES } from './lessons/lessons'; +import { ReadingTimePipe } from './reading-time.pipe'; +import { UtcDatePipe } from './utc-date.pipe'; import { ThoughtsService } from './thoughts.service'; @Component({ selector: 'app-thought-detail', - imports: [NgComponentOutlet], + imports: [NgComponentOutlet, UtcDatePipe, ReadingTimePipe], template: ` @if (thought) {

{{ thought.title }}

-
{{ thought.date }}
+ +
+ + @if (!hasLessonPage) { + · {{ thought.content | readingTime }} + } +
@for (tag of thought.tags; track tag) { {{ tag }} @@ -106,6 +115,9 @@ export class ThoughtDetailComponent { readonly thought = this.service.getBySlug(this.route.snapshot.paramMap.get('slug') ?? ''); + // 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; + // 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. diff --git a/src/app/thoughts-content/thoughts-list.ts b/src/app/thoughts-content/thoughts-list.ts index 9b82e6a..fb46cdd 100644 --- a/src/app/thoughts-content/thoughts-list.ts +++ b/src/app/thoughts-content/thoughts-list.ts @@ -2,9 +2,11 @@ import { Component, inject } from '@angular/core'; import { Router } from '@angular/router'; import { SeoService } from '../shared/seo.service'; import { ThoughtsService } from './thoughts.service'; +import { UtcDatePipe } from './utc-date.pipe'; @Component({ selector: 'app-thoughts-list', + imports: [UtcDatePipe], template: `

Thoughts

@@ -17,7 +19,9 @@ import { ThoughtsService } from './thoughts.service'; (keydown.enter)="navigate(thought.slug)" >
{{ thought.title }}
-
{{ thought.date }}
+
@for (tag of thought.tags; track tag) { {{ tag }} @@ -70,6 +74,7 @@ import { ThoughtsService } from './thoughts.service'; } .thought-card-date { + display: block; font-size: 11px; color: var(--text-secondary, rgba(255, 255, 255, 0.5)); margin-bottom: 8px; diff --git a/src/app/thoughts-content/utc-date.pipe.spec.ts b/src/app/thoughts-content/utc-date.pipe.spec.ts new file mode 100644 index 0000000..feea0d4 --- /dev/null +++ b/src/app/thoughts-content/utc-date.pipe.spec.ts @@ -0,0 +1,14 @@ +import { UtcDatePipe } from './utc-date.pipe'; + +describe('UtcDatePipe', () => { + const pipe = new UtcDatePipe(); + + it('formats a YYYY-MM-DD as a medium date without shifting the day', () => { + expect(pipe.transform('2026-06-15')).toBe('Jun 15, 2026'); + expect(pipe.transform('2026-01-01')).toBe('Jan 1, 2026'); + }); + + it('fails loudly on a date it cannot parse instead of printing "Invalid Date"', () => { + expect(() => pipe.transform('not-a-date')).toThrow(/not-a-date/); + }); +}); diff --git a/src/app/thoughts-content/utc-date.pipe.ts b/src/app/thoughts-content/utc-date.pipe.ts new file mode 100644 index 0000000..6e796e1 --- /dev/null +++ b/src/app/thoughts-content/utc-date.pipe.ts @@ -0,0 +1,28 @@ +import { Pipe, PipeTransform } from '@angular/core'; + +// Built once at module load; constructing an Intl formatter per call is the slow part. +const MEDIUM_UTC = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeZone: 'UTC' }); + +/** + * [ng-03 templates] `{{ thought.date | utcDate }}` → "Jun 15, 2026". + * + * Why not `| date: 'mediumDate' : 'UTC'`? That was the first version, and the + * production build said no: initial bundle +13 kB. @angular/common ships as + * one module that this app already loads eagerly, so using DatePipe anywhere, + * even in a lazy route, pulls its locale formatting into the initial chunk. + * The platform's Intl API does the same job in a few lines for free. + * + * The 'UTC' timezone is the bit that matters either way: '2026-06-15' parses as + * UTC midnight, so formatting in local time shows the 14th west of Greenwich, + * and a server in another zone would render a different day than the browser. + */ +@Pipe({ name: 'utcDate' }) +export class UtcDatePipe implements PipeTransform { + transform(isoDate: string): string { + const parsed = new Date(isoDate); + if (Number.isNaN(parsed.getTime())) { + throw new Error(`utcDate: cannot parse "${isoDate}" as a date`); + } + return MEDIUM_UTC.format(parsed); + } +} From 42043eb9241b67452bb5e9a52ae087049f9e8666 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:52:47 -0500 Subject: [PATCH 20/74] Write lesson 03 with property-vs-attribute and control-flow demos --- .../lessons/lesson-03-templates.ts | 280 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 2 + src/app/thoughts-content/thoughts-bodies.ts | 3 + src/app/thoughts-content/thoughts-data.ts | 9 + 4 files changed, 294 insertions(+) create mode 100644 src/app/thoughts-content/lessons/lesson-03-templates.ts diff --git a/src/app/thoughts-content/lessons/lesson-03-templates.ts b/src/app/thoughts-content/lessons/lesson-03-templates.ts new file mode 100644 index 0000000..e9ebcd8 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-03-templates.ts @@ -0,0 +1,280 @@ +import { Component, 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'; + +const STARTING_TAGS = ['signals', 'pipes', 'control-flow']; + +@Component({ + selector: 'app-lesson-03-templates', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions], + template: ` + +

Simple

+

+ A template is HTML with four kinds of binding. {{ literal.interpolation }} + interpolates text, [prop]="expr" sets a DOM property, + (event)="handler()" listens, and [(x)]="signal" does both. Control + flow is built in: @if/@else, @for and + @switch. Pipes format values on the way out: + {{ literal.pipe }}. +

+ +

+ @for requires a track expression. It's how Angular knows which + DOM row belongs to which item when the list changes, so it can move rows instead of + rebuilding them. +

+ +

Intermediate

+

+ Properties are not attributes. An attribute is the initial value written + in the HTML; a property is the live value on the DOM object. [value] sets the + property. [attr.value] sets the attribute, which an input ignores once someone + has typed in it. Use [attr.x] only where no property exists: + aria-*, colspan, SVG. +

+ + +

Type something in the box, then press each button.

+
+ + +
+
+ + +
+

{{ explanation() }}

+
+ +

+ The rest of the everyday toolkit: [class.active]="on" and + [style.width.px]="w" for single classes and styles; + #ref template variables to grab an element or component; + @let to name a value once; key filters like + (keydown.enter); and $index, $first, + $last, $count inside @for. +

+ + +
    + @for (tag of tags(); track tag; let position = $index, isLast = $last) { +
  • + {{ position + 1 }}. {{ tag }}{{ isLast ? ' (last)' : '' }} + +
  • + } @empty { +
  • All gone.
  • + } +
+ @let count = tags().length; +

+ @switch (count) { + @case (0) { No tags left. } + @case (1) { One tag left. } + @default { {{ count }} tags left. } + } +

+
+ + +

Expert

+

+ Pipes are pure by default: transform() only re-runs when its + input reference changes. A method call in a template, like + {{ literal.methodCall }}, runs on every change detection pass that + checks the view. This site's reading time is a pure pipe for that reason. Impure pipes + (pure: false) run every pass; async is the famous one. +

+ + +

+ The dates on this site first used | date: 'mediumDate' : 'UTC'. The + production build put the initial bundle up 13 kB, even though both + thought views are lazy. @angular/common ships as one module that the app + already loads eagerly, so DatePipe's locale formatting landed in the initial + chunk. A five-line utcDate pipe over Intl.DateTimeFormat + prints the same "Jun 15, 2026" for free. Read the build output, not just the tests. +

+
+

+ Host event bindings. Listen on the component's own element, or on + window/document, through host metadata. That's + preferred over @HostListener. Writing this lesson turned up a real bug in the + desktop's handler: it called the shortcut service twice per keydown, so ⌃⌥Space + opened Spotlight and immediately closed it again. +

+ +

+ Under the sugar: the old *ngIf/*ngFor desugar to + <ng-template> plus a directive. You'll meet them in every pre-v17 + codebase, along with ngTemplateOutlet for passing a reusable template and + context into a child. The built-in control flow compiles to instructions directly, needs no + import, and type-narrows inside @if. +

+ +

+ Angular sanitizes [innerHTML], [href] and + [style] values automatically. DomSanitizer.bypassSecurityTrust* + turns that off, so every call to it deserves a code-review comment explaining why the + input can be trusted. +

+
+ +

Pitfalls

+ +

+ track $index on a list that reorders or deletes. Rows get + reused for the wrong items, so focus, input text and animations jump to the neighbour. + Track a stable id. +

+
+ +

+ Timezones in date formatting. '2026-06-15' parses as UTC + midnight. Format it in local time (what | date does unless you pass + 'UTC') and everyone west of Greenwich sees June 14, while an SSR server in + another zone renders a different date than the browser hydrates. +

+
+ +

+ A <button> inside a <form> defaults + to type="submit". Every non-submit button needs type="button". +

+
+ +

+ Expensive work in template expressions. Filtering or sorting in a method + the template calls runs it on every check. Move it into a computed() or a pure + pipe. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .tag-list { + margin: 0; + padding-left: 0; + list-style: none; + } + .tag-list li { + margin-bottom: 6px; + } + `, +}) +export class Lesson03Templates { + // Literal template syntax shown in prose. Interpolated strings are never + // re-parsed as template, so binding them is the safe way to print "{{". + protected readonly literal = { + interpolation: '{{ value }}', + pipe: "{{ date | date: 'mediumDate' }}", + methodCall: '{{ readingTime(text) }}', + }; + + protected readonly propertyValue = signal(''); + protected readonly attributeValue = signal(''); + protected readonly explanation = signal('Nothing set yet.'); + private presses = 0; + + protected setAttribute(): void { + this.attributeValue.set(`attribute #${++this.presses}`); + this.explanation.set( + 'The value attribute changed (check devtools), but once you have typed, the box keeps showing your text.', + ); + } + + protected setProperty(): void { + this.propertyValue.set(`property #${++this.presses}`); + this.explanation.set('The value property changed, and the box shows it straight away.'); + } + + protected readonly tags = signal(STARTING_TAGS); + + protected remove(tag: string): void { + this.tags.update((tags) => tags.filter((t) => t !== tag)); + } + + protected resetTags(): void { + this.tags.set(STARTING_TAGS); + } + + protected readonly snippets = { + detail: `

{{ thought.title }}

+ +@if (!hasLessonPage) { + · {{ thought.content | readingTime }} +} +@for (tag of thought.tags; track tag) { + {{ tag }} +}`, + controlFlow: `@for (tag of tags(); track tag; let position = $index, isLast = $last) { +
  • + {{ position + 1 }}. {{ tag }}{{ isLast ? ' (last)' : '' }} + +
  • +} @empty { +
  • All gone.
  • +} + +@let count = tags().length; +@switch (count) { + @case (0) { No tags left. } + @case (1) { One tag left. } + @default { {{ count }} tags left. } +}`, + pipe: `@Pipe({ name: 'readingTime' }) +export class ReadingTimePipe implements PipeTransform { + transform(text: string): string { + const words = text.split(/\\s+/).filter(Boolean).length; + return \`\${Math.max(1, Math.ceil(words / 200))} min read\`; + } +}`, + hostListener: `// Before: every toggle fired twice, so ⌃⌥Space opened and closed Spotlight +@HostListener('document:keydown', ['$event']) +onKeydown(event: KeyboardEvent): void { + this.shortcuts.handleKeydown(event); + if (event.metaKey && event.code === 'Space') event.preventDefault(); + this.shortcuts.handleKeydown(event); +} + +// After: binding declared as metadata, one call per event +@Component({ host: { '(document:keydown)': 'onKeydown($event)' } }) +onKeydown(event: KeyboardEvent): void { + this.shortcuts.handleKeydown(event); +}`, + }; + + protected readonly interview = [ + { + q: "What's the difference between property binding and attribute binding?", + a: '[x] sets the DOM property, the live value. [attr.x] sets the HTML attribute, the initial value. They diverge for things like an input value after typing. Use attr only when there is no property, such as aria-*, colspan or SVG attributes.', + }, + { + q: 'Why does @for require track, and what should you track by?', + a: 'track lets Angular map items to DOM rows across changes, so it can move or keep rows instead of recreating them. Track a stable unique id. $index is only safe for static lists that never reorder or delete.', + }, + { + q: 'Pure vs impure pipes?', + a: "A pure pipe re-runs only when its input reference changes, so it is effectively memoised per binding. An impure pipe runs on every change detection pass. Most custom pipes should be pure. AsyncPipe is the classic impure one, because it has to check for new emissions.", + }, + { + q: 'Built-in control flow vs *ngIf / *ngFor?', + a: "@if, @for and @switch are part of the template language. They need no imports, @if narrows types, @for makes tracking mandatory and has @empty, and they're faster. The structural directives desugar to ng-template plus a directive and are still common in older code. There's an automatic migration: ng generate @angular/core:control-flow.", + }, + { + q: 'How do you listen to a global event like keydown on document?', + a: "host: { '(document:keydown)': 'onKey($event)' } in the component metadata, or @HostListener in older code. Both clean themselves up when the component is destroyed. Never add a raw addEventListener without removing it in DestroyRef.", + }, + { + q: 'How does Angular protect against XSS in templates?', + a: 'Interpolation is always text-escaped, and values bound into innerHTML, URLs and styles are sanitized by context. bypassSecurityTrust* disables that for one value, so it should only ever see trusted input.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index cf6f854..74f93c6 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -12,4 +12,6 @@ export const LESSON_PAGES: Record Promise>> = { import('./lesson-01-structure').then((m) => m.Lesson01Structure), 'angular-02-components': () => import('./lesson-02-components').then((m) => m.Lesson02Components), + 'angular-03-templates': () => + import('./lesson-03-templates').then((m) => m.Lesson03Templates), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 231e80e..2315cbe 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -250,4 +250,7 @@ This first one is about the shape of a project: what boots it, where things go, 'angular-02-components': `Lesson one's page had all its layout, demo frame and Q&A markup inline. Copying that twelve more times would have been the wrong move, so this lesson is the refactor: the page is now built from small components (a layout, a demo frame, callouts, an interview-question list, and a code block that copies to the clipboard), and lesson one was rebuilt on them. That makes components the natural topic: what goes in through inputs, what comes out through outputs, what gets projected, and when a component should own nothing at all.`, + '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.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index db38826..94337fd 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -206,4 +206,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'components', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-03-templates', + title: 'Angular 03: Templates and binding', + date: '2026-11-21', + summary: + 'Property vs attribute binding, built-in control flow, pipes and host event bindings. Writing it turned up a keyboard handler that ran twice per keypress, and dates that would have shown the day before for half the world.', + tags: ['angular-guide', 'templates', 'angular'], + relatedApp: 'readme', + }, ]; From 7df9d1012ef6d01cf830e69e6c9a0861c02976c0 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 09:53:05 -0500 Subject: [PATCH 21/74] Bump to 1.4.2 with the lesson 03 changelog entry --- CHANGELOG.md | 9 +++++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78f34fe..f242993 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ All notable changes to this project will be documented in this file. +## 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` +- **fix: ⌘Space was still swallowed.** The same handler kept a `preventDefault()` on ⌘Space that the 1.3.4 remap meant to remove, so the real macOS Spotlight shortcut did nothing while the site had focus. Specs now pin both: one ⌃⌥Space opens Spotlight, and ⌘Space is left un-prevented +- **Readable thought dates**: cards and the reader show "Jun 15, 2026" instead of `2026-06-15`, inside a `
    -
    + + +
    - - @if (form.controls.name.touched && form.controls.name.invalid) { - Name is required + + @if (showError('name')) { + Name is required }
    - - @if (form.controls.email.touched && form.controls.email.invalid) { - Valid email is required + + @if (showError('email')) { + Valid email is required }
    @@ -36,31 +58,37 @@ type SubmissionStatus = 'idle' | 'pending' | 'success' | 'error'; formControlName="message" placeholder="Your message..." rows="6" + [attr.aria-invalid]="showError('message') || null" + [attr.aria-describedby]="showError('message') ? 'contact-message-error' : null" > - @if (form.controls.message.touched && form.controls.message.invalid) { - Message is required + @if (showError('message')) { + Message is required }
    +
    -
    - @if (submissionStatus() === 'pending') { -
    Sending message...
    - } - @if (submissionStatus() === 'success') { -
    Message sent successfully!
    - } - @if (submissionStatus() === 'error') { -
    Failed to send message. Please try again.
    - } + +
    + @if (submissionStatus() === 'pending') { +
    Sending message...
    + } + @if (submissionStatus() === 'success') { +
    Message sent successfully!
    + } + @if (submissionStatus() === 'error') { +
    Failed to send message. Please try again.
    + } +
    `, @@ -191,17 +219,32 @@ type SubmissionStatus = 'idle' | 'pending' | 'success' | 'error'; }) export class ContactApp { private readonly fb = inject(FormBuilder); + private readonly host = inject>(ElementRef); + // [ng-08 forms] nonNullable: reset() goes back to '' rather than null, so + // the value type is string, not string | null. readonly form = this.fb.nonNullable.group({ - name: ['', Validators.required], + name: ['', notBlank], email: ['', [Validators.required, Validators.email]], - message: ['', Validators.required], + message: ['', notBlank], }); readonly submissionStatus = signal('idle'); + /** Errors wait until the field is touched, so nobody is told off before they've typed. */ + showError(field: keyof typeof this.form.controls): boolean { + const control = this.form.controls[field]; + return control.touched && control.invalid; + } + onSubmit() { - if (this.form.invalid) return; + if (this.form.invalid) { + // Show every error at once, then take the user to the first one. + this.form.markAllAsTouched(); + const firstInvalid = Object.entries(this.form.controls).find(([, control]) => control.invalid); + this.host.nativeElement.querySelector(`#contact-${firstInvalid?.[0]}`)?.focus(); + return; + } this.submissionStatus.set('pending'); diff --git a/src/app/shared/validators.spec.ts b/src/app/shared/validators.spec.ts index e3f2125..b950430 100644 --- a/src/app/shared/validators.spec.ts +++ b/src/app/shared/validators.spec.ts @@ -3,10 +3,10 @@ import { notBlank } from './validators'; describe('notBlank', () => { it.each(['', ' ', '\n\t '])('flags %j as blank', (value) => { - expect(notBlank(new FormControl(value))).toEqual({ blank: true }); + expect(notBlank(new FormControl(value, { nonNullable: true }))).toEqual({ blank: true }); }); it('passes text with something in it, even with spaces around', () => { - expect(notBlank(new FormControl(' hi '))).toBeNull(); + expect(notBlank(new FormControl(' hi ', { nonNullable: true }))).toBeNull(); }); }); diff --git a/src/app/shared/validators.ts b/src/app/shared/validators.ts new file mode 100644 index 0000000..817e582 --- /dev/null +++ b/src/app/shared/validators.ts @@ -0,0 +1,12 @@ +import { AbstractControl, ValidationErrors } from '@angular/forms'; + +// [ng-08 forms] A validator is a plain function: control in, errors or null +// out. Validators.required only rejects '' (and null), so " " passes it. +// That's how a contact message of nothing but spaces got through. +// +// Return a small object keyed by the error name. Templates check it with +// control.hasError('blank'), so the key is part of the API: name it for what +// is wrong, not for the validator. +export function notBlank(control: AbstractControl): ValidationErrors | null { + return control.value.trim() === '' ? { blank: true } : null; +} From 08ae613e466d190d8ce8b6e54dcc06ef6cfeb45a Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:21:42 -0500 Subject: [PATCH 44/74] Write lesson 08 with a group validator and FormArray demo --- .../lessons/lesson-08-forms.spec.ts | 2 +- .../lessons/lesson-08-forms.ts | 318 ++++++++++++++++++ src/app/thoughts-content/lessons/lessons.ts | 1 + src/app/thoughts-content/thoughts-bodies.ts | 3 + src/app/thoughts-content/thoughts-data.ts | 9 + 5 files changed, 332 insertions(+), 1 deletion(-) create mode 100644 src/app/thoughts-content/lessons/lesson-08-forms.ts diff --git a/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts b/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts index 5107238..9ab7c4e 100644 --- a/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts +++ b/src/app/thoughts-content/lessons/lesson-08-forms.spec.ts @@ -58,7 +58,7 @@ describe('Lesson08Forms', () => { await click('#demo-add-link'); expect(rows()).toBe(2); - await click('.demo-link-row:last-child .demo-remove-link'); + await click('.demo-link-row:last-of-type .demo-remove-link'); expect(rows()).toBe(1); }); diff --git a/src/app/thoughts-content/lessons/lesson-08-forms.ts b/src/app/thoughts-content/lessons/lesson-08-forms.ts new file mode 100644 index 0000000..4800ece --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-08-forms.ts @@ -0,0 +1,318 @@ +import { Component, inject } from '@angular/core'; +import { FormBuilder, ReactiveFormsModule, ValidationErrors, ValidatorFn, Validators } from '@angular/forms'; +import { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; + +/** + * [ng-08 forms] A cross-field rule belongs on the group, not on either field: + * "confirm must equal password" is about both, and a validator on confirm + * alone wouldn't re-run when the password changes. + */ +const matchingPasswords: ValidatorFn = (group): ValidationErrors | null => { + const { password, confirm } = group.value as { password: string; confirm: string }; + return confirm && password !== confirm ? { mismatch: true } : null; +}; + +@Component({ + selector: 'app-lesson-08-forms', + imports: [Lesson, LessonDemo, CodeBlock, Callout, InterviewQuestions, ReactiveFormsModule], + template: ` + +

    Simple

    +

    + Angular has two form APIs. Template-driven forms put + ngModel on inputs and let the template build the model. They're fine for a + search box. Reactive forms build the model in TypeScript, as a tree of + FormGroup, FormControl and FormArray, and bind + inputs to it with formControlName. Most production apps use reactive forms: + the logic is testable without a DOM, and the types follow the model. +

    +

    + This site's contact form is a reactive form. Writing this lesson, I found three things + wrong with it: +

    +
      +
    • a message of only spaces passed Validators.required
    • +
    • Send was disabled with no explanation
    • +
    • its errors weren't connected to their fields for screen readers
    • +
    + + +

    Intermediate

    +

    + A validator is a function from a control to an errors object or + null. notBlank is three lines and now guards the name and + message. Cross-field rules go on the group. A + FormArray holds a list whose length changes at runtime. +

    + +
    +
    + + +
    +
    + + +
    + @if (showMismatch()) { +

    Passwords don't match.

    + } + +
    +

    + status: {{ form.status }} · dirty: {{ form.dirty }} · touched: + {{ form.touched }} +

    +
    {{ formValue() }}
    +
    + + +

    + Typed forms. Since v14, the form's types are inferred from its initial + values. fb.nonNullable makes reset() go back to the initial value + instead of null, so form.value.name is string, not + string | null. +

    +

    + Accessible errors. Show an error once the field is touched, not while + someone is still typing their first character. Tie it to the input with + aria-invalid and aria-describedby. Keep the submit button + enabled: on an invalid submit, markAllAsTouched() shows every error, then + focus moves to the first one. Put the result message in a live region that's always in + the DOM. +

    + +

    Expert

    +

    + Async validators run after the sync ones pass and put the control in + PENDING while they wait. They're the place for a "username taken" check. Pass + them separately, and set updateOn: 'blur' or debounce inside them, or every + keystroke is a request. +

    + +

    + ControlValueAccessor is how a custom component (a star + rating, a date picker) becomes a form control. It implements four methods, and then + formControlName works on it like on an input. +

    + + +

    + Signal Forms ship in Angular 21 as experimental + (@angular/forms/signals). The model is a plain signal you own, + form() wraps it in a tree of fields, and validation is a schema function. + Each field's value, validity and errors are signals, so no valueChanges + bridging is needed. I'd use it on a greenfield form and know reactive forms for every + existing codebase. Interviews will ask about both. +

    +
    + + +

    Pitfalls

    + +

    + Validators.required accepts whitespace. Add a + notBlank validator for text that has to say something. +

    +
    + +

    + Disabled controls are left out of form.value. Use + getRawValue() when you need everything. +

    +
    + +

    + setValue vs patchValue. + setValue throws unless you pass every field. patchValue takes a + subset, and silently ignores keys that don't exist, typos included. +

    +
    + +

    + Mixing ngModel with formControlName on one + input. It's deprecated and the two models fight. Pick one API per form. +

    +
    + +

    Interview questions

    + +
    + `, + styles: ` + .demo-error { + margin: 0 0 8px; + font-size: 13px; + color: #ff6b6b; + } + .demo-links { + margin: 8px 0; + border: 1px dashed var(--border-primary, rgba(255, 255, 255, 0.3)); + border-radius: 8px; + } + .demo-value { + margin: 8px 0 0; + font-size: 12px; + white-space: pre-wrap; + } + `, +}) +export class Lesson08Forms { + private readonly fb = inject(FormBuilder); + + protected readonly form = this.fb.nonNullable.group( + { + password: ['', [Validators.required, Validators.minLength(8)]], + confirm: ['', Validators.required], + links: this.fb.nonNullable.array([this.link()]), + }, + { validators: matchingPasswords }, + ); + + protected showMismatch(): boolean { + return this.form.hasError('mismatch') && this.form.controls.confirm.touched; + } + + protected addLink(): void { + this.form.controls.links.push(this.link()); + } + + protected formValue(): string { + return JSON.stringify(this.form.getRawValue(), null, 2); + } + + private link() { + return this.fb.nonNullable.control('', Validators.pattern(/^(https:\/\/\S+)?$/)); + } + + protected readonly snippets = { + contact: `readonly form = this.fb.nonNullable.group({ + name: ['', notBlank], + email: ['', [Validators.required, Validators.email]], + message: ['', notBlank], +}); + +onSubmit() { + if (this.form.invalid) { + this.form.markAllAsTouched(); // show every error at once + // ...then focus the first invalid field + return; + } + // send +} + +`, + demo: `const matchingPasswords: ValidatorFn = (group) => { + const { password, confirm } = group.value; + return confirm && password !== confirm ? { mismatch: true } : null; +}; + +form = this.fb.nonNullable.group( + { + password: ['', [Validators.required, Validators.minLength(8)]], + confirm: ['', Validators.required], + links: this.fb.nonNullable.array([this.link()]), + }, + { validators: matchingPasswords }, // on the group: it reads both fields +); + +addLink() { this.form.controls.links.push(this.link()); } + +
    + @for (link of form.controls.links.controls; track link; let i = $index) { + + } +
    `, + async: `const usernameFree = (users: UserService): AsyncValidatorFn => (control) => + timer(300).pipe( // debounce: resubscribed per value + switchMap(() => users.exists(control.value)), + map((taken) => (taken ? { taken: true } : null)), + ); + +username = new FormControl('', { + validators: [Validators.required], + asyncValidators: [usernameFree(inject(UserService))], + updateOn: 'blur', +});`, + cva: `@Component({ + selector: 'app-star-rating', + providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: StarRating, multi: true }], + ... +}) +export class StarRating implements ControlValueAccessor { + writeValue(value: number) { ... } // form → component + registerOnChange(fn: (value: number) => void) { this.onChange = fn; } // component → form + registerOnTouched(fn: () => void) { this.onTouched = fn; } + setDisabledState(disabled: boolean) { ... } +}`, + signalForms: `import { form, required, email, FormField } from '@angular/forms/signals'; + +readonly model = signal({ name: '', email: '' }); +readonly contact = form(this.model, (path) => { + required(path.name); + email(path.email); +}); + +contact.email().valid(); // a signal +contact.email().errors(); // a signal + +`, + }; + + protected readonly interview = [ + { + q: 'Reactive or template-driven forms?', + a: 'Template-driven forms build the model from ngModel in the template: quick for simple cases, but the logic is spread through HTML and hard to unit test. Reactive forms define the model in TypeScript, which makes them strongly typed, testable without a DOM, and better for dynamic fields, cross-field validation and complex flows. I default to reactive. In Angular 21, Signal Forms are an experimental third option built on signals.', + }, + { + q: 'How do you write a custom validator, and a cross-field one?', + a: 'A ValidatorFn takes a control and returns null when valid or an errors object like { blank: true }. For rules involving several fields, such as password confirmation or a date range, put the validator on the FormGroup so it sees every value and re-runs when any of them changes. Read it with group.hasError().', + }, + { + q: 'What does a ControlValueAccessor do?', + a: 'It is the bridge between a form control and a component or element. writeValue pushes the model into the view, registerOnChange and registerOnTouched give the component callbacks to report changes back, and setDisabledState handles disabling. Provide it with NG_VALUE_ACCESSOR as a multi provider, and formControlName and ngModel work on your component.', + }, + { + q: 'How do async validators work?', + a: 'They return an Observable or Promise of errors or null, and run only after the sync validators pass. While they run, the control status is PENDING. To avoid a request per keystroke, use updateOn: blur or debounce inside the validator with timer() and switchMap, since the validator is resubscribed on each value change.', + }, + { + q: 'How do you make a form accessible?', + a: 'Every input has a real label. Errors show once the field is touched, and are linked with aria-invalid and aria-describedby. The submit button stays enabled, and an invalid submit marks everything touched and focuses the first invalid field. Results go into a live region that already exists in the DOM. Use autocomplete attributes for personal data.', + }, + { + q: 'What changed with typed forms?', + a: 'Since Angular 14, FormControl, FormGroup and FormArray are generic and infer their types from initial values, so form.value.email is typed and typos are compile errors. nonNullable controls reset to their initial value instead of null, which removes string | null everywhere. UntypedFormGroup exists for migrating old code.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index 9885402..200f7a7 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -18,4 +18,5 @@ export const LESSON_PAGES: Record Promise>> = { 'angular-05-dependency-injection': () => import('./lesson-05-di').then((m) => m.Lesson05Di), 'angular-06-rxjs': () => import('./lesson-06-rxjs').then((m) => m.Lesson06Rxjs), 'angular-07-routing': () => import('./lesson-07-routing').then((m) => m.Lesson07Routing), + 'angular-08-forms': () => import('./lesson-08-forms').then((m) => m.Lesson08Forms), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 948c46e..7992988 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -265,4 +265,7 @@ The second one was a real gap. The Projects app showed its error state on the fi 'angular-07-routing': `Every thought has tags, and until now they were decoration. I wanted each tag to be a page: /thoughts/tag/angular-guide as a reading list for this series, prerendered like everything else under /thoughts. Wiring that up showed how much of the routing had been done by hand. The cards were divs with click handlers, so there were no real links to put the tags inside. The reader pulled its slug out of ActivatedRoute through an Observable, when the router could just hand it over as an input. And there was no wildcard route at all, so a mistyped URL failed the first navigation outright. The playground below matches URLs against this site's actual route table.`, + 'angular-08-forms': `I opened the contact form to use as this lesson's example and found three things wrong with it. A message of nothing but spaces passed validation, because Validators.required only rejects an empty string. Send stayed greyed out until everything was valid, and nothing said why. And the error messages were just text sitting near the fields, with nothing telling a screen reader which field they belonged to. + +All three are fixed now. Send stays enabled; pressing it shows every problem and puts focus on the first one. The demo below covers what the contact form doesn't need: a rule that spans two fields, and a list of fields that grows and shrinks.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index f509e55..db542e0 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -251,4 +251,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'routing', 'angular'], relatedApp: 'readme', }, + { + slug: 'angular-08-forms', + title: 'Angular 08: Forms', + date: '2026-11-21', + summary: + 'Reactive forms, custom and cross-field validators, FormArray, accessible errors, ControlValueAccessor and the new Signal Forms. Built while fixing a contact form that accepted blank messages and never said what was wrong.', + tags: ['angular-guide', 'forms', 'angular'], + relatedApp: 'contact', + }, ]; From 6aa6f073ffd79a6b920e5a0f9a72c8ce6645f3fa Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:21:49 -0500 Subject: [PATCH 45/74] Bump to 1.4.7 with the lesson 08 changelog entry --- CHANGELOG.md | 8 ++++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b64e434..212c329 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.7 + +- **fix: the contact form accepted blank messages.** `Validators.required` only rejects an empty string, so a name or message of nothing but spaces got through. Both now use a small `notBlank` validator in `shared/validators.ts` +- **Send explains instead of greying out.** The button used to stay disabled until the form was valid, which can't be focused and says nothing about what's wrong. It's now enabled, except while a message is sending, so it can't double-submit. Pressing it on an invalid form shows every error and moves focus to the first field that needs fixing +- **Errors are tied to their fields.** Each error message has an id, and its input gets `aria-invalid` and `aria-describedby` while the error shows. The sending, sent and failed messages now live in one `role="status"` region that's always in the DOM, so they're announced. Name and email have `autocomplete` hints +- **Angular guide, lesson 08: forms** (`/thoughts/angular-08-forms`). The live demo is a password pair checked by a group-level validator, plus a `FormArray` of links you can add and remove, with the form's status and raw value shown as you type. The lesson covers async validators, `ControlValueAccessor`, and Angular 21's experimental Signal Forms, checked against the installed `@angular/forms` 21.2 +- Initial bundle 391.72 kB → 392.09 kB, the lesson's metadata. Forms code stays in lazy chunks + ## 2026-11-21 - version 1.4.6 - **Every tag has its own page**: `/thoughts/tag/`, prerendered with its own title and canonical URL, and every tag pill in the list and the reader links to it. `/thoughts/tag/angular-guide` is now the reading list for this series. It's a path param rather than `?tag=` on purpose: prerendering writes one file per path, so a query-param page would be served the unfiltered list and then change under the reader during hydration. Prerendered routes went from 27 to 74 diff --git a/package-lock.json b/package-lock.json index 511a96a..97c9914 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.6", + "version": "1.4.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.6", + "version": "1.4.7", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index 5990c57..ba9469d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.6", + "version": "1.4.7", "scripts": { "ng": "ng", "start": "ng serve", From c7ea17f3b2b338d5d021eae45eb4f594e12f3cfb Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 10:23:28 -0500 Subject: [PATCH 46/74] Add a failing fitness spec for OnPush everywhere and lesson 09 --- src/app/architecture.spec.ts | 22 ++++++- .../lesson-09-change-detection.spec.ts | 58 +++++++++++++++++++ 2 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 src/app/thoughts-content/lessons/lesson-09-change-detection.spec.ts diff --git a/src/app/architecture.spec.ts b/src/app/architecture.spec.ts index 066fc78..48691dc 100644 --- a/src/app/architecture.spec.ts +++ b/src/app/architecture.spec.ts @@ -9,7 +9,7 @@ import { join, relative, resolve, dirname, sep } from 'node:path'; * feature folder is quietly a dependency of the whole app. These tests make the * convention executable: break the rule and CI goes red with the file name. * - * The layering this repo uses (see docs/angular-guide/01-project-structure.md): + * The layering this repo uses (lesson 01, /thoughts/angular-01-project-structure): * * shell app.ts, menu-bar/, dock/, desktop/, window-manager/, ... * shared/ services and building blocks anyone may use @@ -70,4 +70,24 @@ describe('[ng-01] architecture', () => { .map((file) => relative(APP_ROOT, file)); expect(withNgModule).toEqual([]); }); + + // [ng-09 change detection] OnPush everywhere, unless a component says + // otherwise out loud. The check is per decorator, not per file, because a + // file can declare several components. Eager (the new name for Default) is + // allowed only when written explicitly, so it is always a visible decision + // rather than a forgotten line. + it('every component sets OnPush, or opts into Eager explicitly', () => { + const decorators = files.flatMap((file) => + readFileSync(file, 'utf-8') + .split('@Component(') + .slice(1) + .map((rest) => ({ file, decorator: rest.slice(0, rest.indexOf('export class')) })), + ); + const missing = decorators + .filter(({ decorator }) => !/changeDetection:\s*ChangeDetectionStrategy\.(OnPush|Eager)\b/.test(decorator)) + .map(({ file, decorator }) => `${relative(APP_ROOT, file)} (${/selector:\s*'([^']+)'/.exec(decorator)?.[1]})`); + + expect(decorators.length).toBeGreaterThan(30); + expect(missing).toEqual([]); + }); }); diff --git a/src/app/thoughts-content/lessons/lesson-09-change-detection.spec.ts b/src/app/thoughts-content/lessons/lesson-09-change-detection.spec.ts new file mode 100644 index 0000000..3088b98 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-09-change-detection.spec.ts @@ -0,0 +1,58 @@ +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 { Lesson09ChangeDetection } from './lesson-09-change-detection'; + +expect.extend(axeMatchers); + +describe('Lesson09ChangeDetection', () => { + let fixture: ComponentFixture; + let el: HTMLElement; + + const visits = (selector: string) => el.querySelector(`${selector} .cd-visits`)?.textContent?.trim(); + const click = async (selector: string) => { + el.querySelector(selector)!.click(); + await fixture.whenStable(); + }; + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson09ChangeDetection] }).compileComponents(); + fixture = TestBed.createComponent(Lesson09ChangeDetection); + await fixture.whenStable(); + el = fixture.nativeElement as HTMLElement; + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-09-change-detection']).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('mutating an input in place updates the Eager child but leaves the OnPush child stale', async () => { + await click('#cd-mutate'); + expect(visits('#cd-eager')).toBe('1'); + expect(visits('#cd-onpush')).toBe('0'); + }); + + it('replacing the input with a new object updates both', async () => { + await click('#cd-mutate'); + await click('#cd-replace'); + expect(visits('#cd-eager')).toBe('2'); + expect(visits('#cd-onpush')).toBe('2'); + }); + + it('a signal updates the OnPush child with no input change at all', async () => { + await click('#cd-signal'); + expect(el.querySelector('#cd-onpush .cd-likes')?.textContent?.trim()).toBe('1'); + }); + + it('has no axe violations', async () => { + expect(await axe(el)).toHaveNoViolations(); + }); +}); From cc4515d5d20093e8f1e4ffba44dd8b82b5a7d9c3 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:12:59 -0500 Subject: [PATCH 47/74] Find components with the TypeScript parser in the OnPush fitness test Splitting files on '@Component(' also matched the code samples the lessons print, so five strings counted as components. The parser only sees real class decorators, and a second test pins that. --- src/app/architecture.spec.ts | 42 +++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/src/app/architecture.spec.ts b/src/app/architecture.spec.ts index 48691dc..6253df9 100644 --- a/src/app/architecture.spec.ts +++ b/src/app/architecture.spec.ts @@ -1,5 +1,6 @@ import { readdirSync, readFileSync, statSync } from 'node:fs'; import { join, relative, resolve, dirname, sep } from 'node:path'; +import * as ts from 'typescript'; /** * [ng-01 structure] Architecture fitness tests. @@ -37,6 +38,28 @@ function staticRelativeImports(file: string): string[] { return specifiers.map((match) => resolve(dirname(file), match[1])); } +/** + * Real `@Component(...)` decorators on classes, read with the TypeScript + * parser. A text search also matches the code samples the lessons print. + */ +function componentDecorators(file: string): { file: string; className: string; metadata: string }[] { + const source = ts.createSourceFile(file, readFileSync(file, 'utf-8'), ts.ScriptTarget.Latest, true); + const found: { file: string; className: string; metadata: string }[] = []; + const visit = (node: ts.Node) => { + if (ts.isClassDeclaration(node)) { + for (const decorator of ts.getDecorators(node) ?? []) { + const call = decorator.expression; + if (ts.isCallExpression(call) && ts.isIdentifier(call.expression) && call.expression.text === 'Component') { + found.push({ file, className: node.name?.text ?? '(anonymous)', metadata: call.arguments[0]?.getText(source) ?? '' }); + } + } + } + ts.forEachChild(node, visit); + }; + visit(source); + return found; +} + const isInside = (file: string, folder: string) => relative(join(APP_ROOT, folder), file).split(sep)[0] !== '..'; @@ -77,17 +100,20 @@ describe('[ng-01] architecture', () => { // allowed only when written explicitly, so it is always a visible decision // rather than a forgotten line. it('every component sets OnPush, or opts into Eager explicitly', () => { - const decorators = files.flatMap((file) => - readFileSync(file, 'utf-8') - .split('@Component(') - .slice(1) - .map((rest) => ({ file, decorator: rest.slice(0, rest.indexOf('export class')) })), - ); + const decorators = files.flatMap(componentDecorators); const missing = decorators - .filter(({ decorator }) => !/changeDetection:\s*ChangeDetectionStrategy\.(OnPush|Eager)\b/.test(decorator)) - .map(({ file, decorator }) => `${relative(APP_ROOT, file)} (${/selector:\s*'([^']+)'/.exec(decorator)?.[1]})`); + .filter(({ metadata }) => !/changeDetection:\s*ChangeDetectionStrategy\.(OnPush|Eager)\b/.test(metadata)) + .map(({ file, className }) => `${relative(APP_ROOT, file)} (${className})`); expect(decorators.length).toBeGreaterThan(30); expect(missing).toEqual([]); }); + + it('the decorator finder skips @Component( inside code-sample strings', () => { + const lesson02 = join(APP_ROOT, 'thoughts-content/lessons/lesson-02-components.ts'); + expect(componentDecorators(lesson02).map(({ className }) => className)).toEqual([ + 'DemoBadge', + 'Lesson02Components', + ]); + }); }); From e30bbbabebfe01451b5ed9bf290dfbccc6852106 Mon Sep 17 00:00:00 2001 From: gpbsumido Date: Sat, 21 Nov 2026 11:12:59 -0500 Subject: [PATCH 48/74] Switch every component to OnPush All 35 components were checked on every pass. None of them holds state that changes outside signals or template events, so the switch needs no other code changes. The contact form's reset gets a comment: it renders only because a signal write sits next to it. --- src/app/app.ts | 3 ++- src/app/apps/about-app.ts | 3 ++- src/app/apps/contact-app.ts | 6 +++++- src/app/apps/finder/finder-app.ts | 10 +++++++++- src/app/apps/placeholder-app.ts | 3 ++- src/app/apps/projects-app.ts | 10 +++++++++- src/app/apps/readme-app.ts | 3 ++- src/app/apps/settings/system-preferences.ts | 3 ++- src/app/apps/terminal-app.ts | 3 ++- src/app/context-menu/context-menu.ts | 11 ++++++++++- src/app/desktop-icons/desktop-icon.ts | 3 ++- src/app/desktop-icons/desktop-icons.ts | 3 ++- src/app/desktop/desktop.ts | 3 ++- src/app/dock/dock.ts | 3 ++- src/app/menu-bar/menu-bar.ts | 2 ++ src/app/spotlight/spotlight.ts | 3 ++- src/app/thoughts-content/lessons/callout.ts | 3 ++- src/app/thoughts-content/lessons/code-block.ts | 3 ++- .../thoughts-content/lessons/interview-questions.ts | 3 ++- .../thoughts-content/lessons/lesson-01-structure.ts | 3 ++- .../thoughts-content/lessons/lesson-02-components.ts | 4 +++- .../thoughts-content/lessons/lesson-03-templates.ts | 3 ++- src/app/thoughts-content/lessons/lesson-04-signals.ts | 3 ++- src/app/thoughts-content/lessons/lesson-05-di.ts | 5 ++++- src/app/thoughts-content/lessons/lesson-06-rxjs.ts | 3 ++- src/app/thoughts-content/lessons/lesson-07-routing.ts | 3 ++- src/app/thoughts-content/lessons/lesson-08-forms.ts | 3 ++- src/app/thoughts-content/lessons/lesson-demo.ts | 3 ++- src/app/thoughts-content/lessons/lesson.ts | 3 ++- src/app/thoughts-content/thought-detail.ts | 3 ++- src/app/thoughts-content/thoughts-list.ts | 3 ++- src/app/window-manager/window.ts | 2 ++ 32 files changed, 92 insertions(+), 30 deletions(-) diff --git a/src/app/app.ts b/src/app/app.ts index aa9a9ed..16092c2 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,5 +1,5 @@ import { NgComponentOutlet } from '@angular/common'; -import { Component, effect, inject, viewChild } from '@angular/core'; +import { ChangeDetectionStrategy, Component, effect, inject, viewChild } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; import { NavigationEnd, Router, RouterOutlet } from '@angular/router'; import { filter, map } from 'rxjs'; @@ -19,6 +19,7 @@ import { WindowManagerService } from './window-manager/window-manager.service'; @Component({ selector: 'app-root', + changeDetection: ChangeDetectionStrategy.OnPush, imports: [ RouterOutlet, Desktop, diff --git a/src/app/apps/about-app.ts b/src/app/apps/about-app.ts index cf52d40..b62d7f8 100644 --- a/src/app/apps/about-app.ts +++ b/src/app/apps/about-app.ts @@ -1,9 +1,10 @@ -import { Component, output, signal } from '@angular/core'; +import { ChangeDetectionStrategy, Component, output, signal } from '@angular/core'; export type AboutTab = 'overview' | 'skills' | 'experience'; @Component({ selector: 'app-about', + changeDetection: ChangeDetectionStrategy.OnPush, template: `
    👤
    diff --git a/src/app/apps/contact-app.ts b/src/app/apps/contact-app.ts index 2a4142b..e906010 100644 --- a/src/app/apps/contact-app.ts +++ b/src/app/apps/contact-app.ts @@ -1,4 +1,4 @@ -import { Component, ElementRef, inject, signal } from '@angular/core'; +import { ChangeDetectionStrategy, Component, ElementRef, inject, signal } from '@angular/core'; import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; import { notBlank } from '../shared/validators'; @@ -6,6 +6,7 @@ type SubmissionStatus = 'idle' | 'pending' | 'success' | 'error'; @Component({ selector: 'app-contact', + changeDetection: ChangeDetectionStrategy.OnPush, imports: [ReactiveFormsModule], template: `
    @@ -249,6 +250,9 @@ export class ContactApp { this.submissionStatus.set('pending'); // Simulate async submission + // [ng-09 change detection] form.reset() changes plain control state, + // which marks nothing for check. It renders because the signal write next + // to it does. Drop that write and the old errors stay on screen. setTimeout(() => { this.submissionStatus.set('success'); this.form.reset(); diff --git a/src/app/apps/finder/finder-app.ts b/src/app/apps/finder/finder-app.ts index 03aac41..69081a0 100644 --- a/src/app/apps/finder/finder-app.ts +++ b/src/app/apps/finder/finder-app.ts @@ -1,8 +1,16 @@ -import { Component, computed, inject, output, signal } from '@angular/core'; +import { + ChangeDetectionStrategy, + Component, + computed, + inject, + output, + signal, +} from '@angular/core'; import { FileSystemService, FileEntry } from './file-system.service'; @Component({ selector: 'app-finder', + changeDetection: ChangeDetectionStrategy.OnPush, template: `
    diff --git a/src/app/apps/placeholder-app.ts b/src/app/apps/placeholder-app.ts index 4645b27..2443f39 100644 --- a/src/app/apps/placeholder-app.ts +++ b/src/app/apps/placeholder-app.ts @@ -1,7 +1,8 @@ -import { Component, input } from '@angular/core'; +import { ChangeDetectionStrategy, Component, input } from '@angular/core'; @Component({ selector: 'app-placeholder', + changeDetection: ChangeDetectionStrategy.OnPush, template: `
    {{ icon() }} diff --git a/src/app/apps/projects-app.ts b/src/app/apps/projects-app.ts index 6f9a4ba..0f93875 100644 --- a/src/app/apps/projects-app.ts +++ b/src/app/apps/projects-app.ts @@ -1,4 +1,11 @@ -import { Component, computed, inject, output, signal } from '@angular/core'; +import { + ChangeDetectionStrategy, + Component, + computed, + inject, + output, + signal, +} from '@angular/core'; import { ProjectsService } from './projects.service'; export interface GitHubRepo { @@ -12,6 +19,7 @@ export interface GitHubRepo { @Component({ selector: 'app-projects', + changeDetection: ChangeDetectionStrategy.OnPush, template: `
    diff --git a/src/app/apps/readme-app.ts b/src/app/apps/readme-app.ts index 77a96b0..9337a1e 100644 --- a/src/app/apps/readme-app.ts +++ b/src/app/apps/readme-app.ts @@ -1,8 +1,9 @@ -import { Component, inject } from '@angular/core'; +import { ChangeDetectionStrategy, Component, inject } from '@angular/core'; import { AppLauncherService } from '../shared/app-launcher.service'; @Component({ selector: 'app-readme', + changeDetection: ChangeDetectionStrategy.OnPush, template: `

    README.md

    diff --git a/src/app/apps/settings/system-preferences.ts b/src/app/apps/settings/system-preferences.ts index 5253700..850e10f 100644 --- a/src/app/apps/settings/system-preferences.ts +++ b/src/app/apps/settings/system-preferences.ts @@ -1,4 +1,4 @@ -import { Component, inject, signal } from '@angular/core'; +import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core'; import { SettingsService } from '../../shared/settings/settings.service'; type Pane = 'appearance' | 'dock' | 'general'; @@ -10,6 +10,7 @@ interface SidebarItem { @Component({ selector: 'app-system-preferences', + changeDetection: ChangeDetectionStrategy.OnPush, template: `