Skip to content

Commit e37306b

Browse files
committed
fix(docs): give each page its own description and canonical URL, and stop layout shifts
Every page shipped the homepage description, og:description and og:url, and none had a canonical link, because Analog's markdown routes drop the frontmatter description. The page-meta map now carries each page's description and noIndex, and the title strategy sets the description, canonical link, og:url and social titles on every navigation. Pages with `noIndex` get `robots: noindex`, so the kitchen sink stays out of search. The live site answered every link and sitemap URL with a 307 to its trailing-slash form, where the client briefly rendered the homepage before the page. Workers now serve `/guide` from `guide/index.html` (`html_handling: drop-trailing-slash`). `<ngmd-image>` rendered an empty placeholder that the browser filled in later, so screenshots pushed the page down (desktop CLS about 0.2). It now renders its figure at build time, with the image's width and height read from public/, so the image is in the prerendered HTML and its space is reserved.
1 parent e4ff5c8 commit e37306b

13 files changed

Lines changed: 348 additions & 88 deletions

‎apps/docs/image-sizes.spec.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import {mkdirSync, mkdtempSync, writeFileSync} from 'node:fs';
2+
import {tmpdir} from 'node:os';
3+
import {join} from 'node:path';
4+
import {imageSize, readImageSizes} from './image-sizes';
5+
6+
function png(width: number, height: number): Uint8Array {
7+
const bytes = new Uint8Array(24);
8+
bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
9+
const view = new DataView(bytes.buffer);
10+
view.setUint32(16, width);
11+
view.setUint32(20, height);
12+
return bytes;
13+
}
14+
15+
function jpeg(width: number, height: number): Uint8Array {
16+
// SOI, an APP0 segment, then a baseline start-of-frame segment.
17+
const app0 = [0xff, 0xe0, 0x00, 0x04, 0x00, 0x00];
18+
const sof = [
19+
0xff,
20+
0xc0,
21+
0x00,
22+
0x11,
23+
0x08,
24+
height >> 8,
25+
height & 0xff,
26+
width >> 8,
27+
width & 0xff,
28+
0x03,
29+
];
30+
return new Uint8Array([0xff, 0xd8, ...app0, ...sof, ...new Array(12).fill(0)]);
31+
}
32+
33+
describe('imageSize', () => {
34+
it('reads PNG and JPEG headers', () => {
35+
expect(imageSize(png(1280, 800))).toEqual([1280, 800]);
36+
expect(imageSize(jpeg(640, 480))).toEqual([640, 480]);
37+
});
38+
39+
it('returns undefined for other files', () => {
40+
expect(imageSize(new TextEncoder().encode('<svg></svg>'))).toBeUndefined();
41+
});
42+
});
43+
44+
describe('readImageSizes', () => {
45+
it('keys the sizes by URL path', () => {
46+
const dir = mkdtempSync(join(tmpdir(), 'image-sizes-'));
47+
mkdirSync(join(dir, 'images/panel'), {recursive: true});
48+
writeFileSync(join(dir, 'images/panel/router.png'), png(1280, 800));
49+
writeFileSync(join(dir, 'logo.svg'), '<svg></svg>');
50+
expect(readImageSizes(dir)).toEqual({'/images/panel/router.png': [1280, 800]});
51+
});
52+
});

‎apps/docs/image-sizes.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import {readFileSync, readdirSync, statSync} from 'node:fs';
2+
import {join, relative, sep} from 'node:path';
3+
4+
/**
5+
* Width and height in pixels, by the public URL of the image
6+
* (`/images/panel/router.png`). The build-time `<ngmd-image>` writes them into
7+
* the `width` and `height` of its `<img>`, so the browser reserves the image's
8+
* space before it loads and the page does not shift (CLS).
9+
*/
10+
export type ImageSizes = Record<string, [number, number]>;
11+
12+
/** The sizes of the PNG and JPEG files under `dir`, keyed by their URL path. */
13+
export function readImageSizes(dir: string): ImageSizes {
14+
const sizes: ImageSizes = {};
15+
const walk = (current: string) => {
16+
for (const name of readdirSync(current)) {
17+
const file = join(current, name);
18+
if (statSync(file).isDirectory()) walk(file);
19+
else if (/\.(png|jpe?g)$/i.test(name)) {
20+
const size = imageSize(readFileSync(file));
21+
if (size) sizes['/' + relative(dir, file).split(sep).join('/')] = size;
22+
}
23+
}
24+
};
25+
try {
26+
walk(dir);
27+
} catch {
28+
// no public/ directory
29+
}
30+
return sizes;
31+
}
32+
33+
/** Width and height from a PNG or JPEG header, or `undefined` for anything else. */
34+
export function imageSize(bytes: Uint8Array): [number, number] | undefined {
35+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
36+
// PNG: signature, then the IHDR chunk with width and height.
37+
if (bytes.length >= 24 && view.getUint32(0) === 0x89504e47)
38+
return [view.getUint32(16), view.getUint32(20)];
39+
// JPEG: walk the segments to the first start-of-frame marker.
40+
if (bytes.length >= 4 && view.getUint16(0) === 0xffd8) {
41+
let offset = 2;
42+
while (offset + 9 < bytes.length) {
43+
if (bytes[offset] !== 0xff) return undefined;
44+
const marker = bytes[offset + 1];
45+
const length = view.getUint16(offset + 2);
46+
const isFrame = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
47+
if (isFrame) return [view.getUint16(offset + 7), view.getUint16(offset + 5)];
48+
offset += 2 + length;
49+
}
50+
}
51+
return undefined;
52+
}

‎apps/docs/page-meta.plugin.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
1-
import {statSync} from 'node:fs';
1+
import {readFileSync, statSync} from 'node:fs';
22
import {join} from 'node:path';
33
import type {Plugin, ViteDevServer} from 'vite';
4-
import {gitDate, routeFromPagePath, walkContentFiles, walkPageFiles} from './plugin-utils.ts';
4+
import {
5+
gitDate,
6+
isNoIndex,
7+
parseFrontmatter,
8+
routeFromPagePath,
9+
walkContentFiles,
10+
walkPageFiles,
11+
} from './plugin-utils.ts';
512

613
/**
7-
* Build-time map of page URL → { editUrl, lastUpdated }.
14+
* Build-time map of page URL → { editUrl, lastUpdated, description, noIndex }.
815
*
916
* Walks `src/app/pages` (for `.page.ts` routes) and `src/content/**\/*.md`
1017
* (each markdown file's path under content/ becomes its route, matching the
@@ -14,11 +21,16 @@ import {gitDate, routeFromPagePath, walkContentFiles, walkPageFiles} from './plu
1421
*
1522
* If the file is uncommitted, lastUpdated falls back to its mtime in ISO
1623
* date form so dev iteration still shows something.
24+
*
25+
* A markdown page also carries its frontmatter `description` and `noIndex`,
26+
* which `PageMetaService` writes into the page's head tags.
1727
*/
1828

1929
export interface PageMeta {
2030
editUrl: string;
2131
lastUpdated: string;
32+
description?: string;
33+
noIndex?: boolean;
2234
}
2335

2436
const VIRTUAL_ID = 'virtual:ngmd/page-meta';
@@ -73,10 +85,15 @@ export function pageMetaPlugin(opts: {repoUrl: string; branch?: string; dir?: st
7385
for (const [rel, route] of walkContentFiles(contentDir, root)) {
7486
const date = gitDate(rel, root);
7587
if (!date) continue;
88+
const {attributes} = parseFrontmatter(readFileSync(join(root, rel), 'utf8'));
7689
// .md edit URL wins when present (more useful for prose pages)
7790
map[route] = {
7891
editUrl: `${opts.repoUrl}/edit/${branch}/${dir}${rel}`,
7992
lastUpdated: date,
93+
...(typeof attributes['description'] === 'string'
94+
? {description: attributes['description']}
95+
: {}),
96+
...(isNoIndex(attributes) ? {noIndex: true} : {}),
8097
};
8198
}
8299
} catch {

‎apps/docs/src/app/components/media-enhancer.ts‎

Lines changed: 5 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ import {Router} from '@angular/router';
33
import {enhanceOnNavigation} from '../utils/enhance-on-navigation';
44

55
/**
6-
* Hydrates the placeholder divs emitted by the ngmd-video and ngmd-image
7-
* marked extensions. The marked extensions output plain `<div data-...>`
8-
* elements; this enhancer creates the real <iframe> and <figure><img>
9-
* structures programmatically — bypassing any Angular [innerHTML]
10-
* sanitisation that may strip iframes in some configurations.
6+
* Hydrates the placeholder divs emitted by the ngmd-video marked extension.
7+
* It outputs plain `<div data-...>` elements; this enhancer creates the real
8+
* <iframe> programmatically, bypassing any Angular [innerHTML] sanitisation
9+
* that may strip iframes in some configurations. `<ngmd-image>` renders its
10+
* `<figure><img>` directly, so it is in the prerendered HTML.
1111
*/
1212
@Component({
1313
selector: 'app-media-enhancer',
@@ -29,12 +29,6 @@ export class MediaEnhancer implements AfterViewInit {
2929
'.ngmd-video[data-video-src]:not([data-enhanced])',
3030
(el) => this.enhanceVideo(el),
3131
);
32-
enhanceOnNavigation(
33-
this.router,
34-
this.destroyRef,
35-
'.ngmd-image[data-image-src]:not([data-enhanced])',
36-
(el) => this.enhanceImage(el),
37-
);
3832
}
3933

4034
private enhanceVideo(el: HTMLElement): void {
@@ -49,31 +43,4 @@ export class MediaEnhancer implements AfterViewInit {
4943
iframe.loading = 'lazy';
5044
el.appendChild(iframe);
5145
}
52-
53-
private enhanceImage(el: HTMLElement): void {
54-
el.setAttribute('data-enhanced', 'true');
55-
const src = el.dataset['imageSrc'] ?? '';
56-
const alt = el.dataset['imageAlt'] ?? '';
57-
const caption = el.dataset['imageCaption'] ?? '';
58-
const width = el.dataset['imageWidth'] ?? '';
59-
60-
// Replace the placeholder with an actual <figure>
61-
const figure = document.createElement('figure');
62-
figure.className = 'ngmd-image';
63-
if (width) figure.style.maxWidth = /^\d+(\.\d+)?$/.test(width) ? `${width}px` : width;
64-
65-
const img = document.createElement('img');
66-
img.src = src;
67-
img.alt = alt;
68-
img.loading = 'lazy';
69-
figure.appendChild(img);
70-
71-
if (caption) {
72-
const figcaption = document.createElement('figcaption');
73-
figcaption.textContent = caption;
74-
figure.appendChild(figcaption);
75-
}
76-
77-
el.replaceWith(figure);
78-
}
7946
}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import {DOCUMENT} from '@angular/core';
2+
import {TestBed} from '@angular/core/testing';
3+
import {Meta} from '@angular/platform-browser';
4+
import siteConfig from '../../../ngmd.config';
5+
import {PageMetaService, canonicalUrl} from './page-meta.service';
6+
7+
vi.mock('virtual:ngmd/page-meta', () => ({
8+
pageMeta: {
9+
'/inspectors/router': {editUrl: '', lastUpdated: '', description: 'The Router tab.'},
10+
'/contributing/kitchen-sink': {editUrl: '', lastUpdated: '', noIndex: true},
11+
},
12+
}));
13+
14+
describe('canonicalUrl', () => {
15+
it('drops the query, fragment and trailing slash', () => {
16+
expect(canonicalUrl('/inspectors/router/?tab=1#agent-tools')).toBe(
17+
'https://pangular-inspector.dev/inspectors/router',
18+
);
19+
});
20+
21+
it('keeps the slash of the homepage', () => {
22+
expect(canonicalUrl('/')).toBe('https://pangular-inspector.dev/');
23+
});
24+
});
25+
26+
describe('PageMetaService', () => {
27+
const tag = (selector: string) => TestBed.inject(Meta).getTag(selector)?.content;
28+
29+
it('sets the canonical link, og:url, titles and the page description', () => {
30+
TestBed.inject(PageMetaService).setPage(
31+
'/inspectors/router#agent-tools',
32+
'Pangular Inspector | Router',
33+
);
34+
35+
const canonical = TestBed.inject(DOCUMENT).head.querySelector('link[rel="canonical"]');
36+
expect(canonical?.getAttribute('href')).toBe(
37+
'https://pangular-inspector.dev/inspectors/router',
38+
);
39+
expect(tag('property="og:url"')).toBe('https://pangular-inspector.dev/inspectors/router');
40+
expect(tag('property="og:title"')).toBe('Pangular Inspector | Router');
41+
expect(tag('name="twitter:title"')).toBe('Pangular Inspector | Router');
42+
for (const selector of [
43+
'name="description"',
44+
'property="og:description"',
45+
'name="twitter:description"',
46+
])
47+
expect(tag(selector)).toBe('The Router tab.');
48+
expect(tag('name="robots"')).toBeUndefined();
49+
});
50+
51+
it('falls back to the site description, and marks a noIndex page', () => {
52+
const pageMeta = TestBed.inject(PageMetaService);
53+
54+
pageMeta.setPage('/contributing/kitchen-sink', 'Kitchen sink');
55+
expect(tag('name="description"')).toBe(siteConfig.site.description);
56+
expect(tag('name="robots"')).toBe('noindex');
57+
58+
pageMeta.setPage('/inspectors/router', 'Router');
59+
expect(tag('name="robots"')).toBeUndefined();
60+
});
61+
62+
it('keeps one canonical link across pages', () => {
63+
const pageMeta = TestBed.inject(PageMetaService);
64+
pageMeta.setPage('/a', 'A');
65+
pageMeta.setPage('/b', 'B');
66+
67+
const links = TestBed.inject(DOCUMENT).head.querySelectorAll('link[rel="canonical"]');
68+
expect(links.length).toBe(1);
69+
expect(links[0].getAttribute('href')).toBe('https://pangular-inspector.dev/b');
70+
});
71+
});
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import {DOCUMENT, Service, inject} from '@angular/core';
2+
import {Meta} from '@angular/platform-browser';
3+
import {pageMeta} from 'virtual:ngmd/page-meta';
4+
import siteConfig from '../../../ngmd.config';
5+
import {stripUrl} from '../route-url/route-url.service';
6+
7+
/**
8+
* The head tags that differ per page: the canonical URL, `og:url`, the
9+
* Open Graph and Twitter titles, the description in its three tags, and
10+
* `robots: noindex` for a page whose frontmatter sets `noIndex`. The
11+
* description comes from the page's frontmatter (see `page-meta.plugin.ts`),
12+
* or is the site's. `index.html` holds the site-wide values, and the
13+
* prerendered HTML carries each page's own.
14+
*/
15+
@Service()
16+
export class PageMetaService {
17+
private readonly meta = inject(Meta);
18+
private readonly document = inject(DOCUMENT);
19+
20+
/** Point the tags at the page at `url`, titled `title`. */
21+
setPage(url: string, title: string): void {
22+
const canonical = canonicalUrl(url);
23+
const page = pageMeta[stripUrl(url)];
24+
const description = page?.description?.trim() || siteConfig.site.description;
25+
26+
this.meta.updateTag({property: 'og:url', content: canonical});
27+
this.meta.updateTag({property: 'og:title', content: title});
28+
this.meta.updateTag({name: 'twitter:title', content: title});
29+
this.meta.updateTag({name: 'description', content: description});
30+
this.meta.updateTag({property: 'og:description', content: description});
31+
this.meta.updateTag({name: 'twitter:description', content: description});
32+
if (page?.noIndex) this.meta.updateTag({name: 'robots', content: 'noindex'});
33+
else this.meta.removeTag('name="robots"');
34+
this.setCanonical(canonical);
35+
}
36+
37+
private setCanonical(href: string): void {
38+
let link = this.document.head.querySelector<HTMLLinkElement>('link[rel="canonical"]');
39+
if (!link) {
40+
link = this.document.createElement('link');
41+
link.setAttribute('rel', 'canonical');
42+
this.document.head.appendChild(link);
43+
}
44+
link.setAttribute('href', href);
45+
}
46+
}
47+
48+
/** The absolute URL of a page, without a query, fragment or trailing slash, as the sitemap lists it. */
49+
export function canonicalUrl(url: string): string {
50+
const base = siteConfig.site.url.replace(/\/+$/, '');
51+
const path = stripUrl(url);
52+
return path === '/' ? `${base}/` : `${base}${path}`;
53+
}

‎apps/docs/src/app/title-strategy.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {Injectable, inject} from '@angular/core';
22
import {Title} from '@angular/platform-browser';
33
import {TitleStrategy, type RouterStateSnapshot} from '@angular/router';
44
import siteConfig, {navItems, navLabels} from '../ngmd.config';
5+
import {PageMetaService} from './services/page-meta/page-meta.service';
56
import {stripUrl} from './services/route-url/route-url.service';
67

78
/**
@@ -15,11 +16,13 @@ import {stripUrl} from './services/route-url/route-url.service';
1516
* 4. `siteConfig.site.tagline` for the homepage.
1617
*
1718
* Replaces Angular's `DefaultTitleStrategy`, which would otherwise overwrite
18-
* our format with just the raw frontmatter title.
19+
* our format with just the raw frontmatter title. It also points the
20+
* canonical URL and the social tags at the page (see `PageMetaService`).
1921
*/
2022
@Injectable({providedIn: 'root'})
2123
export class NgmdTitleStrategy extends TitleStrategy {
2224
private readonly title = inject(Title);
25+
private readonly pageMeta = inject(PageMetaService);
2326

2427
override updateTitle(snapshot: RouterStateSnapshot): void {
2528
const name = siteConfig.site.name;
@@ -28,7 +31,7 @@ export class NgmdTitleStrategy extends TitleStrategy {
2831
// Homepage uses the tagline in place of a page title.
2932
if (url === '/' || url === '') {
3033
const tagline = siteConfig.site.tagline;
31-
this.title.setTitle(tagline ? `${name} | ${tagline}` : name);
34+
this.setTitle(url, tagline ? `${name} | ${tagline}` : name);
3235
return;
3336
}
3437

@@ -43,6 +46,11 @@ export class NgmdTitleStrategy extends TitleStrategy {
4346
.map((w) => (w ? w[0].toUpperCase() + w.slice(1) : w))
4447
.join(' ');
4548
}
46-
this.title.setTitle(pageTitle ? `${name} | ${pageTitle}` : name);
49+
this.setTitle(url, pageTitle ? `${name} | ${pageTitle}` : name);
50+
}
51+
52+
private setTitle(url: string, title: string): void {
53+
this.title.setTitle(title);
54+
this.pageMeta.setPage(url, title);
4755
}
4856
}

0 commit comments

Comments
 (0)