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", 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/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/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([]); + }); +}); 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'; 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.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/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.', + }, + ]; +} 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.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(); + }); +}); 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', + }, ]; 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));