Repository navigation
fix(docs): give each page its own description and canonical URL, and stop layout shifts #443
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
erkamyaman
wants to merge
1
commit into
main
Choose a base branch
from
claude/blissful-shannon-m0cnu9
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import {mkdirSync, mkdtempSync, writeFileSync} from 'node:fs'; | ||
| import {tmpdir} from 'node:os'; | ||
| import {join} from 'node:path'; | ||
| import {imageSize, readImageSizes} from './image-sizes'; | ||
|
|
||
| function png(width: number, height: number): Uint8Array { | ||
| const bytes = new Uint8Array(24); | ||
| bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); | ||
| const view = new DataView(bytes.buffer); | ||
| view.setUint32(16, width); | ||
| view.setUint32(20, height); | ||
| return bytes; | ||
| } | ||
|
|
||
| function jpeg(width: number, height: number): Uint8Array { | ||
| // SOI, an APP0 segment, then a baseline start-of-frame segment. | ||
| const app0 = [0xff, 0xe0, 0x00, 0x04, 0x00, 0x00]; | ||
| const sof = [ | ||
| 0xff, | ||
| 0xc0, | ||
| 0x00, | ||
| 0x11, | ||
| 0x08, | ||
| height >> 8, | ||
| height & 0xff, | ||
| width >> 8, | ||
| width & 0xff, | ||
| 0x03, | ||
| ]; | ||
| return new Uint8Array([0xff, 0xd8, ...app0, ...sof, ...new Array(12).fill(0)]); | ||
| } | ||
|
|
||
| describe('imageSize', () => { | ||
| it('reads PNG and JPEG headers', () => { | ||
| expect(imageSize(png(1280, 800))).toEqual([1280, 800]); | ||
| expect(imageSize(jpeg(640, 480))).toEqual([640, 480]); | ||
| }); | ||
|
|
||
| it('returns undefined for other files', () => { | ||
| expect(imageSize(new TextEncoder().encode('<svg></svg>'))).toBeUndefined(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('readImageSizes', () => { | ||
| it('keys the sizes by URL path', () => { | ||
| const dir = mkdtempSync(join(tmpdir(), 'image-sizes-')); | ||
| mkdirSync(join(dir, 'images/panel'), {recursive: true}); | ||
| writeFileSync(join(dir, 'images/panel/router.png'), png(1280, 800)); | ||
| writeFileSync(join(dir, 'logo.svg'), '<svg></svg>'); | ||
| expect(readImageSizes(dir)).toEqual({'/images/panel/router.png': [1280, 800]}); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import {readFileSync, readdirSync, statSync} from 'node:fs'; | ||
| import {join, relative, sep} from 'node:path'; | ||
|
|
||
| /** | ||
| * Width and height in pixels, by the public URL of the image | ||
| * (`/images/panel/router.png`). The build-time `<ngmd-image>` writes them into | ||
| * the `width` and `height` of its `<img>`, so the browser reserves the image's | ||
| * space before it loads and the page does not shift (CLS). | ||
| */ | ||
| export type ImageSizes = Record<string, [number, number]>; | ||
|
|
||
| /** The sizes of the PNG and JPEG files under `dir`, keyed by their URL path. */ | ||
| export function readImageSizes(dir: string): ImageSizes { | ||
| const sizes: ImageSizes = {}; | ||
| const walk = (current: string) => { | ||
| for (const name of readdirSync(current)) { | ||
| const file = join(current, name); | ||
| if (statSync(file).isDirectory()) walk(file); | ||
| else if (/\.(png|jpe?g)$/i.test(name)) { | ||
| const size = imageSize(readFileSync(file)); | ||
| if (size) sizes['/' + relative(dir, file).split(sep).join('/')] = size; | ||
| } | ||
| } | ||
| }; | ||
| try { | ||
| walk(dir); | ||
| } catch { | ||
| // no public/ directory | ||
| } | ||
| return sizes; | ||
| } | ||
|
|
||
| /** Width and height from a PNG or JPEG header, or `undefined` for anything else. */ | ||
| export function imageSize(bytes: Uint8Array): [number, number] | undefined { | ||
| const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); | ||
| // PNG: signature, then the IHDR chunk with width and height. | ||
| if (bytes.length >= 24 && view.getUint32(0) === 0x89504e47) | ||
| return [view.getUint32(16), view.getUint32(20)]; | ||
| // JPEG: walk the segments to the first start-of-frame marker. | ||
| if (bytes.length >= 4 && view.getUint16(0) === 0xffd8) { | ||
| let offset = 2; | ||
| while (offset + 9 < bytes.length) { | ||
| if (bytes[offset] !== 0xff) return undefined; | ||
| const marker = bytes[offset + 1]; | ||
| const length = view.getUint16(offset + 2); | ||
| const isFrame = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker); | ||
| if (isFrame) return [view.getUint16(offset + 7), view.getUint16(offset + 5)]; | ||
| offset += 2 + length; | ||
| } | ||
| } | ||
| return undefined; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
71 changes: 71 additions & 0 deletions
71
apps/docs/src/app/services/page-meta/page-meta.service.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import {DOCUMENT} from '@angular/core'; | ||
| import {TestBed} from '@angular/core/testing'; | ||
| import {Meta} from '@angular/platform-browser'; | ||
| import siteConfig from '../../../ngmd.config'; | ||
| import {PageMetaService, canonicalUrl} from './page-meta.service'; | ||
|
|
||
| vi.mock('virtual:ngmd/page-meta', () => ({ | ||
| pageMeta: { | ||
| '/inspectors/router': {editUrl: '', lastUpdated: '', description: 'The Router tab.'}, | ||
| '/contributing/kitchen-sink': {editUrl: '', lastUpdated: '', noIndex: true}, | ||
| }, | ||
| })); | ||
|
|
||
| describe('canonicalUrl', () => { | ||
| it('drops the query, fragment and trailing slash', () => { | ||
| expect(canonicalUrl('/inspectors/router/?tab=1#agent-tools')).toBe( | ||
| 'https://pangular-inspector.dev/inspectors/router', | ||
| ); | ||
| }); | ||
|
|
||
| it('keeps the slash of the homepage', () => { | ||
| expect(canonicalUrl('/')).toBe('https://pangular-inspector.dev/'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('PageMetaService', () => { | ||
| const tag = (selector: string) => TestBed.inject(Meta).getTag(selector)?.content; | ||
|
|
||
| it('sets the canonical link, og:url, titles and the page description', () => { | ||
| TestBed.inject(PageMetaService).setPage( | ||
| '/inspectors/router#agent-tools', | ||
| 'Pangular Inspector | Router', | ||
| ); | ||
|
|
||
| const canonical = TestBed.inject(DOCUMENT).head.querySelector('link[rel="canonical"]'); | ||
| expect(canonical?.getAttribute('href')).toBe( | ||
| 'https://pangular-inspector.dev/inspectors/router', | ||
| ); | ||
| expect(tag('property="og:url"')).toBe('https://pangular-inspector.dev/inspectors/router'); | ||
| expect(tag('property="og:title"')).toBe('Pangular Inspector | Router'); | ||
| expect(tag('name="twitter:title"')).toBe('Pangular Inspector | Router'); | ||
| for (const selector of [ | ||
| 'name="description"', | ||
| 'property="og:description"', | ||
| 'name="twitter:description"', | ||
| ]) | ||
| expect(tag(selector)).toBe('The Router tab.'); | ||
| expect(tag('name="robots"')).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('falls back to the site description, and marks a noIndex page', () => { | ||
| const pageMeta = TestBed.inject(PageMetaService); | ||
|
|
||
| pageMeta.setPage('/contributing/kitchen-sink', 'Kitchen sink'); | ||
| expect(tag('name="description"')).toBe(siteConfig.site.description); | ||
| expect(tag('name="robots"')).toBe('noindex'); | ||
|
|
||
| pageMeta.setPage('/inspectors/router', 'Router'); | ||
| expect(tag('name="robots"')).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('keeps one canonical link across pages', () => { | ||
| const pageMeta = TestBed.inject(PageMetaService); | ||
| pageMeta.setPage('/a', 'A'); | ||
| pageMeta.setPage('/b', 'B'); | ||
|
|
||
| const links = TestBed.inject(DOCUMENT).head.querySelectorAll('link[rel="canonical"]'); | ||
| expect(links.length).toBe(1); | ||
| expect(links[0].getAttribute('href')).toBe('https://pangular-inspector.dev/b'); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import {DOCUMENT, Service, inject} from '@angular/core'; | ||
| import {Meta} from '@angular/platform-browser'; | ||
| import {pageMeta} from 'virtual:ngmd/page-meta'; | ||
| import siteConfig from '../../../ngmd.config'; | ||
| import {stripUrl} from '../route-url/route-url.service'; | ||
|
|
||
| /** | ||
| * The head tags that differ per page: the canonical URL, `og:url`, the | ||
| * Open Graph and Twitter titles, the description in its three tags, and | ||
| * `robots: noindex` for a page whose frontmatter sets `noIndex`. The | ||
| * description comes from the page's frontmatter (see `page-meta.plugin.ts`), | ||
| * or is the site's. `index.html` holds the site-wide values, and the | ||
| * prerendered HTML carries each page's own. | ||
| */ | ||
| @Service() | ||
| export class PageMetaService { | ||
| private readonly meta = inject(Meta); | ||
| private readonly document = inject(DOCUMENT); | ||
|
|
||
| /** Point the tags at the page at `url`, titled `title`. */ | ||
| setPage(url: string, title: string): void { | ||
| const canonical = canonicalUrl(url); | ||
| const page = pageMeta[stripUrl(url)]; | ||
| const description = page?.description?.trim() || siteConfig.site.description; | ||
|
|
||
| this.meta.updateTag({property: 'og:url', content: canonical}); | ||
| this.meta.updateTag({property: 'og:title', content: title}); | ||
| this.meta.updateTag({name: 'twitter:title', content: title}); | ||
| this.meta.updateTag({name: 'description', content: description}); | ||
| this.meta.updateTag({property: 'og:description', content: description}); | ||
| this.meta.updateTag({name: 'twitter:description', content: description}); | ||
| if (page?.noIndex) this.meta.updateTag({name: 'robots', content: 'noindex'}); | ||
| else this.meta.removeTag('name="robots"'); | ||
| this.setCanonical(canonical); | ||
| } | ||
|
|
||
| private setCanonical(href: string): void { | ||
| let link = this.document.head.querySelector<HTMLLinkElement>('link[rel="canonical"]'); | ||
| if (!link) { | ||
| link = this.document.createElement('link'); | ||
| link.setAttribute('rel', 'canonical'); | ||
| this.document.head.appendChild(link); | ||
| } | ||
| link.setAttribute('href', href); | ||
| } | ||
| } | ||
|
|
||
| /** The absolute URL of a page, without a query, fragment or trailing slash, as the sitemap lists it. */ | ||
| export function canonicalUrl(url: string): string { | ||
| const base = siteConfig.site.url.replace(/\/+$/, ''); | ||
| const path = stripUrl(url); | ||
| return path === '/' ? `${base}/` : `${base}${path}`; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Report image scan failures other than a missing directory.
If
statSyncorreadFileSyncfails for a public image, this catch returns an incomplete size map without reporting the failure. The build can then emit images without dimensions. Catch only the expected missing-directory error; let other scan errors fail the build. (raw.githubusercontent.com)