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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

All notable changes to this project will be documented in this file.

## 2026-11-21 - version 1.4.11

- **fix: prerendered pages showed the time the site was built.** The menu bar clock rendered on the server, so every Thoughts page shipped a frozen build-time clock until the JavaScript loaded. The clock now renders empty on the server and starts in `afterNextRender`, which only runs in the browser
- **The menu bar hydrates.** It was marked `ngSkipHydration` to hide that server/browser difference, so the browser threw away the server's HTML for the whole bar and drew it again. With the difference gone, the attribute is gone. The interval also no longer starts from inside an `effect` with no signal dependencies
- **A spec renders the menu bar on the real server platform** (`menu-bar.server.spec.ts`, through `renderApplication`). TestBed runs browser-only hooks, so it can't show what the server sends
- **Angular guide, lesson 12: SSR and hydration** (`/thoughts/angular-12-ssr`). The live demo says whether the page you're reading was prerendered or rendered in your browser: the server writes its render time into `TransferState` and the browser reads it back. The lesson covers render modes per route, hydration, browser-only code, the HTTP transfer cache, event replay, incremental hydration and `PendingTasks`
- I formatted the demo's time with `DatePipe` first, and the initial bundle went to 407.07 kB, over the 400 kB budget. It's the lesson 03 trap again; `Intl.DateTimeFormat` brought it back to 395.26 kB

## 2026-11-21 - version 1.4.10

- **fix: CI's typecheck checked zero files.** It ran `npx tsc --noEmit` against the root `tsconfig.json`, which has `"files": []` and only project references, so plain `tsc` compiled nothing and passed. It now typechecks `tsconfig.app.json` and `tsconfig.spec.json`
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "angular-paul",
"version": "1.4.10",
"version": "1.4.11",
"scripts": {
"ng": "ng",
"start": "ng serve",
Expand Down
38 changes: 38 additions & 0 deletions src/app/menu-bar/menu-bar.server.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { bootstrapApplication, BootstrapContext } from '@angular/platform-browser';
import { provideServerRendering, renderApplication } from '@angular/platform-server';
import { MenuBar } from './menu-bar';

// [ng-12 ssr] A server render through the real platform-server, not TestBed.
// TestBed runs every browser-only hook, so it can't show what the server emits:
// this is the HTML a visitor receives before any JavaScript has run.
async function renderMenuBarOnServer(): Promise<string> {
const bootstrap = (context: BootstrapContext) =>
bootstrapApplication(
MenuBar,
{ providers: [provideZonelessChangeDetection(), provideServerRendering()] },
context,
);
return renderApplication(bootstrap, {
document: '<html><head></head><body><app-menu-bar></app-menu-bar></body></html>',
url: '/',
});
}

describe('MenuBar server render', () => {
it('emits no clock time, so a prerendered page never shows the build time', async () => {
const html = await renderMenuBarOnServer();

const clock = html.match(/<span[^>]*class="menu-bar-clock"[^>]*>([^<]*)<\/span>/);
expect(clock).not.toBeNull();
expect(clock![1].trim(), 'server-rendered clock text').toBe('');
});

it('lets the menu bar hydrate instead of being thrown away and re-rendered', async () => {
const html = await renderMenuBarOnServer();

const host = html.match(/<app-menu-bar[^>]*>/);
expect(host).not.toBeNull();
expect(host![0].toLowerCase()).not.toContain('ngskiphydration');
});
});
30 changes: 16 additions & 14 deletions src/app/menu-bar/menu-bar.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import { DOCUMENT } from '@angular/common';
import {
afterNextRender,
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
effect,
ElementRef,
inject,
output,
PLATFORM_ID,
signal,
} from '@angular/core';
import { SettingsService } from '../shared/settings/settings.service';
Expand All @@ -19,34 +18,37 @@ import { MenuBarItem, MenuBarService } from './menu-bar.service';
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './menu-bar.html',
styleUrl: './menu-bar.scss',
// The live clock differs between server render and client bootstrap; skip
// hydration for this subtree so it re-renders cleanly in the browser.
host: { ngSkipHydration: 'true' },
})
export class MenuBar {
private readonly menuBarService = inject(MenuBarService);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly document = inject(DOCUMENT);
private readonly destroyRef = inject(DestroyRef);
private readonly platformId = inject(PLATFORM_ID);
private readonly settings = inject(SettingsService);

readonly menus = this.menuBarService.menus;
readonly activeAppName = this.menuBarService.activeAppName;
private readonly now = signal(new Date());
readonly clock = computed(() => this.formatTime(this.now()));
// [ng-12 ssr] null until the browser takes over. A prerendered page is built
// once and served for days, so any time the server wrote would be stale, and
// a server/client difference is what used to need ngSkipHydration here.
private readonly now = signal<Date | null>(null);
readonly clock = computed(() => {
const now = this.now();
return now ? this.formatTime(now) : '';
});
readonly openMenuId = signal<string | null>(null);
readonly spotlightRequested = output<void>();

private intervalId: ReturnType<typeof setInterval> | null = null;
private outsideListener: (() => void) | null = null;

constructor() {
effect(() => {
if (!isPlatformBrowser(this.platformId)) return;
this.intervalId = setInterval(() => {
this.now.set(new Date());
}, 1000);
// [ng-12 ssr] afterNextRender never runs on the server, so it replaces the
// PLATFORM_ID check. It runs after hydration has claimed the server DOM, so
// filling the clock in here can't cause a mismatch.
afterNextRender(() => {
this.now.set(new Date());
this.intervalId = setInterval(() => this.now.set(new Date()), 1000);
});

this.destroyRef.onDestroy(() => {
Expand Down
72 changes: 72 additions & 0 deletions src/app/thoughts-content/lessons/lesson-12-ssr.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { PLATFORM_ID, TransferState } from '@angular/core';
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 { Lesson12Ssr, RENDERED_AT } from './lesson-12-ssr';

expect.extend(axeMatchers);

describe('Lesson12Ssr', () => {
const origin = (fixture: ComponentFixture<Lesson12Ssr>) =>
(fixture.nativeElement as HTMLElement)
.querySelector('#demo-render-origin')
?.textContent?.trim();

async function render(): Promise<ComponentFixture<Lesson12Ssr>> {
const fixture = TestBed.createComponent(Lesson12Ssr);
await fixture.whenStable();
return fixture;
}

beforeEach(async () => {
await TestBed.configureTestingModule({ imports: [Lesson12Ssr] }).compileComponents();
});

it('is registered as the lesson page for its thought', () => {
expect(LESSON_PAGES['angular-12-ssr']).toBeDefined();
});

it('teaches at three levels, then pitfalls and interview questions', async () => {
const fixture = await render();
const headings = [...(fixture.nativeElement as HTMLElement).querySelectorAll('h2')].map((h) =>
h.textContent?.trim(),
);
expect(headings).toEqual(
expect.arrayContaining([
'Simple',
'Intermediate',
'Expert',
'Pitfalls',
'Interview questions',
]),
);
});

it('stamps the render time into TransferState when it renders on the server', async () => {
TestBed.overrideProvider(PLATFORM_ID, { useValue: 'server' });
await render();

expect(TestBed.inject(TransferState).get(RENDERED_AT, null)).toMatch(/^\d{4}-\d{2}-\d{2}T/);
});

it('reads the server stamp back in the browser instead of recomputing it', async () => {
TestBed.inject(TransferState).set(RENDERED_AT, '2026-11-21T09:05:00.000Z');
const fixture = await render();

expect(origin(fixture)).toContain('Prerendered on the server');
// Intl puts a narrow no-break space before AM on current ICU, so match any space.
expect(origin(fixture)).toMatch(/Nov 21, 2026, 9:05:00\sAM UTC/);
});

it('says so when there was no server render, as after a client-side navigation', async () => {
const fixture = await render();

expect(origin(fixture)).toContain('Rendered in your browser');
});

it('has no axe violations', async () => {
const fixture = await render();
expect(await axe(fixture.nativeElement)).toHaveNoViolations();
});
});
Loading
Loading