Compare commits
12 Commits
orchestrat
...
b15dfd7801
| Author | SHA1 | Date | |
|---|---|---|---|
| b15dfd7801 | |||
| 575ba06bb9 | |||
| 1ff26be61b | |||
| 1de146c650 | |||
| 1d2965a7ff | |||
| 271df12334 | |||
| 34367181d2 | |||
| 46c86447d1 | |||
| 2ccac6b28a | |||
| da38cc3624 | |||
| 6c1572bf3c | |||
| 7813499ee3 |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -41,3 +41,9 @@ __screenshots__/
|
||||
# System files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Browser and audit artifacts
|
||||
/test-results
|
||||
/playwright-report
|
||||
/blob-report
|
||||
/.lighthouseci
|
||||
|
||||
@@ -8,3 +8,7 @@ public/**/*.svg
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
.cursor
|
||||
test-results
|
||||
playwright-report
|
||||
.lighthouseci
|
||||
blob-report
|
||||
|
||||
13
AGENTS.md
13
AGENTS.md
@@ -42,6 +42,9 @@ This is a bilingual recruiter and B2B portfolio for a software/DevOps engineer.
|
||||
| `npm run format:check` | Prettier check (CI). |
|
||||
| `npm run serve:ssr` | Serve the production SSR bundle. |
|
||||
| `npm run serve:ssr:Portfolio` | Alias of `serve:ssr` for existing tooling. |
|
||||
| `npm run e2e` | Playwright + axe-core against the SSR bundle. |
|
||||
| `npm run e2e:install` | Install the pinned Chromium build. |
|
||||
| `npm run lighthouse` | Production build, then Lighthouse CI. |
|
||||
| `npm run ci` | lint, format:check, test:ci, then build. |
|
||||
|
||||
## Code conventions
|
||||
@@ -99,6 +102,7 @@ German and English are written idiomatically per language, never machine-transla
|
||||
- No `window`, `document`, `navigator`, `localStorage` or `matchMedia` access outside `afterNextRender` or `isPlatformBrowser` guards
|
||||
- Use the injected `DOCUMENT` token when the document element is required (it works on server and browser)
|
||||
- No user-agent sniffing; use CSS media queries for device capability
|
||||
- Exception: `isApplePlatform()` in `src/app/core/platform/browser.ts` may read `navigator.userAgentData?.platform ?? navigator.platform` after hydration, only to label the Command key. There is no CSS media query for that key. It is not used for device capability.
|
||||
- Capability helpers live in `src/app/core/platform/browser.ts` and return conservative defaults on the server
|
||||
- Helpers that use `inject()` must be called from a field initializer or constructor, never from a lifecycle hook or callback, and the resolved value must be stored on the instance
|
||||
- Every addressable route must remain prerenderable
|
||||
@@ -121,8 +125,13 @@ German and English are written idiomatically per language, never machine-transla
|
||||
- Real locale-prefixed URLs
|
||||
- Server-rendered core text
|
||||
- Per-route titles from the content layer
|
||||
- Canonical origin is `SITE_CONFIG.siteOrigin` (`https://antoniolede.de`); every absolute URL in the app and tests is derived from it
|
||||
- Per-route metadata (description, canonical, reciprocal hreflang including `x-default`, Open Graph, Twitter, robots) is written by `SeoService` during SSR and on every client navigation
|
||||
- One JSON-LD `@graph` script per route: Person and ProfessionalService on Home, Service on service routes, CreativeWork per public case on projects, WebPage elsewhere
|
||||
- `public/robots.txt`, `public/sitemap.xml` and `public/llms.txt` stay synchronized with `prerenderablePaths()` via `crawl-assets.spec.ts`
|
||||
- The language switch exposes `hreflang` on the alternate-locale link
|
||||
|
||||
Canonical, hreflang document tags and JSON-LD arrive in the integration phase. The language switch already exposes `hreflang` on the alternate-locale link.
|
||||
Browser binaries, HTML reports, traces and screenshots are not committed (`test-results`, `playwright-report`, `.lighthouseci`).
|
||||
|
||||
## Test checklist
|
||||
|
||||
@@ -136,6 +145,8 @@ A change is not done until:
|
||||
6. Routing and locale contracts still have unit coverage (paths, locale helpers, navigation links)
|
||||
7. No new `window` / `document` / `navigator` reads were added outside an SSR-safe guard
|
||||
8. Placeholder or legal copy was not replaced with invented professional claims
|
||||
9. Crawl files still match `SITE_CONFIG.siteOrigin` and `prerenderablePaths()`
|
||||
10. Playwright (`npm run e2e`) and Lighthouse CI (`npm run lighthouse`) still pass when the change affects public HTML, metadata or chrome
|
||||
|
||||
## Domain boundaries
|
||||
|
||||
|
||||
@@ -30,6 +30,9 @@ npm install
|
||||
| `npm run format:check` | Check formatting without writing. |
|
||||
| `npm run serve:ssr` | Serve the production SSR bundle from `dist/`. |
|
||||
| `npm run serve:ssr:Portfolio` | Alias of `serve:ssr`. |
|
||||
| `npm run e2e` | Playwright + axe-core against the production SSR bundle. |
|
||||
| `npm run e2e:install` | Install the pinned Chromium build for Playwright. |
|
||||
| `npm run lighthouse` | Production build, then Lighthouse CI (`lighthouserc.json`). |
|
||||
| `npm run ci` | lint, format check, tests, then production build. |
|
||||
|
||||
## Local SSR build
|
||||
@@ -41,6 +44,8 @@ npm run serve:ssr
|
||||
|
||||
The server listens on `http://localhost:4000` unless `PORT` is set. The CV is copied into the browser output at `/cv/CV.pdf`.
|
||||
|
||||
`npm run e2e` builds the SSR bundle and serves it on port 4173. `npm run lighthouse` builds, then starts the SSR server on port 4000. Browser binaries and generated reports (`test-results`, `playwright-report`, `.lighthouseci`) are not committed.
|
||||
|
||||
## Project structure
|
||||
|
||||
```
|
||||
|
||||
48
e2e/a11y.e2e.ts
Normal file
48
e2e/a11y.e2e.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import AxeBuilder from '@axe-core/playwright';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { pagePath } from './helpers';
|
||||
|
||||
const AXE_PATHS = [
|
||||
pagePath('home', 'de'),
|
||||
pagePath('home', 'en'),
|
||||
pagePath('projects', 'de'),
|
||||
pagePath('projects', 'en'),
|
||||
pagePath('servicesAi', 'de'),
|
||||
pagePath('servicesAi', 'en'),
|
||||
pagePath('contact', 'de'),
|
||||
pagePath('contact', 'en'),
|
||||
pagePath('imprint', 'de'),
|
||||
pagePath('imprint', 'en'),
|
||||
'/missing-route',
|
||||
'/en/missing-route',
|
||||
];
|
||||
|
||||
test.describe('accessibility', () => {
|
||||
test('revealed content stays visible under reduced motion', async ({ page }) => {
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' });
|
||||
await page.goto(pagePath('home', 'de'));
|
||||
const pending = page.locator('.reveal-pending');
|
||||
await expect(pending).toHaveCount(0);
|
||||
await expect(page.locator('app-systems-map')).toBeVisible();
|
||||
await expect(page.locator('app-case-card').first()).toBeVisible();
|
||||
});
|
||||
|
||||
for (const path of AXE_PATHS) {
|
||||
test(`axe has no serious or critical violations on ${path}`, async ({ page }) => {
|
||||
await page.goto(path);
|
||||
const results = await new AxeBuilder({ page }).analyze();
|
||||
const blocking = results.violations.filter(
|
||||
(violation) => violation.impact === 'serious' || violation.impact === 'critical',
|
||||
);
|
||||
|
||||
const details = blocking
|
||||
.map((violation) => {
|
||||
const nodes = violation.nodes.map((node) => node.target.join(' ')).join(', ');
|
||||
return `${violation.id} (${violation.impact}): ${nodes}`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
expect(blocking, details).toEqual([]);
|
||||
});
|
||||
}
|
||||
});
|
||||
37
e2e/contact.e2e.ts
Normal file
37
e2e/contact.e2e.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { SITE_CONTENT_DATA } from '../src/app/core/content/site-content';
|
||||
import { SITE_CONFIG } from '../src/app/core/content/site-config';
|
||||
import { pagePath } from './helpers';
|
||||
|
||||
test.describe('contact briefing', () => {
|
||||
test('builds a mailto href and issues no network request', async ({ page }) => {
|
||||
const extras: string[] = [];
|
||||
await page.route('**/*', (route) => {
|
||||
const url = route.request().url();
|
||||
const resource = route.request().resourceType();
|
||||
if (resource !== 'document' && !url.startsWith('data:') && !url.startsWith('blob:')) {
|
||||
extras.push(`${resource} ${url}`);
|
||||
}
|
||||
void route.continue();
|
||||
});
|
||||
|
||||
await page.goto(pagePath('contact', 'de'), { waitUntil: 'networkidle' });
|
||||
extras.length = 0;
|
||||
|
||||
const emptySubmit = page.locator('.submit');
|
||||
await expect(emptySubmit).toHaveAttribute('aria-disabled', 'true');
|
||||
expect(await emptySubmit.getAttribute('href')).toBeNull();
|
||||
|
||||
await page.locator('#contact-name').fill('Ada');
|
||||
await page.locator('#contact-email').fill('ada@example.com');
|
||||
await page.locator('#contact-projectType').selectOption('software');
|
||||
await page.locator('#contact-situation').fill('Need a migration.');
|
||||
|
||||
const href = await page.locator('a.submit').getAttribute('href');
|
||||
expect(href).toMatch(/^mailto:/);
|
||||
expect(href).toContain(encodeURIComponent(SITE_CONTENT_DATA.de.contact.mailSubject));
|
||||
expect(href).toContain(encodeURIComponent('Ada'));
|
||||
expect(href).toContain(SITE_CONFIG.contactEmail);
|
||||
expect(extras, extras.join('\n')).toEqual([]);
|
||||
});
|
||||
});
|
||||
79
e2e/fragments.e2e.ts
Normal file
79
e2e/fragments.e2e.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import { APP_LOCALES } from '../src/app/core/i18n/locale';
|
||||
import { pagePath } from './helpers';
|
||||
|
||||
const VIEWPORTS = [768, 820, 1024, 1280, 1440] as const;
|
||||
const VIEWPORT_HEIGHT = 900;
|
||||
const MAX_HEADER_HEIGHT = 200;
|
||||
|
||||
async function waitForScrollSettle(page: Page): Promise<void> {
|
||||
await page.evaluate(async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
let last = window.scrollY;
|
||||
let stableFrames = 0;
|
||||
const tick = () => {
|
||||
if (window.scrollY === last) {
|
||||
stableFrames += 1;
|
||||
if (stableFrames >= 8) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
stableFrames = 0;
|
||||
last = window.scrollY;
|
||||
}
|
||||
requestAnimationFrame(tick);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test.describe('fragment scrolling', () => {
|
||||
test('case headings stay fully visible under the compact header', async ({ page }, testInfo) => {
|
||||
test.skip(
|
||||
testInfo.project.name === 'mobile',
|
||||
'desktop widths are measured here to avoid a duplicate run',
|
||||
);
|
||||
|
||||
for (const width of VIEWPORTS) {
|
||||
await page.setViewportSize({ width, height: VIEWPORT_HEIGHT });
|
||||
|
||||
for (const locale of APP_LOCALES) {
|
||||
const path = `${pagePath('projects', locale)}#myspa`;
|
||||
const label = `${width}px ${locale}`;
|
||||
await page.goto(path, { waitUntil: 'networkidle' });
|
||||
|
||||
const header = page.locator('.site-header');
|
||||
const heading = page.locator('#myspa h2');
|
||||
await expect(heading).toBeVisible();
|
||||
|
||||
await waitForScrollSettle(page);
|
||||
|
||||
const headerBox = await header.boundingBox();
|
||||
expect(headerBox, label).toBeTruthy();
|
||||
expect(
|
||||
headerBox!.height,
|
||||
`header height at ${label} must be at most ${MAX_HEADER_HEIGHT}px`,
|
||||
).toBeLessThanOrEqual(MAX_HEADER_HEIGHT);
|
||||
expect(
|
||||
headerBox!.height,
|
||||
`header height at ${label} must be at most 25% of the viewport`,
|
||||
).toBeLessThanOrEqual(VIEWPORT_HEIGHT * 0.25);
|
||||
|
||||
await expect(header).not.toHaveCSS('position', 'sticky');
|
||||
await expect(heading).toBeInViewport({ ratio: 1 });
|
||||
|
||||
const headingOwnsCentre = await heading.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const node = document.elementFromPoint(
|
||||
rect.left + rect.width / 2,
|
||||
rect.top + rect.height / 2,
|
||||
);
|
||||
return node !== null && (element === node || element.contains(node));
|
||||
});
|
||||
expect(headingOwnsCentre, `heading centre must not be covered at ${label}`).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
97
e2e/helpers.ts
Normal file
97
e2e/helpers.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { expect, type APIRequestContext, type Page } from '@playwright/test';
|
||||
import { SITE_CONFIG } from '../src/app/core/content/site-config';
|
||||
import { SITE_CONTENT_DATA } from '../src/app/core/content/site-content';
|
||||
import { type AppLocale } from '../src/app/core/i18n/locale';
|
||||
import { LOCALE_HTML_LANG } from '../src/app/core/i18n/locale';
|
||||
import { type RouteId } from '../src/app/core/routing/route-ids';
|
||||
import { routePath } from '../src/app/core/routing/route-paths';
|
||||
import { buildRouteMetadata } from '../src/app/core/seo/route-metadata';
|
||||
|
||||
export const ORIGIN = SITE_CONFIG.siteOrigin;
|
||||
|
||||
export function pagePath(routeId: RouteId, locale: AppLocale): string {
|
||||
return routePath(routeId, locale);
|
||||
}
|
||||
|
||||
export async function readHtml(
|
||||
request: APIRequestContext,
|
||||
path: string,
|
||||
expectedStatus: number,
|
||||
): Promise<string> {
|
||||
const response = await request.get(path);
|
||||
expect(response.status(), `GET ${path} status`).toBe(expectedStatus);
|
||||
return response.text();
|
||||
}
|
||||
|
||||
export function attr(html: string, selector: string, attribute: string): string | null {
|
||||
const pattern = new RegExp(
|
||||
`<[^>]*${selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^>]*${attribute}="([^"]*)"`,
|
||||
'i',
|
||||
);
|
||||
return html.match(pattern)?.[1] ?? null;
|
||||
}
|
||||
|
||||
export function count(html: string, snippet: string): number {
|
||||
return html.split(snippet).length - 1;
|
||||
}
|
||||
|
||||
export async function expectHead(
|
||||
request: APIRequestContext,
|
||||
routeId: RouteId,
|
||||
locale: AppLocale,
|
||||
): Promise<void> {
|
||||
const path =
|
||||
routeId === 'notFound'
|
||||
? locale === 'en'
|
||||
? '/en/missing-route'
|
||||
: '/missing-route'
|
||||
: pagePath(routeId, locale);
|
||||
const expectedStatus = routeId === 'notFound' ? 404 : 200;
|
||||
const html = await readHtml(request, path, expectedStatus);
|
||||
const metadata = buildRouteMetadata(routeId, locale, SITE_CONTENT_DATA);
|
||||
|
||||
expect(html, `${path} title`).toContain(`<title>${metadata.title}</title>`);
|
||||
expect(html).toContain(`name="description"`);
|
||||
expect(html).toContain(`content="${metadata.description}"`);
|
||||
expect(html).toContain(`name="robots"`);
|
||||
expect(html).toContain(`content="${metadata.robots}"`);
|
||||
expect(html).toContain(`<html lang="${LOCALE_HTML_LANG[locale]}"`);
|
||||
expect(count(html, 'name="description"')).toBe(1);
|
||||
expect(count(html, 'name="robots"')).toBe(1);
|
||||
expect(count(html, 'type="application/ld+json"')).toBe(1);
|
||||
|
||||
if (routeId === 'notFound') {
|
||||
expect(html).not.toMatch(/rel="canonical"/);
|
||||
expect(html).not.toMatch(/rel="alternate"[^>]*hreflang/);
|
||||
return;
|
||||
}
|
||||
|
||||
expect(html).toContain(`rel="canonical"`);
|
||||
expect(html).toContain(`href="${metadata.canonical}"`);
|
||||
expect(count(html, 'rel="canonical"')).toBe(1);
|
||||
expect(html).toContain('hreflang="de-DE"');
|
||||
expect(html).toContain('hreflang="en"');
|
||||
expect(html).toContain('hreflang="x-default"');
|
||||
expect(html).toContain('property="og:type"');
|
||||
expect(html).toContain('property="og:title"');
|
||||
expect(html).toContain('property="og:description"');
|
||||
expect(html).toContain('property="og:url"');
|
||||
expect(html).toContain('property="og:site_name"');
|
||||
expect(html).toContain('property="og:locale"');
|
||||
expect(html).toContain('name="twitter:card"');
|
||||
expect(html).toContain('name="twitter:title"');
|
||||
expect(html).toContain('name="twitter:description"');
|
||||
}
|
||||
|
||||
export async function expectNoOverflow(page: Page, route: string, width: number): Promise<void> {
|
||||
const overflow = await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= window.innerWidth + 1,
|
||||
);
|
||||
expect(overflow, `horizontal overflow at ${width}px on ${route}`).toBe(true);
|
||||
}
|
||||
|
||||
export async function jsonLdGraph(page: Page): Promise<unknown> {
|
||||
const raw = await page.locator('script[type="application/ld+json"]').first().textContent();
|
||||
expect(raw).toBeTruthy();
|
||||
return JSON.parse(raw ?? 'null');
|
||||
}
|
||||
123
e2e/keyboard.e2e.ts
Normal file
123
e2e/keyboard.e2e.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { pagePath } from './helpers';
|
||||
|
||||
test.describe('keyboard and palette', () => {
|
||||
test('skip link is first and moves focus to main', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await page.keyboard.press('Tab');
|
||||
const skip = page.locator('.skip-link');
|
||||
await expect(skip).toBeFocused();
|
||||
await page.keyboard.press('Enter');
|
||||
await expect(page.locator('#main-content')).toBeFocused();
|
||||
});
|
||||
|
||||
test('mobile nav toggle keeps aria-expanded in sync', async ({ page, request }) => {
|
||||
const ssr = await request.get('/');
|
||||
expect(ssr.ok()).toBe(true);
|
||||
const html = await ssr.text();
|
||||
expect(html).toContain('aria-expanded="true"');
|
||||
expect(html).toContain('id="primary-nav"');
|
||||
expect(html).toContain('class="site-nav"');
|
||||
expect(html).toMatch(/<div[^>]*class="site"/);
|
||||
expect(html).not.toMatch(/<div[^>]*class="[^"]*\bsite\b[^"]*\bnav-collapsed\b/);
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goto('/');
|
||||
const toggle = page.locator('.nav-toggle');
|
||||
await expect(toggle).toBeVisible();
|
||||
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
|
||||
await toggle.click();
|
||||
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
|
||||
await toggle.click();
|
||||
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
|
||||
test('collapsed header stays under 25% of the viewport and is not sticky below md', async ({
|
||||
page,
|
||||
}) => {
|
||||
const viewport = { width: 390, height: 844 };
|
||||
await page.setViewportSize(viewport);
|
||||
await page.goto('/');
|
||||
|
||||
const header = page.locator('.site-header');
|
||||
const box = await header.boundingBox();
|
||||
expect(box).toBeTruthy();
|
||||
expect(box!.height).toBeLessThan(viewport.height * 0.25);
|
||||
|
||||
await expect
|
||||
.poll(async () => header.evaluate((element) => getComputedStyle(element).position))
|
||||
.not.toBe('sticky');
|
||||
|
||||
await page.locator('.nav-toggle').click();
|
||||
await expect(page.locator('.nav-toggle')).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(await header.evaluate((element) => getComputedStyle(element).position)).not.toBe(
|
||||
'sticky',
|
||||
);
|
||||
|
||||
for (const width of [768, 820, 1024, 1280, 1440]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.goto('/');
|
||||
expect(
|
||||
await header.evaluate((element) => getComputedStyle(element).position),
|
||||
`header must not be sticky at ${width}px`,
|
||||
).not.toBe('sticky');
|
||||
}
|
||||
});
|
||||
|
||||
test('compact services submenu stays keyboard accessible at 1024px', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.skip(testInfo.project.name === 'mobile', 'compact submenu applies from md up');
|
||||
|
||||
await page.setViewportSize({ width: 1024, height: 900 });
|
||||
await page.goto('/');
|
||||
|
||||
const servicesParent = page.locator(
|
||||
`.primary-nav > li > a[href="${pagePath('services', 'de')}"]`,
|
||||
);
|
||||
const firstChild = page.locator(
|
||||
`.primary-nav > li > .submenu a[href="${pagePath('servicesSoftware', 'de')}"]`,
|
||||
);
|
||||
|
||||
await servicesParent.focus();
|
||||
await expect(firstChild).toBeVisible();
|
||||
await page.keyboard.press('Tab');
|
||||
await expect(firstChild).toBeFocused();
|
||||
|
||||
const headerBox = await page.locator('.site-header').boundingBox();
|
||||
expect(headerBox, 'header while submenu is open').toBeTruthy();
|
||||
expect(headerBox!.height, 'header height while submenu is open').toBeLessThanOrEqual(200);
|
||||
});
|
||||
|
||||
test('palette opens with Control+K, traps focus, locks scroll and restores on Escape', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto('/');
|
||||
const trigger = page.locator('.command-palette-trigger');
|
||||
await trigger.focus();
|
||||
await page.keyboard.press('Control+k');
|
||||
|
||||
const dialog = page.locator('[role="dialog"]');
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(page.locator('.site')).toHaveAttribute('inert', '');
|
||||
expect(await page.evaluate(() => document.body.style.overflow)).toBe('hidden');
|
||||
|
||||
const focusable = dialog.locator(
|
||||
'a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled])',
|
||||
);
|
||||
const count = await focusable.count();
|
||||
const first = focusable.first();
|
||||
const last = focusable.nth(count - 1);
|
||||
await last.focus();
|
||||
await page.keyboard.press('Tab');
|
||||
await expect(first).toBeFocused();
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await expect(last).toBeFocused();
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(dialog).toHaveCount(0);
|
||||
await expect(page.locator('.site')).not.toHaveAttribute('inert');
|
||||
expect(await page.evaluate(() => document.body.style.overflow)).toBe('');
|
||||
await expect(trigger).toBeFocused();
|
||||
});
|
||||
});
|
||||
79
e2e/layout.e2e.ts
Normal file
79
e2e/layout.e2e.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { SITE_CONFIG } from '../src/app/core/content/site-config';
|
||||
import { expectNoOverflow, pagePath } from './helpers';
|
||||
|
||||
const CHECKED = [
|
||||
pagePath('home', 'de'),
|
||||
pagePath('home', 'en'),
|
||||
pagePath('projects', 'de'),
|
||||
pagePath('projects', 'en'),
|
||||
pagePath('servicesAi', 'de'),
|
||||
pagePath('contact', 'de'),
|
||||
pagePath('imprint', 'en'),
|
||||
'/missing-route',
|
||||
];
|
||||
|
||||
const VIEWPORTS = [320, 768, 1024, 1440] as const;
|
||||
|
||||
test.describe('layout and crawlability', () => {
|
||||
test('does not overflow horizontally on checked routes', async ({ page }) => {
|
||||
for (const width of VIEWPORTS) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
for (const path of CHECKED) {
|
||||
await page.goto(path);
|
||||
await expectNoOverflow(page, path, width);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('same-origin links and crawl files respond below 400', async ({ page, request }) => {
|
||||
const seen = new Set<string>();
|
||||
const queue = [pagePath('home', 'de'), pagePath('home', 'en')];
|
||||
|
||||
while (queue.length > 0) {
|
||||
const path = queue.shift() as string;
|
||||
if (seen.has(path)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(path);
|
||||
|
||||
await page.goto(path);
|
||||
const { urls, baseURI } = await page.evaluate(() => {
|
||||
const values = [
|
||||
...Array.from(document.querySelectorAll('a[href]'), (node) => node.getAttribute('href')),
|
||||
...Array.from(document.querySelectorAll('[src]'), (node) => node.getAttribute('src')),
|
||||
];
|
||||
return {
|
||||
baseURI: document.baseURI,
|
||||
urls: values.filter(
|
||||
(value): value is string => typeof value === 'string' && value.length > 0,
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
for (const raw of urls) {
|
||||
if (raw.startsWith('mailto:') || raw.startsWith('tel:') || raw.startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolved = new URL(raw, baseURI);
|
||||
if (resolved.origin !== new URL(baseURI).origin) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const next = `${resolved.pathname}${resolved.search}`;
|
||||
const response = await request.get(next);
|
||||
expect(response.status(), `${raw} from ${path}`).toBeLessThan(400);
|
||||
|
||||
if (!seen.has(next) && !next.includes('.')) {
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const asset of ['/robots.txt', '/sitemap.xml', '/llms.txt', SITE_CONFIG.cvAssetPath]) {
|
||||
const response = await request.get(asset);
|
||||
expect(response.status(), asset).toBe(200);
|
||||
}
|
||||
});
|
||||
});
|
||||
100
e2e/seo.e2e.ts
Normal file
100
e2e/seo.e2e.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import { SITE_CONTENT_DATA } from '../src/app/core/content/site-content';
|
||||
import { expectHead, jsonLdGraph, pagePath } from './helpers';
|
||||
|
||||
async function ensurePrimaryNavOpen(page: Page): Promise<void> {
|
||||
const toggle = page.locator('.nav-toggle');
|
||||
if ((await toggle.isVisible()) && (await toggle.getAttribute('aria-expanded')) === 'false') {
|
||||
await toggle.click();
|
||||
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
|
||||
}
|
||||
}
|
||||
|
||||
test.describe('server-rendered metadata', () => {
|
||||
test('German and English Home include the full head contract', async ({ request, page }) => {
|
||||
await expectHead(request, 'home', 'de');
|
||||
await expectHead(request, 'home', 'en');
|
||||
|
||||
await page.goto('/');
|
||||
const graph = (await jsonLdGraph(page)) as { '@graph': Array<{ '@type': string }> };
|
||||
const types = graph['@graph'].map((node) => node['@type']);
|
||||
expect(types).toContain('Person');
|
||||
expect(types).toContain('ProfessionalService');
|
||||
|
||||
await page.goto('/en');
|
||||
const english = (await jsonLdGraph(page)) as { '@graph': Array<{ '@type': string }> };
|
||||
expect(english['@graph'].map((node) => node['@type'])).toEqual(
|
||||
expect.arrayContaining(['Person', 'ProfessionalService']),
|
||||
);
|
||||
});
|
||||
|
||||
test('projects, AI service, contact, legal and 404 keep locale metadata', async ({ request }) => {
|
||||
for (const locale of ['de', 'en'] as const) {
|
||||
await expectHead(request, 'projects', locale);
|
||||
await expectHead(request, 'servicesAi', locale);
|
||||
await expectHead(request, 'contact', locale);
|
||||
await expectHead(request, 'imprint', locale);
|
||||
await expectHead(request, 'notFound', locale);
|
||||
}
|
||||
});
|
||||
|
||||
test('unmatched URLs return 404 and a real route stays 200', async ({ request }) => {
|
||||
const home = await request.get('/');
|
||||
expect(home.status(), 'GET /').toBe(200);
|
||||
|
||||
await expectHead(request, 'notFound', 'de');
|
||||
await expectHead(request, 'notFound', 'en');
|
||||
});
|
||||
|
||||
test('client navigation does not duplicate head tags', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await ensurePrimaryNavOpen(page);
|
||||
await page.locator('a.contact-cta').first().waitFor();
|
||||
|
||||
const assertUnique = async (canonical: string, description: string) => {
|
||||
await expect(page.locator('link[rel="canonical"]')).toHaveCount(1);
|
||||
await expect(page.locator('link[rel="alternate"][hreflang="de-DE"]')).toHaveCount(1);
|
||||
await expect(page.locator('link[rel="alternate"][hreflang="en"]')).toHaveCount(1);
|
||||
await expect(page.locator('link[rel="alternate"][hreflang="x-default"]')).toHaveCount(1);
|
||||
await expect(page.locator('meta[name="description"]')).toHaveCount(1);
|
||||
await expect(page.locator('meta[name="robots"]')).toHaveCount(1);
|
||||
await expect(page.locator('script[type="application/ld+json"]')).toHaveCount(1);
|
||||
await expect(page.locator('link[rel="canonical"]')).toHaveAttribute('href', canonical);
|
||||
await expect(page.locator('meta[name="description"]')).toHaveAttribute(
|
||||
'content',
|
||||
description,
|
||||
);
|
||||
};
|
||||
|
||||
await ensurePrimaryNavOpen(page);
|
||||
await page
|
||||
.locator(`a[href="${pagePath('projects', 'de')}"]`)
|
||||
.first()
|
||||
.click();
|
||||
await page.waitForURL('**/projekte');
|
||||
await assertUnique(
|
||||
'https://antoniolede.de/projekte',
|
||||
SITE_CONTENT_DATA.de.pages.projects.description,
|
||||
);
|
||||
|
||||
await ensurePrimaryNavOpen(page);
|
||||
const servicesParent = page.locator(
|
||||
`.primary-nav > li > a[href="${pagePath('services', 'de')}"]`,
|
||||
);
|
||||
const servicesAiLink = page
|
||||
.locator(`.primary-nav a[href="${pagePath('servicesAi', 'de')}"]`)
|
||||
.first();
|
||||
if (!(await servicesAiLink.isVisible())) {
|
||||
await servicesParent.hover();
|
||||
await expect(servicesAiLink).toBeVisible();
|
||||
}
|
||||
await servicesAiLink.click();
|
||||
await page.waitForURL('**/leistungen/ai-integration');
|
||||
await expect(page.locator('link[rel="canonical"]')).toHaveCount(1);
|
||||
await expect(page.locator('link[rel="canonical"]')).toHaveAttribute(
|
||||
'href',
|
||||
'https://antoniolede.de/leistungen/ai-integration',
|
||||
);
|
||||
await expect(page.locator('script[type="application/ld+json"]')).toHaveCount(1);
|
||||
});
|
||||
});
|
||||
66
e2e/systems-map.e2e.ts
Normal file
66
e2e/systems-map.e2e.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { pagePath } from './helpers';
|
||||
|
||||
test.describe('Systems Map', () => {
|
||||
test('keeps the card list visible and shows the SVG from 1024px', async ({ page }) => {
|
||||
await page.goto(pagePath('home', 'de'));
|
||||
|
||||
for (const width of [390, 768, 1024, 1440]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
const list = page.locator('.systems-map-list');
|
||||
await expect(list).toBeVisible();
|
||||
await expect(list.locator('.systems-map-cards li')).toHaveCount(8);
|
||||
|
||||
const figure = page.locator('.systems-map-figure');
|
||||
if (width < 1024) {
|
||||
await expect(figure).toBeHidden();
|
||||
} else {
|
||||
await expect(figure).toBeVisible();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('keeps SVG labels inside their shapes at 1024 and 1440', async ({ page }) => {
|
||||
await page.goto(pagePath('home', 'de'));
|
||||
|
||||
for (const width of [1024, 1440]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
const overflow = await page.evaluate(() => {
|
||||
const nodes = Array.from(document.querySelectorAll<SVGGElement>('.systems-map-node'));
|
||||
return nodes.flatMap((node) => {
|
||||
const shape = node.querySelector('circle, rect');
|
||||
const text = node.querySelector('text');
|
||||
if (!shape || !text) {
|
||||
return [`${node.getAttribute('aria-label') ?? 'node'} missing shape or text`];
|
||||
}
|
||||
|
||||
const shapeBox = (shape as SVGGraphicsElement).getBBox();
|
||||
const textBox = (text as SVGGraphicsElement).getBBox();
|
||||
const fits =
|
||||
textBox.x >= shapeBox.x - 0.5 &&
|
||||
textBox.y >= shapeBox.y - 0.5 &&
|
||||
textBox.x + textBox.width <= shapeBox.x + shapeBox.width + 0.5 &&
|
||||
textBox.y + textBox.height <= shapeBox.y + shapeBox.height + 0.5;
|
||||
|
||||
return fits ? [] : [node.getAttribute('aria-label') ?? 'unnamed node'];
|
||||
});
|
||||
});
|
||||
|
||||
expect(overflow, `labels overflow at ${width}px`).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test('every SVG node points at a real route', async ({ page, request }) => {
|
||||
await page.goto(pagePath('home', 'de'));
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
const hrefs = await page
|
||||
.locator('.systems-map-node')
|
||||
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute('href') ?? ''));
|
||||
|
||||
expect(hrefs.length).toBeGreaterThan(0);
|
||||
for (const href of hrefs) {
|
||||
const response = await request.get(href);
|
||||
expect(response.status(), href).toBe(200);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -6,10 +6,19 @@ const prettier = require('eslint-config-prettier');
|
||||
|
||||
module.exports = tseslint.config(
|
||||
{
|
||||
ignores: ['dist/**', '.angular/**', 'node_modules/**', 'coverage/**'],
|
||||
ignores: [
|
||||
'dist/**',
|
||||
'.angular/**',
|
||||
'node_modules/**',
|
||||
'coverage/**',
|
||||
'playwright-report/**',
|
||||
'test-results/**',
|
||||
'.lighthouseci/**',
|
||||
],
|
||||
},
|
||||
{
|
||||
files: ['**/*.ts'],
|
||||
ignores: ['e2e/**/*.ts', 'playwright.config.ts'],
|
||||
extends: [
|
||||
eslint.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
@@ -39,5 +48,15 @@ module.exports = tseslint.config(
|
||||
files: ['**/*.html'],
|
||||
extends: [...angular.configs.templateRecommended, ...angular.configs.templateAccessibility],
|
||||
},
|
||||
{
|
||||
files: ['e2e/**/*.ts', 'playwright.config.ts'],
|
||||
extends: [eslint.configs.recommended, ...tseslint.configs.recommended],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: './tsconfig.e2e.json',
|
||||
tsconfigRootDir: __dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
prettier,
|
||||
);
|
||||
|
||||
31
lighthouserc.json
Normal file
31
lighthouserc.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"ci": {
|
||||
"collect": {
|
||||
"startServerCommand": "npm run serve:ssr",
|
||||
"startServerReadyPattern": "Node Express server listening",
|
||||
"url": [
|
||||
"http://127.0.0.1:4000/",
|
||||
"http://127.0.0.1:4000/en",
|
||||
"http://127.0.0.1:4000/leistungen/ai-integration",
|
||||
"http://127.0.0.1:4000/en/projects"
|
||||
],
|
||||
"numberOfRuns": 3,
|
||||
"settings": {
|
||||
"preset": "desktop",
|
||||
"chromeFlags": "--no-sandbox --headless=new"
|
||||
}
|
||||
},
|
||||
"assert": {
|
||||
"assertions": {
|
||||
"categories:performance": ["error", { "minScore": 0.85 }],
|
||||
"categories:accessibility": ["error", { "minScore": 1 }],
|
||||
"categories:best-practices": ["error", { "minScore": 1 }],
|
||||
"categories:seo": ["error", { "minScore": 1 }]
|
||||
}
|
||||
},
|
||||
"upload": {
|
||||
"target": "filesystem",
|
||||
"outputDir": ".lighthouseci"
|
||||
}
|
||||
}
|
||||
}
|
||||
3177
package-lock.json
generated
3177
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -14,7 +14,10 @@
|
||||
"format:check": "prettier --check .",
|
||||
"serve:ssr": "node dist/Portfolio/server/server.mjs",
|
||||
"serve:ssr:Portfolio": "node dist/Portfolio/server/server.mjs",
|
||||
"ci": "npm run lint && npm run format:check && npm run test:ci && npm run build"
|
||||
"ci": "npm run lint && npm run format:check && npm run test:ci && npm run build",
|
||||
"e2e": "playwright test",
|
||||
"e2e:install": "playwright install chromium",
|
||||
"lighthouse": "npm run build && lhci autorun"
|
||||
},
|
||||
"prettier": {
|
||||
"printWidth": 100,
|
||||
@@ -47,10 +50,14 @@
|
||||
"@angular/build": "^21.0.5",
|
||||
"@angular/cli": "^21.0.5",
|
||||
"@angular/compiler-cli": "^21.0.0",
|
||||
"@axe-core/playwright": "^4.13.0",
|
||||
"@eslint/js": "^9.39.5",
|
||||
"@lhci/cli": "^0.15.1",
|
||||
"@playwright/test": "1.62.1",
|
||||
"@types/express": "^5.0.1",
|
||||
"@types/node": "^20.17.19",
|
||||
"angular-eslint": "^21.4.0",
|
||||
"axe-core": "^4.13.0",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"jsdom": "^27.1.0",
|
||||
|
||||
40
playwright.config.ts
Normal file
40
playwright.config.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
testMatch: '**/*.e2e.ts',
|
||||
forbidOnly: !!process.env['CI'],
|
||||
retries: 0,
|
||||
workers: 1,
|
||||
reporter: [['list'], ['html', { open: 'never' }]],
|
||||
use: {
|
||||
baseURL: 'http://127.0.0.1:4173',
|
||||
screenshot: 'only-on-failure',
|
||||
trace: 'retain-on-failure',
|
||||
},
|
||||
webServer: {
|
||||
command: 'npm run build && npm run serve:ssr',
|
||||
url: 'http://127.0.0.1:4173',
|
||||
env: { PORT: '4173' },
|
||||
timeout: 300_000,
|
||||
reuseExistingServer: !process.env['CI'],
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
name: 'desktop',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
viewport: { width: 1440, height: 900 },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'mobile',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
viewport: { width: 390, height: 844 },
|
||||
hasTouch: true,
|
||||
isMobile: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
51
public/llms.txt
Normal file
51
public/llms.txt
Normal file
@@ -0,0 +1,51 @@
|
||||
# Antonio Ledebuhr
|
||||
|
||||
Fullstack and DevOps engineer in Tangermünde. The public site documents a curated set of stations, four service areas, and a local mailto briefing. German is the default language; English is the full second version.
|
||||
|
||||
## Profile
|
||||
|
||||
- https://antoniolede.de/
|
||||
- https://antoniolede.de/en
|
||||
- https://antoniolede.de/ueber-mich
|
||||
- https://antoniolede.de/en/about
|
||||
|
||||
## Services
|
||||
|
||||
- https://antoniolede.de/leistungen
|
||||
- https://antoniolede.de/en/services
|
||||
- https://antoniolede.de/leistungen/software
|
||||
- https://antoniolede.de/en/services/software
|
||||
- https://antoniolede.de/leistungen/hardware-netzwerk
|
||||
- https://antoniolede.de/en/services/hardware-network
|
||||
- https://antoniolede.de/leistungen/cluster
|
||||
- https://antoniolede.de/en/services/clusters
|
||||
- https://antoniolede.de/leistungen/ai-integration
|
||||
- https://antoniolede.de/en/services/ai-integration
|
||||
|
||||
## Projects
|
||||
|
||||
- https://antoniolede.de/projekte
|
||||
- https://antoniolede.de/en/projects
|
||||
- https://antoniolede.de/projekte#innofocus
|
||||
- https://antoniolede.de/en/projects#innofocus
|
||||
- https://antoniolede.de/projekte#roesterei
|
||||
- https://antoniolede.de/en/projects#roesterei
|
||||
- https://antoniolede.de/projekte#myspa
|
||||
- https://antoniolede.de/en/projects#myspa
|
||||
- https://antoniolede.de/projekte#hdi
|
||||
- https://antoniolede.de/en/projects#hdi
|
||||
|
||||
## Contact, stack and legal
|
||||
|
||||
- https://antoniolede.de/kontakt
|
||||
- https://antoniolede.de/en/contact
|
||||
- https://antoniolede.de/stack
|
||||
- https://antoniolede.de/en/stack
|
||||
- https://antoniolede.de/impressum
|
||||
- https://antoniolede.de/en/legal-notice
|
||||
- https://antoniolede.de/datenschutz
|
||||
- https://antoniolede.de/en/privacy
|
||||
|
||||
## Languages
|
||||
|
||||
German URLs are unprefixed. English URLs live under `/en`. Each public page exists in both locales.
|
||||
4
public/robots.txt
Normal file
4
public/robots.txt
Normal file
@@ -0,0 +1,4 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
|
||||
Sitemap: https://antoniolede.de/sitemap.xml
|
||||
147
public/sitemap.xml
Normal file
147
public/sitemap.xml
Normal file
@@ -0,0 +1,147 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
|
||||
<url>
|
||||
<loc>https://antoniolede.de/</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/leistungen</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/leistungen/software</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen/software" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services/software" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen/software" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/leistungen/hardware-netzwerk</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen/hardware-netzwerk" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services/hardware-network" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen/hardware-netzwerk" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/leistungen/cluster</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen/cluster" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services/clusters" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen/cluster" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/leistungen/ai-integration</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen/ai-integration" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services/ai-integration" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen/ai-integration" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/projekte</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/projekte" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/projects" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/projekte" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/stack</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/stack" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/stack" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/stack" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/ueber-mich</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/ueber-mich" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/about" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/ueber-mich" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/kontakt</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/kontakt" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/contact" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/kontakt" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/impressum</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/impressum" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/legal-notice" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/impressum" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/datenschutz</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/datenschutz" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/privacy" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/datenschutz" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/services</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/services/software</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen/software" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services/software" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen/software" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/services/hardware-network</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen/hardware-netzwerk" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services/hardware-network" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen/hardware-netzwerk" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/services/clusters</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen/cluster" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services/clusters" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen/cluster" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/services/ai-integration</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/leistungen/ai-integration" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/services/ai-integration" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/leistungen/ai-integration" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/projects</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/projekte" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/projects" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/projekte" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/stack</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/stack" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/stack" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/stack" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/about</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/ueber-mich" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/about" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/ueber-mich" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/contact</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/kontakt" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/contact" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/kontakt" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/legal-notice</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/impressum" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/legal-notice" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/impressum" />
|
||||
</url>
|
||||
<url>
|
||||
<loc>https://antoniolede.de/en/privacy</loc>
|
||||
<xhtml:link rel="alternate" hreflang="de-DE" href="https://antoniolede.de/datenschutz" />
|
||||
<xhtml:link rel="alternate" hreflang="en" href="https://antoniolede.de/en/privacy" />
|
||||
<xhtml:link rel="alternate" hreflang="x-default" href="https://antoniolede.de/datenschutz" />
|
||||
</url>
|
||||
</urlset>
|
||||
@@ -1,9 +1,15 @@
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
import { provideRouter, withComponentInputBinding, withInMemoryScrolling } from '@angular/router';
|
||||
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
|
||||
import {
|
||||
provideRouter,
|
||||
TitleStrategy,
|
||||
withComponentInputBinding,
|
||||
withInMemoryScrolling,
|
||||
} from '@angular/router';
|
||||
import { routes } from './app.routes';
|
||||
import { SITE_CONTENT } from './core/content/content.token';
|
||||
import { SITE_CONTENT_DATA } from './core/content/site-content';
|
||||
import { routes } from './app.routes';
|
||||
import { SeoTitleStrategy } from './core/seo/seo-title.strategy';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
@@ -18,5 +24,6 @@ export const appConfig: ApplicationConfig = {
|
||||
),
|
||||
provideClientHydration(withEventReplay()),
|
||||
{ provide: SITE_CONTENT, useValue: SITE_CONTENT_DATA },
|
||||
{ provide: TitleStrategy, useClass: SeoTitleStrategy },
|
||||
],
|
||||
};
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
<a class="skip-link" href="#main-content">{{ shell().skipLink }}</a>
|
||||
<app-dot-background aria-hidden="true"></app-dot-background>
|
||||
<div class="site" [class.nav-collapsed]="!navOpen()">
|
||||
<div class="site" [class.nav-collapsed]="!navOpen()" [attr.inert]="palette.open() ? '' : null">
|
||||
<header class="site-header">
|
||||
<div class="content-container site-header-inner glass-surface">
|
||||
<a class="site-identity" [routerLink]="navigation.link('home')">
|
||||
{{ siteConfig.personName }}
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
class="nav-toggle"
|
||||
[attr.aria-expanded]="navOpen()"
|
||||
aria-controls="primary-nav"
|
||||
[attr.aria-label]="menuLabel()"
|
||||
(click)="toggleNav()"
|
||||
>
|
||||
<span aria-hidden="true"></span>
|
||||
</button>
|
||||
<div class="site-toolbar cluster">
|
||||
<app-command-palette-trigger></app-command-palette-trigger>
|
||||
<button
|
||||
type="button"
|
||||
class="nav-toggle"
|
||||
[attr.aria-expanded]="navOpen()"
|
||||
aria-controls="primary-nav"
|
||||
[attr.aria-label]="menuLabel()"
|
||||
(click)="toggleNav()"
|
||||
>
|
||||
<span aria-hidden="true"></span>
|
||||
</button>
|
||||
</div>
|
||||
<nav class="site-nav" [attr.aria-label]="shell().primaryNavLabel">
|
||||
<ul class="primary-nav" id="primary-nav">
|
||||
@for (item of navigation.primaryNav(); track item.routeId) {
|
||||
@@ -28,7 +31,7 @@
|
||||
>{{ item.label }}</a
|
||||
>
|
||||
@if (item.children; as children) {
|
||||
<ul>
|
||||
<ul class="submenu">
|
||||
@for (child of children; track child.routeId) {
|
||||
<li>
|
||||
<a
|
||||
@@ -91,3 +94,4 @@
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
<app-command-palette></app-command-palette>
|
||||
|
||||
19
src/app/app.routes.server.spec.ts
Normal file
19
src/app/app.routes.server.spec.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { RenderMode } from '@angular/ssr';
|
||||
import { serverRoutes } from './app.routes.server';
|
||||
|
||||
describe('server routes', () => {
|
||||
it('returns HTTP 404 from the catch-all and leaves prerendered routes without a status', () => {
|
||||
const catchAll = serverRoutes.find((route) => route.path === '**');
|
||||
|
||||
expect(catchAll?.renderMode).toBe(RenderMode.Server);
|
||||
expect(catchAll && 'status' in catchAll ? catchAll.status : undefined).toBe(404);
|
||||
|
||||
const prerendered = serverRoutes.filter((route) => route.path !== '**');
|
||||
expect(prerendered.length).toBeGreaterThan(0);
|
||||
|
||||
for (const route of prerendered) {
|
||||
expect(route.renderMode, route.path).toBe(RenderMode.Prerender);
|
||||
expect('status' in route, `${route.path} must not set status`).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -9,5 +9,6 @@ export const serverRoutes: ServerRoute[] = [
|
||||
{
|
||||
path: '**',
|
||||
renderMode: RenderMode.Server,
|
||||
status: 404,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
}
|
||||
|
||||
.site-header {
|
||||
position: sticky;
|
||||
position: relative;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
padding-block: var(--space-3);
|
||||
@@ -37,14 +37,34 @@
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.site-identity,
|
||||
.site-nav a,
|
||||
.site-actions a,
|
||||
.site-footer a,
|
||||
.nav-toggle {
|
||||
min-height: 2.75rem;
|
||||
}
|
||||
|
||||
.site-identity,
|
||||
.site-nav a,
|
||||
.site-actions a,
|
||||
.site-footer a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.site-identity {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.nav-toggle {
|
||||
.site-toolbar {
|
||||
justify-self: end;
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.nav-toggle {
|
||||
width: 2.75rem;
|
||||
height: 2.75rem;
|
||||
border: 1px solid var(--surface-glass-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
@@ -116,7 +136,11 @@
|
||||
|
||||
.site-main {
|
||||
flex: 1;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.site-main:focus-visible {
|
||||
outline: var(--focus-ring-width) solid var(--focus-ring-color);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
}
|
||||
|
||||
.site-footer {
|
||||
@@ -137,27 +161,70 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
.site-header {
|
||||
padding-block: var(--space-2);
|
||||
}
|
||||
|
||||
.site-header-inner {
|
||||
grid-template-columns: auto 1fr auto;
|
||||
grid-template-columns: 1fr auto auto;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding-block: var(--space-2);
|
||||
}
|
||||
|
||||
.site-nav,
|
||||
.nav-collapsed .site-nav {
|
||||
display: flex;
|
||||
grid-column: 1 / -1;
|
||||
order: 5;
|
||||
}
|
||||
|
||||
.site-actions,
|
||||
.nav-collapsed .site-nav,
|
||||
.nav-collapsed .site-actions {
|
||||
display: flex;
|
||||
grid-column: auto;
|
||||
order: 3;
|
||||
}
|
||||
|
||||
.site-toolbar {
|
||||
order: 2;
|
||||
}
|
||||
|
||||
.primary-nav {
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-4);
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.primary-nav ul {
|
||||
padding-inline-start: 0;
|
||||
.primary-nav > li {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.primary-nav > li > a {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.primary-nav > li > .submenu {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
min-width: max-content;
|
||||
z-index: 20;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
gap: var(--space-1);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--surface-glass);
|
||||
backdrop-filter: blur(var(--blur-glass));
|
||||
-webkit-backdrop-filter: blur(var(--blur-glass));
|
||||
border: 1px solid var(--surface-glass-border);
|
||||
box-shadow: var(--shadow-soft);
|
||||
}
|
||||
|
||||
.primary-nav > li:hover > .submenu,
|
||||
.primary-nav > li:focus-within > .submenu {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,67 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { App } from './app';
|
||||
import { ApplicationRef, PLATFORM_ID } from '@angular/core';
|
||||
import { TestBed, type ComponentFixture } from '@angular/core/testing';
|
||||
import { provideRouter, Router, TitleStrategy } from '@angular/router';
|
||||
import { App, WIDE_NAV_QUERY } from './app';
|
||||
import { routes } from './app.routes';
|
||||
import { SITE_CONTENT } from './core/content/content.token';
|
||||
import { SITE_CONTENT_DATA } from './core/content/site-content';
|
||||
import { SeoTitleStrategy } from './core/seo/seo-title.strategy';
|
||||
|
||||
function mockViewport(wide: boolean): void {
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: (query: string): MediaQueryList =>
|
||||
({
|
||||
matches: wide && query === WIDE_NAV_QUERY,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
}) as MediaQueryList,
|
||||
});
|
||||
}
|
||||
|
||||
async function configureApp(
|
||||
extraProviders: { provide: unknown; useValue: unknown }[] = [],
|
||||
): Promise<void> {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [App],
|
||||
providers: [
|
||||
provideRouter(routes),
|
||||
{ provide: SITE_CONTENT, useValue: SITE_CONTENT_DATA },
|
||||
{ provide: TitleStrategy, useClass: SeoTitleStrategy },
|
||||
...extraProviders,
|
||||
],
|
||||
}).compileComponents();
|
||||
}
|
||||
|
||||
async function flush(fixture: ComponentFixture<App>): Promise<void> {
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
TestBed.inject(ApplicationRef).tick();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
}
|
||||
|
||||
function toggle(root: HTMLElement): HTMLButtonElement {
|
||||
return root.querySelector('.nav-toggle') as HTMLButtonElement;
|
||||
}
|
||||
|
||||
describe('App', () => {
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
|
||||
mockViewport(true);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [App],
|
||||
providers: [provideRouter(routes), { provide: SITE_CONTENT, useValue: SITE_CONTENT_DATA }],
|
||||
}).compileComponents();
|
||||
await configureApp();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
Reflect.deleteProperty(window, 'matchMedia');
|
||||
});
|
||||
|
||||
it('should create the shell', async () => {
|
||||
@@ -43,4 +88,83 @@ describe('App', () => {
|
||||
expect(compiled.querySelector('a.language-switch[hreflang]')).toBeTruthy();
|
||||
expect(compiled.querySelector('footer')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('keeps the palette trigger in the header and the dialog outside .site', async () => {
|
||||
const fixture = TestBed.createComponent(App);
|
||||
await fixture.whenStable();
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
const site = compiled.querySelector('.site');
|
||||
const trigger = compiled.querySelector('header .command-palette-trigger');
|
||||
|
||||
expect(site).toBeTruthy();
|
||||
expect(trigger).toBeTruthy();
|
||||
expect(site?.contains(trigger)).toBe(true);
|
||||
|
||||
(trigger as HTMLButtonElement).click();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
TestBed.inject(ApplicationRef).tick();
|
||||
fixture.detectChanges();
|
||||
|
||||
const dialog = compiled.querySelector('[role="dialog"]');
|
||||
expect(dialog).toBeTruthy();
|
||||
expect(site?.contains(dialog)).toBe(false);
|
||||
expect(site?.hasAttribute('inert')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the server-rendered nav expanded and collapses after hydration on a narrow viewport', async () => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
|
||||
mockViewport(false);
|
||||
await configureApp();
|
||||
|
||||
const fixture = TestBed.createComponent(App);
|
||||
const shell = fixture.componentInstance as unknown as { navOpen: () => boolean };
|
||||
expect(shell.navOpen()).toBe(true);
|
||||
|
||||
await flush(fixture);
|
||||
const button = toggle(fixture.nativeElement);
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(button.getAttribute('aria-controls')).toBe('primary-nav');
|
||||
expect(button.getAttribute('aria-label')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('.site')?.classList.contains('nav-collapsed')).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('does not collapse the nav on the server even when the viewport helper would be narrow', async () => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
|
||||
mockViewport(false);
|
||||
await configureApp([{ provide: PLATFORM_ID, useValue: 'server' }]);
|
||||
|
||||
const fixture = TestBed.createComponent(App);
|
||||
await flush(fixture);
|
||||
|
||||
expect(toggle(fixture.nativeElement).getAttribute('aria-expanded')).toBe('true');
|
||||
expect(fixture.nativeElement.querySelector('.site')?.classList.contains('nav-collapsed')).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('closes the nav on navigation when the viewport is narrow', async () => {
|
||||
TestBed.resetTestingModule();
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
|
||||
mockViewport(false);
|
||||
await configureApp();
|
||||
|
||||
const fixture = TestBed.createComponent(App);
|
||||
await flush(fixture);
|
||||
|
||||
const button = toggle(fixture.nativeElement);
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
button.click();
|
||||
fixture.detectChanges();
|
||||
expect(button.getAttribute('aria-expanded')).toBe('true');
|
||||
|
||||
await TestBed.inject(Router).navigateByUrl('/projekte');
|
||||
await flush(fixture);
|
||||
|
||||
expect(toggle(fixture.nativeElement).getAttribute('aria-expanded')).toBe('false');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,22 +1,54 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
|
||||
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
|
||||
import { DOCUMENT, ViewportScroller } from '@angular/common';
|
||||
import {
|
||||
afterNextRender,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
inject,
|
||||
Injector,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { NavigationEnd, Router, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
|
||||
import { filter } from 'rxjs';
|
||||
import { DotBackground } from './components/dot-background/dot-background';
|
||||
import { SHELL_COPY } from './core/content/shell-copy';
|
||||
import { SITE_CONFIG } from './core/content/site-config';
|
||||
import { LOCALE_HTML_LANG, otherLocale } from './core/i18n/locale';
|
||||
import { LocaleService } from './core/i18n/locale.service';
|
||||
import { NavigationService } from './core/navigation/navigation.service';
|
||||
import { isBrowserPlatform, viewportMatches } from './core/platform/browser';
|
||||
import { CommandPalette } from './shared/command-palette/command-palette';
|
||||
import { CommandPaletteTrigger } from './shared/command-palette/command-palette-trigger/command-palette-trigger';
|
||||
import { CommandPaletteService } from './shared/command-palette/command-palette.service';
|
||||
|
||||
/** Matches `md` in `src/_breakpoints.scss` (48rem). */
|
||||
export const WIDE_NAV_QUERY = '(min-width: 48rem)';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [RouterOutlet, RouterLink, RouterLinkActive, DotBackground],
|
||||
imports: [
|
||||
RouterOutlet,
|
||||
RouterLink,
|
||||
RouterLinkActive,
|
||||
DotBackground,
|
||||
CommandPalette,
|
||||
CommandPaletteTrigger,
|
||||
],
|
||||
templateUrl: './app.html',
|
||||
styleUrl: './app.scss',
|
||||
})
|
||||
export class App {
|
||||
protected readonly navigation = inject(NavigationService);
|
||||
protected readonly localeService = inject(LocaleService);
|
||||
protected readonly palette = inject(CommandPaletteService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private readonly viewportScroller = inject(ViewportScroller);
|
||||
private readonly isBrowser = isBrowserPlatform();
|
||||
private readonly wideNav = viewportMatches(WIDE_NAV_QUERY);
|
||||
protected readonly siteConfig = SITE_CONFIG;
|
||||
protected readonly navOpen = signal(true);
|
||||
|
||||
@@ -27,7 +59,61 @@ export class App {
|
||||
this.navOpen() ? this.shell().menuClose : this.shell().menuOpen,
|
||||
);
|
||||
|
||||
constructor() {
|
||||
afterNextRender(
|
||||
() => {
|
||||
this.collapseNavIfNarrow();
|
||||
this.bindHeaderScrollOffset();
|
||||
},
|
||||
{ injector: this.injector },
|
||||
);
|
||||
|
||||
this.router.events
|
||||
.pipe(
|
||||
filter((event): event is NavigationEnd => event instanceof NavigationEnd),
|
||||
takeUntilDestroyed(),
|
||||
)
|
||||
.subscribe(() => this.collapseNavIfNarrow());
|
||||
}
|
||||
|
||||
protected toggleNav(): void {
|
||||
this.navOpen.update((open) => !open);
|
||||
}
|
||||
|
||||
private collapseNavIfNarrow(): void {
|
||||
if (!this.isBrowser || this.wideNav) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.navOpen.set(false);
|
||||
}
|
||||
|
||||
private bindHeaderScrollOffset(): void {
|
||||
if (!this.isBrowser) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.viewportScroller.setOffset(() => [0, this.headerOffsetPx()]);
|
||||
}
|
||||
|
||||
private headerOffsetPx(): number {
|
||||
const view = this.document.defaultView;
|
||||
if (!view) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const styles = view.getComputedStyle(this.document.documentElement);
|
||||
const raw = styles.getPropertyValue('--header-offset').trim();
|
||||
const numeric = Number.parseFloat(raw);
|
||||
if (!Number.isFinite(numeric)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (raw.endsWith('rem')) {
|
||||
const rootSize = Number.parseFloat(styles.fontSize);
|
||||
return numeric * (Number.isFinite(rootSize) ? rootSize : 16);
|
||||
}
|
||||
|
||||
return numeric;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,53 +1,281 @@
|
||||
import { ApplicationRef } from '@angular/core';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { DotBackground } from './dot-background';
|
||||
|
||||
function mockContext(): CanvasRenderingContext2D {
|
||||
const gradient = { addColorStop: vi.fn() };
|
||||
|
||||
return {
|
||||
clearRect: vi.fn(),
|
||||
beginPath: vi.fn(),
|
||||
arc: vi.fn(),
|
||||
fill: vi.fn(),
|
||||
createRadialGradient: vi.fn(() => gradient),
|
||||
} as unknown as CanvasRenderingContext2D;
|
||||
}
|
||||
|
||||
function mockMatchMedia(matchesQuery: (query: string) => boolean): void {
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: (query: string): MediaQueryList =>
|
||||
({
|
||||
matches: matchesQuery(query),
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
}) as MediaQueryList,
|
||||
});
|
||||
}
|
||||
|
||||
describe('DotBackground', () => {
|
||||
let component: DotBackground;
|
||||
let fixture: ComponentFixture<DotBackground>;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
Reflect.deleteProperty(window, 'matchMedia');
|
||||
Object.defineProperty(document, 'hidden', {
|
||||
configurable: true,
|
||||
get: () => false,
|
||||
});
|
||||
});
|
||||
|
||||
async function createFixture(): Promise<ComponentFixture<DotBackground>> {
|
||||
TestBed.resetTestingModule();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [DotBackground],
|
||||
}).compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(DotBackground);
|
||||
component = fixture.componentInstance;
|
||||
const fixture = TestBed.createComponent(DotBackground);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
});
|
||||
TestBed.inject(ApplicationRef).tick();
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
it('should create', async () => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
const fixture = await createFixture();
|
||||
expect(fixture.componentInstance).toBeTruthy();
|
||||
});
|
||||
|
||||
it('does not throw when destroyed after browser initialization', async () => {
|
||||
const gradient = { addColorStop: vi.fn() };
|
||||
const context = {
|
||||
clearRect: vi.fn(),
|
||||
beginPath: vi.fn(),
|
||||
arc: vi.fn(),
|
||||
fill: vi.fn(),
|
||||
createRadialGradient: vi.fn(() => gradient),
|
||||
};
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(mockContext());
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(1);
|
||||
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(
|
||||
context as unknown as CanvasRenderingContext2D,
|
||||
const fixture = await createFixture();
|
||||
expect(() => fixture.destroy()).not.toThrow();
|
||||
});
|
||||
|
||||
it('adds no listener and schedules no animation frame when the 2D context is null', async () => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
|
||||
const scheduled: FrameRequestCallback[] = [];
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
|
||||
scheduled.push(callback);
|
||||
return scheduled.length;
|
||||
});
|
||||
const windowAdd = vi.spyOn(window, 'addEventListener');
|
||||
const documentAdd = vi.spyOn(document, 'addEventListener');
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [DotBackground],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(DotBackground);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
TestBed.inject(ApplicationRef).tick();
|
||||
|
||||
const pending = scheduled.splice(0);
|
||||
for (const callback of pending) {
|
||||
callback(0);
|
||||
}
|
||||
|
||||
expect(scheduled).toEqual([]);
|
||||
expect(windowAdd.mock.calls.some((call) => call[0] === 'resize')).toBe(false);
|
||||
expect(windowAdd.mock.calls.some((call) => call[0] === 'mousemove')).toBe(false);
|
||||
expect(windowAdd.mock.calls.some((call) => call[0] === 'click')).toBe(false);
|
||||
expect(documentAdd.mock.calls.some((call) => call[0] === 'visibilitychange')).toBe(false);
|
||||
expect(() => fixture.destroy()).not.toThrow();
|
||||
});
|
||||
|
||||
it('cancels the scheduled frame and removes every listener on destroy', async () => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(mockContext());
|
||||
const raf = vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(17);
|
||||
const cancel = vi.spyOn(window, 'cancelAnimationFrame');
|
||||
const windowAdd = vi.spyOn(window, 'addEventListener');
|
||||
const windowRemove = vi.spyOn(window, 'removeEventListener');
|
||||
const documentAdd = vi.spyOn(document, 'addEventListener');
|
||||
const documentRemove = vi.spyOn(document, 'removeEventListener');
|
||||
|
||||
const fixture = await createFixture();
|
||||
|
||||
expect(raf).toHaveBeenCalled();
|
||||
|
||||
const windowAdds = windowAdd.mock.calls.filter((call) =>
|
||||
['resize', 'mousemove', 'click'].includes(String(call[0])),
|
||||
);
|
||||
const animationFrameSpy = vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(0);
|
||||
const documentAdds = documentAdd.mock.calls.filter((call) => call[0] === 'visibilitychange');
|
||||
|
||||
const initializedFixture = TestBed.createComponent(DotBackground);
|
||||
initializedFixture.detectChanges();
|
||||
await initializedFixture.whenStable();
|
||||
expect(windowAdds.length).toBeGreaterThan(0);
|
||||
expect(documentAdds.length).toBeGreaterThan(0);
|
||||
|
||||
expect(() => initializedFixture.destroy()).not.toThrow();
|
||||
fixture.destroy();
|
||||
|
||||
animationFrameSpy.mockRestore();
|
||||
vi.restoreAllMocks();
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
|
||||
for (const [type, handler] of windowAdds) {
|
||||
expect(windowRemove).toHaveBeenCalledWith(type, handler);
|
||||
}
|
||||
|
||||
for (const [type, handler] of documentAdds) {
|
||||
expect(documentRemove).toHaveBeenCalledWith(type, handler);
|
||||
}
|
||||
});
|
||||
|
||||
it('draws a single static frame under reduced motion and skips pointer listeners', async () => {
|
||||
mockMatchMedia((query) => query.includes('prefers-reduced-motion'));
|
||||
const context = mockContext();
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context);
|
||||
const scheduled: FrameRequestCallback[] = [];
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
|
||||
scheduled.push(callback);
|
||||
return scheduled.length;
|
||||
});
|
||||
const windowAdd = vi.spyOn(window, 'addEventListener');
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [DotBackground],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(DotBackground);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
TestBed.inject(ApplicationRef).tick();
|
||||
|
||||
const pending = scheduled.splice(0);
|
||||
for (const callback of pending) {
|
||||
callback(0);
|
||||
}
|
||||
|
||||
expect(context.clearRect).toHaveBeenCalled();
|
||||
expect(scheduled).toEqual([]);
|
||||
expect(windowAdd.mock.calls.some((call) => call[0] === 'mousemove')).toBe(false);
|
||||
expect(windowAdd.mock.calls.some((call) => call[0] === 'click')).toBe(false);
|
||||
fixture.destroy();
|
||||
});
|
||||
|
||||
it('registers no pointer listeners for a coarse pointer', async () => {
|
||||
mockMatchMedia((query) => query.includes('pointer: coarse'));
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(mockContext());
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(1);
|
||||
const windowAdd = vi.spyOn(window, 'addEventListener');
|
||||
|
||||
await createFixture();
|
||||
|
||||
expect(windowAdd.mock.calls.some((call) => call[0] === 'mousemove')).toBe(false);
|
||||
expect(windowAdd.mock.calls.some((call) => call[0] === 'click')).toBe(false);
|
||||
expect(windowAdd.mock.calls.some((call) => call[0] === 'resize')).toBe(true);
|
||||
});
|
||||
|
||||
it('pauses the loop when the document is hidden and resumes when it is visible', async () => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(mockContext());
|
||||
const raf = vi.spyOn(window, 'requestAnimationFrame').mockReturnValue(21);
|
||||
const cancel = vi.spyOn(window, 'cancelAnimationFrame');
|
||||
|
||||
await createFixture();
|
||||
expect(raf).toHaveBeenCalled();
|
||||
raf.mockClear();
|
||||
|
||||
Object.defineProperty(document, 'hidden', {
|
||||
configurable: true,
|
||||
get: () => true,
|
||||
});
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
|
||||
expect(cancel).toHaveBeenCalled();
|
||||
|
||||
Object.defineProperty(document, 'hidden', {
|
||||
configurable: true,
|
||||
get: () => false,
|
||||
});
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
|
||||
expect(raf).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('starts with a bounded initial dot count on a large desktop viewport', async () => {
|
||||
const context = mockContext();
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context);
|
||||
const widthStub = vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(2560);
|
||||
const heightStub = vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(1440);
|
||||
const scheduled: FrameRequestCallback[] = [];
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
|
||||
scheduled.push(callback);
|
||||
return scheduled.length;
|
||||
});
|
||||
|
||||
try {
|
||||
const fixture = await createFixture();
|
||||
const pending = scheduled.splice(0);
|
||||
for (const callback of pending) {
|
||||
callback(0);
|
||||
}
|
||||
|
||||
const arcCalls = vi.mocked(context.arc).mock.calls.length;
|
||||
expect(arcCalls).toBeGreaterThanOrEqual(6);
|
||||
expect(arcCalls).toBeLessThanOrEqual(24);
|
||||
fixture.destroy();
|
||||
} finally {
|
||||
widthStub.mockRestore();
|
||||
heightStub.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('redraws the static frame after resize under reduced motion without starting a loop', async () => {
|
||||
mockMatchMedia((query) => query.includes('prefers-reduced-motion'));
|
||||
const context = mockContext();
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context);
|
||||
const scheduled: FrameRequestCallback[] = [];
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
|
||||
scheduled.push(callback);
|
||||
return scheduled.length;
|
||||
});
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [DotBackground],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(DotBackground);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
TestBed.inject(ApplicationRef).tick();
|
||||
|
||||
const pending = scheduled.splice(0);
|
||||
for (const callback of pending) {
|
||||
callback(0);
|
||||
}
|
||||
|
||||
vi.mocked(context.clearRect).mockClear();
|
||||
vi.mocked(context.arc).mockClear();
|
||||
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
|
||||
const resizeFrames = scheduled.splice(0);
|
||||
for (const callback of resizeFrames) {
|
||||
callback(0);
|
||||
}
|
||||
|
||||
expect(context.clearRect).toHaveBeenCalled();
|
||||
expect(context.arc).toHaveBeenCalled();
|
||||
expect(scheduled).toEqual([]);
|
||||
fixture.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import {
|
||||
afterNextRender,
|
||||
Component,
|
||||
DestroyRef,
|
||||
ElementRef,
|
||||
inject,
|
||||
NgZone,
|
||||
OnDestroy,
|
||||
ViewChild,
|
||||
} from '@angular/core';
|
||||
import { isBrowserPlatform, prefersCoarsePointer } from '../../core/platform/browser';
|
||||
import {
|
||||
isBrowserPlatform,
|
||||
prefersCoarsePointer,
|
||||
prefersReducedMotion,
|
||||
} from '../../core/platform/browser';
|
||||
import { Dot } from '../../models/dot';
|
||||
|
||||
@Component({
|
||||
@@ -15,21 +20,33 @@ import { Dot } from '../../models/dot';
|
||||
imports: [],
|
||||
templateUrl: './dot-background.html',
|
||||
styleUrl: './dot-background.scss',
|
||||
host: {
|
||||
'aria-hidden': 'true',
|
||||
},
|
||||
})
|
||||
export class DotBackground implements OnDestroy {
|
||||
export class DotBackground {
|
||||
@ViewChild('canvas') canvasRef!: ElementRef<HTMLCanvasElement>;
|
||||
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private readonly ngZone = inject(NgZone);
|
||||
private readonly coarsePointer = prefersCoarsePointer();
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly isBrowser = isBrowserPlatform();
|
||||
private readonly coarsePointer = prefersCoarsePointer();
|
||||
private readonly reducedMotion = prefersReducedMotion();
|
||||
|
||||
private ctx: CanvasRenderingContext2D | undefined;
|
||||
private dots: Dot[] = [];
|
||||
private mouse = { x: -1000, y: -1000 };
|
||||
private animationId = 0;
|
||||
private initialized = false;
|
||||
private resizeFrameId = 0;
|
||||
private loopActive = false;
|
||||
private tornDown = false;
|
||||
private readonly teardowns: Array<() => void> = [];
|
||||
|
||||
private readonly INIT_DOT_COUNT = 12;
|
||||
private readonly INITIAL_DOT_COUNT_MIN = 6;
|
||||
private readonly INITIAL_DOT_COUNT_MAX = 24;
|
||||
private readonly INITIAL_DOT_COUNT_MAX_COARSE = 12;
|
||||
private readonly INITIAL_DOT_AREA_DIVISOR = 130_000;
|
||||
private readonly MAX_DOT_COUNT = 100;
|
||||
private readonly MAX_DOT_COUNT_MOBILE = 40;
|
||||
private readonly COLORS = ['#6366f1', '#8b5cf6', '#a855f7', '#3b82f6'];
|
||||
@@ -39,27 +56,34 @@ export class DotBackground implements OnDestroy {
|
||||
private ballSpawnNextColor = 0;
|
||||
|
||||
constructor() {
|
||||
this.destroyRef.onDestroy(() => this.teardown());
|
||||
|
||||
afterNextRender(() => {
|
||||
this.init();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
if (!this.initialized) {
|
||||
private view(): Window | null {
|
||||
return this.document.defaultView;
|
||||
}
|
||||
|
||||
private init(): void {
|
||||
if (this.tornDown || !this.isBrowser) {
|
||||
return;
|
||||
}
|
||||
|
||||
cancelAnimationFrame(this.animationId);
|
||||
const view = this.view();
|
||||
|
||||
if (this.isBrowser) {
|
||||
window.removeEventListener('resize', this.resize);
|
||||
window.removeEventListener('mousemove', this.onMouseMove);
|
||||
window.removeEventListener('click', this.onMouseClick);
|
||||
if (!view) {
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = this.canvasRef?.nativeElement;
|
||||
|
||||
if (!canvas) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private init() {
|
||||
const canvas = this.canvasRef.nativeElement;
|
||||
let ctx: CanvasRenderingContext2D | null = null;
|
||||
|
||||
try {
|
||||
@@ -76,21 +100,113 @@ export class DotBackground implements OnDestroy {
|
||||
this.resize();
|
||||
this.initDots();
|
||||
|
||||
window.addEventListener('resize', this.resize);
|
||||
window.addEventListener('mousemove', this.onMouseMove);
|
||||
window.addEventListener('click', this.onMouseClick);
|
||||
this.listen(view, 'resize', this.onResize);
|
||||
this.listen(this.document, 'visibilitychange', this.onVisibilityChange);
|
||||
|
||||
this.initialized = true;
|
||||
this.ngZone.runOutsideAngular(() => this.animate());
|
||||
if (!this.reducedMotion && !this.coarsePointer) {
|
||||
this.listen(view, 'mousemove', this.onMouseMove);
|
||||
this.listen(view, 'click', this.onMouseClick);
|
||||
}
|
||||
|
||||
if (this.reducedMotion) {
|
||||
this.drawFrame();
|
||||
return;
|
||||
}
|
||||
|
||||
this.ngZone.runOutsideAngular(() => this.startLoop());
|
||||
}
|
||||
|
||||
private resize = () => {
|
||||
const canvas = this.canvasRef.nativeElement;
|
||||
const width = window.innerWidth;
|
||||
const height = window.innerHeight;
|
||||
private listen(target: EventTarget, type: string, handler: EventListener): void {
|
||||
target.addEventListener(type, handler);
|
||||
this.teardowns.push(() => target.removeEventListener(type, handler));
|
||||
}
|
||||
|
||||
const dx = Math.abs(width - canvas.width) / width;
|
||||
const dy = Math.abs(height - canvas.height) / height;
|
||||
private requestFrame(callback: FrameRequestCallback): number {
|
||||
const view = this.view();
|
||||
return view ? view.requestAnimationFrame(callback) : 0;
|
||||
}
|
||||
|
||||
private cancelFrame(id: number): void {
|
||||
const view = this.view();
|
||||
|
||||
if (!view || id === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
view.cancelAnimationFrame(id);
|
||||
}
|
||||
|
||||
private startLoop(): void {
|
||||
if (this.loopActive || this.reducedMotion || this.tornDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.loopActive = true;
|
||||
this.scheduleAnimate();
|
||||
}
|
||||
|
||||
private stopLoop(): void {
|
||||
this.loopActive = false;
|
||||
this.cancelFrame(this.animationId);
|
||||
this.animationId = 0;
|
||||
}
|
||||
|
||||
private scheduleAnimate(): void {
|
||||
this.animationId = this.requestFrame(this.animate);
|
||||
}
|
||||
|
||||
private teardown(): void {
|
||||
if (this.tornDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.tornDown = true;
|
||||
this.stopLoop();
|
||||
this.cancelFrame(this.resizeFrameId);
|
||||
this.resizeFrameId = 0;
|
||||
|
||||
for (const dispose of this.teardowns) {
|
||||
dispose();
|
||||
}
|
||||
|
||||
this.teardowns.length = 0;
|
||||
}
|
||||
|
||||
private onResize = (): void => {
|
||||
if (this.resizeFrameId !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.resizeFrameId = this.requestFrame(() => {
|
||||
this.resizeFrameId = 0;
|
||||
this.resize();
|
||||
});
|
||||
};
|
||||
|
||||
private onVisibilityChange = (): void => {
|
||||
if (this.document.hidden) {
|
||||
this.stopLoop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.reducedMotion) {
|
||||
this.ngZone.runOutsideAngular(() => this.startLoop());
|
||||
}
|
||||
};
|
||||
|
||||
private resize = (): void => {
|
||||
const view = this.view();
|
||||
const canvas = this.canvasRef?.nativeElement;
|
||||
|
||||
if (!view || !canvas) {
|
||||
return;
|
||||
}
|
||||
|
||||
const width = view.innerWidth;
|
||||
const height = view.innerHeight;
|
||||
|
||||
const dx = width === 0 ? 0 : Math.abs(width - canvas.width) / width;
|
||||
const dy = height === 0 ? 0 : Math.abs(height - canvas.height) / height;
|
||||
|
||||
if (!this.coarsePointer || dy > 0.2 || dx > 0.05) {
|
||||
canvas.width = width;
|
||||
@@ -100,21 +216,44 @@ export class DotBackground implements OnDestroy {
|
||||
dot.x = Math.max(dot.radius, Math.min(width - dot.radius, dot.x));
|
||||
dot.y = Math.max(dot.radius, Math.min(height - dot.radius, dot.y));
|
||||
}
|
||||
|
||||
if (this.reducedMotion && this.ctx) {
|
||||
this.drawFrame();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private onMouseMove = (e: MouseEvent) => {
|
||||
const canvas = this.canvasRef.nativeElement;
|
||||
this.mouse.x = (e.clientX / window.innerWidth) * canvas.width;
|
||||
this.mouse.y = (e.clientY / window.innerHeight) * canvas.height;
|
||||
private onMouseMove = (event: Event): void => {
|
||||
if (!(event instanceof MouseEvent)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const view = this.view();
|
||||
const canvas = this.canvasRef?.nativeElement;
|
||||
|
||||
if (!view || !canvas) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.mouse.x = (event.clientX / view.innerWidth) * canvas.width;
|
||||
this.mouse.y = (event.clientY / view.innerHeight) * canvas.height;
|
||||
};
|
||||
|
||||
private onMouseClick = () => {
|
||||
private onMouseClick = (): void => {
|
||||
const dot = this.spawnDot();
|
||||
dot.x = this.mouse.x;
|
||||
dot.y = this.mouse.y;
|
||||
};
|
||||
|
||||
private targetDotCount(width: number, height: number): number {
|
||||
const maxInitial = this.coarsePointer
|
||||
? this.INITIAL_DOT_COUNT_MAX_COARSE
|
||||
: this.INITIAL_DOT_COUNT_MAX;
|
||||
const area = Math.max(0, width) * Math.max(0, height);
|
||||
const fromArea = Math.round(area / this.INITIAL_DOT_AREA_DIVISOR);
|
||||
return Math.min(maxInitial, Math.max(this.INITIAL_DOT_COUNT_MIN, fromArea));
|
||||
}
|
||||
|
||||
private spawnDot(): Dot {
|
||||
const dotId = this.ballSpawnId++;
|
||||
const maxCount = this.coarsePointer ? this.MAX_DOT_COUNT_MOBILE : this.MAX_DOT_COUNT;
|
||||
@@ -140,7 +279,7 @@ export class DotBackground implements OnDestroy {
|
||||
return dot;
|
||||
}
|
||||
|
||||
private populateDot(dot: Dot) {
|
||||
private populateDot(dot: Dot): void {
|
||||
const { width, height } = this.canvasRef.nativeElement;
|
||||
|
||||
dot.x = Math.random() * width;
|
||||
@@ -151,17 +290,29 @@ export class DotBackground implements OnDestroy {
|
||||
dot.color = this.COLORS[this.ballSpawnNextColor++ % this.COLORS.length];
|
||||
}
|
||||
|
||||
private initDots() {
|
||||
for (let i = 0; i < this.INIT_DOT_COUNT; i++) {
|
||||
private initDots(): void {
|
||||
const { width, height } = this.canvasRef.nativeElement;
|
||||
const count = this.targetDotCount(width, height);
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
this.spawnDot();
|
||||
}
|
||||
}
|
||||
|
||||
private animate = () => {
|
||||
const canvas = this.canvasRef.nativeElement;
|
||||
private animate = (): void => {
|
||||
this.animationId = 0;
|
||||
this.drawFrame();
|
||||
|
||||
if (this.loopActive && !this.tornDown) {
|
||||
this.scheduleAnimate();
|
||||
}
|
||||
};
|
||||
|
||||
private drawFrame(): void {
|
||||
const canvas = this.canvasRef?.nativeElement;
|
||||
const ctx = this.ctx;
|
||||
|
||||
if (!ctx) {
|
||||
if (!canvas || !ctx) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -213,7 +364,5 @@ export class DotBackground implements OnDestroy {
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
this.animationId = requestAnimationFrame(this.animate);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,6 +105,10 @@ const BASE_CATEGORIES: readonly SkillCategory[] = [
|
||||
},
|
||||
];
|
||||
|
||||
export const SKILL_GRID_ITEM_NAMES: readonly string[] = BASE_CATEGORIES.flatMap((category) =>
|
||||
category.skills.map((skill) => skill.name),
|
||||
);
|
||||
|
||||
@Component({
|
||||
selector: 'app-skills-grid',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
|
||||
24
src/app/core/commands/command-ids.ts
Normal file
24
src/app/core/commands/command-ids.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
export type CommandId =
|
||||
| 'help'
|
||||
| 'projects'
|
||||
| 'servicesAi'
|
||||
| 'cv'
|
||||
| 'contact'
|
||||
| 'brew'
|
||||
| 'ignite'
|
||||
| 'rev'
|
||||
| 'clear'
|
||||
| 'close';
|
||||
|
||||
export const COMMAND_IDS: readonly CommandId[] = [
|
||||
'help',
|
||||
'projects',
|
||||
'servicesAi',
|
||||
'cv',
|
||||
'contact',
|
||||
'brew',
|
||||
'ignite',
|
||||
'rev',
|
||||
'clear',
|
||||
'close',
|
||||
];
|
||||
@@ -96,6 +96,9 @@ export interface ServiceSequenceCopy {
|
||||
export interface ServicePageCopy extends PageCopy {
|
||||
readonly sequence: ServiceSequenceCopy;
|
||||
readonly offerings: readonly OfferingCopy[];
|
||||
readonly deliveredOfferingsHeading: string;
|
||||
readonly offerOfferingsHeading: string;
|
||||
readonly offeringCaseBackedLabel: string;
|
||||
}
|
||||
|
||||
export interface AudienceEntryCopy {
|
||||
@@ -111,6 +114,10 @@ export interface HomePageCopy extends PageCopy {
|
||||
readonly metrics: readonly MetricCopy[];
|
||||
readonly audiences: readonly AudienceEntryCopy[];
|
||||
readonly featuredCaseIds: readonly CaseStudyId[];
|
||||
readonly systemsMap: {
|
||||
readonly heading: string;
|
||||
readonly intro: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type ContactFieldId =
|
||||
@@ -163,12 +170,14 @@ export interface StackGroupCopy {
|
||||
|
||||
export interface StackPageCopy extends PageCopy {
|
||||
readonly groups: readonly StackGroupCopy[];
|
||||
readonly evidenceNote: string;
|
||||
}
|
||||
|
||||
export interface CaseStudyLabels {
|
||||
readonly situation: string;
|
||||
readonly approach: string;
|
||||
readonly outcome: string;
|
||||
readonly metrics: string;
|
||||
readonly stack: string;
|
||||
readonly tags: string;
|
||||
}
|
||||
@@ -180,6 +189,12 @@ export interface ProjectsPageCopy extends PageCopy {
|
||||
export type ServicePageId =
|
||||
'servicesSoftware' | 'servicesHardwareNetwork' | 'servicesClusters' | 'servicesAi';
|
||||
|
||||
export interface SiteSeoCopy {
|
||||
readonly jobTitle: string;
|
||||
readonly professionalServiceName: string;
|
||||
readonly professionalServiceDescription: string;
|
||||
}
|
||||
|
||||
export interface SiteContent {
|
||||
readonly pages: Record<RouteId, PageCopy>;
|
||||
readonly home: HomePageCopy;
|
||||
@@ -189,4 +204,5 @@ export interface SiteContent {
|
||||
readonly projects: ProjectsPageCopy;
|
||||
readonly stack: StackPageCopy;
|
||||
readonly legal: Record<'imprint' | 'privacy', LegalPageCopy>;
|
||||
readonly seo: SiteSeoCopy;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,10 @@ export const HOME_DE: HomePageCopy = {
|
||||
},
|
||||
],
|
||||
featuredCaseIds: ['innofocus', 'roesterei', 'myspa', 'hdi'],
|
||||
systemsMap: {
|
||||
heading: 'Wie die Schichten zusammenhängen',
|
||||
intro: 'Hardware, Cluster, Software und KI-Anbindung — und wo die öffentlichen Fälle ansetzen.',
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
id: 'profile',
|
||||
|
||||
@@ -41,6 +41,7 @@ export const PROJECTS_DE: ProjectsPageCopy = {
|
||||
situation: 'Lage',
|
||||
approach: 'Vorgehen',
|
||||
outcome: 'Ergebnis',
|
||||
metrics: 'Kennzahlen',
|
||||
stack: 'Technik',
|
||||
tags: 'Schlagworte',
|
||||
},
|
||||
@@ -50,21 +51,23 @@ export const STACK_DE: StackPageCopy = {
|
||||
routeId: 'stack',
|
||||
title: 'Technik-Stack | Antonio Ledebuhr',
|
||||
description:
|
||||
'Der öffentliche Stack in sieben Gruppen: Programmierung, Datenbanken, DevOps, Betriebssysteme, Infrastructure as Code, Hypervisor und Werkzeuge.',
|
||||
'Technik-Überblick in sieben Gruppen: Programmierung, Datenbanken, DevOps, Betriebssysteme, Infrastructure as Code, Hypervisor und Werkzeuge.',
|
||||
hero: {
|
||||
headline: 'Der Stack, der auf diesen Seiten vorkommt',
|
||||
headline: 'Ein Technik-Überblick zur Einordnung',
|
||||
proof:
|
||||
'Die Gruppen gehören zur Produktarbeit in Java und Spring sowie in C# und .NET, zur Datenarbeit in SQL Server, zu Containern und Clustern und zu Servern vor Ort.',
|
||||
'Die Rasterkarte ist eine Vertrautheitsliste. Sie zeigt Technologien aus der Arbeit, ohne jeden Eintrag als öffentlichen Fall zu belegen.',
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
id: 'reading',
|
||||
headline: 'Eine Auswahl, keine Rangliste',
|
||||
body: ['Die Übersicht ist eine Auswahl aus der öffentlichen Arbeit, keine Rangliste.'],
|
||||
headline: 'Überblick, keine Rangliste',
|
||||
body: [
|
||||
'Die Übersicht ordnet Technologien nach Gruppen. Sie ist keine Rangliste und kein Nachweis, dass jeder Eintrag in einem öffentlichen Fall vorkommt.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'groups',
|
||||
headline: 'Wo die Gruppen in der Arbeit vorkommen',
|
||||
headline: 'Welche Gruppen die Arbeit berührt',
|
||||
body: [
|
||||
'Produktarbeit in Java und Spring sowie in C# und .NET, mit Angular auf der Oberfläche. Datenarbeit in SQL Server und T-SQL. Container und Cluster mit Docker, Kubernetes und Azure AKS. Pipelines in GitLab CI/CD und Azure DevOps, GitOps mit Argo CD. Server und Virtualisierung vor Ort.',
|
||||
],
|
||||
@@ -83,6 +86,8 @@ export const STACK_DE: StackPageCopy = {
|
||||
{ id: 'hyperviser', title: 'Hypervisor' },
|
||||
{ id: 'tools', title: 'Werkzeuge' },
|
||||
],
|
||||
evidenceNote:
|
||||
'In den öffentlichen Fällen sind unter anderem Angular, TypeScript, C#, .NET, Java, Spring, SQL Server, MySQL, MariaDB, Docker, Kubernetes, Azure, Azure DevOps, GitLab, Proxmox und Microsoft 365 belegt. Die übrigen Einträge der Übersicht stehen für Breite und Vertrautheit, ohne öffentlichen Referenzfall.',
|
||||
};
|
||||
|
||||
export const ABOUT_DE: PageCopy = {
|
||||
|
||||
@@ -126,6 +126,9 @@ export const SERVICES_SOFTWARE_DE: ServicePageCopy = {
|
||||
},
|
||||
},
|
||||
offerings: [],
|
||||
deliveredOfferingsHeading: 'Umgesetzte Arbeit',
|
||||
offerOfferingsHeading: 'Angebot, je Auftrag geprüft',
|
||||
offeringCaseBackedLabel: 'Belegt durch den öffentlichen Fall {case}.',
|
||||
};
|
||||
|
||||
export const SERVICES_HARDWARE_DE: ServicePageCopy = {
|
||||
@@ -208,6 +211,9 @@ export const SERVICES_HARDWARE_DE: ServicePageCopy = {
|
||||
},
|
||||
},
|
||||
offerings: [],
|
||||
deliveredOfferingsHeading: 'Umgesetzte Arbeit',
|
||||
offerOfferingsHeading: 'Angebot, je Auftrag geprüft',
|
||||
offeringCaseBackedLabel: 'Belegt durch den öffentlichen Fall {case}.',
|
||||
};
|
||||
|
||||
export const SERVICES_CLUSTERS_DE: ServicePageCopy = {
|
||||
@@ -289,6 +295,9 @@ export const SERVICES_CLUSTERS_DE: ServicePageCopy = {
|
||||
},
|
||||
},
|
||||
offerings: [],
|
||||
deliveredOfferingsHeading: 'Umgesetzte Arbeit',
|
||||
offerOfferingsHeading: 'Angebot, je Auftrag geprüft',
|
||||
offeringCaseBackedLabel: 'Belegt durch den öffentlichen Fall {case}.',
|
||||
};
|
||||
|
||||
export const SERVICES_AI_DE: ServicePageCopy = {
|
||||
@@ -421,4 +430,7 @@ export const SERVICES_AI_DE: ServicePageCopy = {
|
||||
status: 'offer',
|
||||
},
|
||||
],
|
||||
deliveredOfferingsHeading: 'Umgesetzte Arbeit',
|
||||
offerOfferingsHeading: 'Angebot, je Auftrag geprüft',
|
||||
offeringCaseBackedLabel: 'Belegt durch den öffentlichen Fall {case}.',
|
||||
};
|
||||
|
||||
@@ -34,6 +34,12 @@ export const SITE_CONTENT_DE: SiteContent = {
|
||||
imprint: IMPRINT_DE,
|
||||
privacy: PRIVACY_DE,
|
||||
},
|
||||
seo: {
|
||||
jobTitle: 'Fullstack- und DevOps-Ingenieur',
|
||||
professionalServiceName: 'Software- und DevOps-Leistungen',
|
||||
professionalServiceDescription:
|
||||
'Vier Leistungsbereiche für Produktsoftware, Infrastruktur, Cluster und KI-Anbindung — vom ersten Workshop bis zum Betrieb, mit direktem Kundenkontakt.',
|
||||
},
|
||||
pages: {
|
||||
home: HOME_DE,
|
||||
services: SERVICES_OVERVIEW_DE,
|
||||
|
||||
@@ -75,6 +75,10 @@ export const HOME_EN: HomePageCopy = {
|
||||
},
|
||||
],
|
||||
featuredCaseIds: ['innofocus', 'roesterei', 'myspa', 'hdi'],
|
||||
systemsMap: {
|
||||
heading: 'How the layers connect',
|
||||
intro: 'Hardware, clusters, software and AI integration — and where the public cases attach.',
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
id: 'profile',
|
||||
|
||||
@@ -41,6 +41,7 @@ export const PROJECTS_EN: ProjectsPageCopy = {
|
||||
situation: 'Situation',
|
||||
approach: 'Approach',
|
||||
outcome: 'Outcome',
|
||||
metrics: 'Metrics',
|
||||
stack: 'Stack',
|
||||
tags: 'Tags',
|
||||
},
|
||||
@@ -50,21 +51,23 @@ export const STACK_EN: StackPageCopy = {
|
||||
routeId: 'stack',
|
||||
title: 'Technology stack | Antonio Ledebuhr',
|
||||
description:
|
||||
'The public stack in seven groups: programming, databases, DevOps, operating systems, infrastructure as code, hypervisors and tools.',
|
||||
'A technology overview in seven groups: programming, databases, DevOps, operating systems, infrastructure as code, hypervisors and tools.',
|
||||
hero: {
|
||||
headline: 'The stack that appears on these pages',
|
||||
headline: 'A technology overview, not a proof list',
|
||||
proof:
|
||||
'The groups belong to product work in Java and Spring and in C# and .NET, to SQL Server data work, to containers and clusters, and to servers on site.',
|
||||
'The grid is a familiarity list. It shows technologies from the work without claiming a public case for every entry.',
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
id: 'reading',
|
||||
headline: 'A selection, not a ranking',
|
||||
body: ['The overview is a selection from the public work, not a ranking.'],
|
||||
headline: 'An overview, not a ranking',
|
||||
body: [
|
||||
'The grid groups technologies for orientation. It is not a ranking, and it does not claim that every entry appears in a public case.',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'groups',
|
||||
headline: 'Where the groups show up in the work',
|
||||
headline: 'Which groups the work touches',
|
||||
body: [
|
||||
'Product work in Java and Spring and in C# and .NET, with Angular on the front end. SQL Server and T-SQL data work. Containers and clusters with Docker, Kubernetes and Azure AKS. Pipelines in GitLab CI/CD and Azure DevOps, GitOps with Argo CD. Servers and virtualisation on site.',
|
||||
],
|
||||
@@ -83,6 +86,8 @@ export const STACK_EN: StackPageCopy = {
|
||||
{ id: 'hyperviser', title: 'Hypervisors' },
|
||||
{ id: 'tools', title: 'Tools' },
|
||||
],
|
||||
evidenceNote:
|
||||
'The public cases evidence items such as Angular, TypeScript, C#, .NET, Java, Spring, SQL Server, MySQL, MariaDB, Docker, Kubernetes, Azure, Azure DevOps, GitLab, Proxmox and Microsoft 365. The remaining entries show breadth and familiarity without a public reference.',
|
||||
};
|
||||
|
||||
export const ABOUT_EN: PageCopy = {
|
||||
|
||||
@@ -126,6 +126,9 @@ export const SERVICES_SOFTWARE_EN: ServicePageCopy = {
|
||||
},
|
||||
},
|
||||
offerings: [],
|
||||
deliveredOfferingsHeading: 'Delivered work',
|
||||
offerOfferingsHeading: 'Offered and validated per engagement',
|
||||
offeringCaseBackedLabel: 'Backed by the public case {case}.',
|
||||
};
|
||||
|
||||
export const SERVICES_HARDWARE_EN: ServicePageCopy = {
|
||||
@@ -208,6 +211,9 @@ export const SERVICES_HARDWARE_EN: ServicePageCopy = {
|
||||
},
|
||||
},
|
||||
offerings: [],
|
||||
deliveredOfferingsHeading: 'Delivered work',
|
||||
offerOfferingsHeading: 'Offered and validated per engagement',
|
||||
offeringCaseBackedLabel: 'Backed by the public case {case}.',
|
||||
};
|
||||
|
||||
export const SERVICES_CLUSTERS_EN: ServicePageCopy = {
|
||||
@@ -289,6 +295,9 @@ export const SERVICES_CLUSTERS_EN: ServicePageCopy = {
|
||||
},
|
||||
},
|
||||
offerings: [],
|
||||
deliveredOfferingsHeading: 'Delivered work',
|
||||
offerOfferingsHeading: 'Offered and validated per engagement',
|
||||
offeringCaseBackedLabel: 'Backed by the public case {case}.',
|
||||
};
|
||||
|
||||
export const SERVICES_AI_EN: ServicePageCopy = {
|
||||
@@ -421,4 +430,7 @@ export const SERVICES_AI_EN: ServicePageCopy = {
|
||||
status: 'offer',
|
||||
},
|
||||
],
|
||||
deliveredOfferingsHeading: 'Delivered work',
|
||||
offerOfferingsHeading: 'Offered and validated per engagement',
|
||||
offeringCaseBackedLabel: 'Backed by the public case {case}.',
|
||||
};
|
||||
|
||||
@@ -34,6 +34,12 @@ export const SITE_CONTENT_EN: SiteContent = {
|
||||
imprint: IMPRINT_EN,
|
||||
privacy: PRIVACY_EN,
|
||||
},
|
||||
seo: {
|
||||
jobTitle: 'Fullstack and DevOps engineer',
|
||||
professionalServiceName: 'Software and DevOps services',
|
||||
professionalServiceDescription:
|
||||
'Four service areas covering product software, infrastructure, clusters and AI integration — from the first workshop through to operations, with direct customer contact.',
|
||||
},
|
||||
pages: {
|
||||
home: HOME_EN,
|
||||
services: SERVICES_OVERVIEW_EN,
|
||||
|
||||
70
src/app/core/content/signature-copy.spec.ts
Normal file
70
src/app/core/content/signature-copy.spec.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { COMMAND_IDS } from '../commands/command-ids';
|
||||
import { APP_LOCALES } from '../i18n/locale';
|
||||
import { SIGNATURE_COPY } from './signature-copy';
|
||||
|
||||
function leafPaths(value: unknown, prefix = ''): string[] {
|
||||
if (typeof value === 'string') {
|
||||
return [prefix];
|
||||
}
|
||||
|
||||
if (value !== null && typeof value === 'object') {
|
||||
return Object.keys(value).flatMap((key) => {
|
||||
const next = prefix.length > 0 ? `${prefix}.${key}` : key;
|
||||
return leafPaths((value as Record<string, unknown>)[key], next);
|
||||
});
|
||||
}
|
||||
|
||||
return [prefix];
|
||||
}
|
||||
|
||||
function collectStrings(value: unknown): string[] {
|
||||
if (typeof value === 'string') {
|
||||
return [value];
|
||||
}
|
||||
|
||||
if (value !== null && typeof value === 'object') {
|
||||
return Object.values(value).flatMap((entry) => collectStrings(entry));
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
describe('SIGNATURE_COPY', () => {
|
||||
it('exposes the same key structure in both locales', () => {
|
||||
const [first, ...rest] = APP_LOCALES.map((locale) => leafPaths(SIGNATURE_COPY[locale]));
|
||||
|
||||
for (const keys of rest) {
|
||||
expect(keys).toEqual(first);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps every string non-empty', () => {
|
||||
for (const locale of APP_LOCALES) {
|
||||
for (const value of collectStrings(SIGNATURE_COPY[locale])) {
|
||||
expect(value.trim().length).toBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('does not import from src/app/shared', () => {
|
||||
const source = readFileSync(
|
||||
join(process.cwd(), 'src/app/core/content/signature-copy.ts'),
|
||||
'utf8',
|
||||
);
|
||||
expect(source).not.toMatch(/from ['"][^'"]*\/shared\//);
|
||||
});
|
||||
|
||||
it('describes every CommandId in both locales', () => {
|
||||
for (const locale of APP_LOCALES) {
|
||||
const descriptions = SIGNATURE_COPY[locale].palette.commandDescriptions;
|
||||
|
||||
expect(Object.keys(descriptions).sort()).toEqual([...COMMAND_IDS].sort());
|
||||
|
||||
for (const id of COMMAND_IDS) {
|
||||
expect(descriptions[id].trim().length).toBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
153
src/app/core/content/signature-copy.ts
Normal file
153
src/app/core/content/signature-copy.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
import { type CommandId } from '../commands/command-ids';
|
||||
import { type AppLocale } from '../i18n/locale';
|
||||
|
||||
export interface SignatureCopy {
|
||||
readonly palette: {
|
||||
readonly triggerLabel: string;
|
||||
readonly shortcutHint: string;
|
||||
readonly shortcutHintApple: string;
|
||||
readonly dialogTitle: string;
|
||||
readonly dialogDescription: string;
|
||||
readonly inputLabel: string;
|
||||
readonly inputPlaceholder: string;
|
||||
readonly closeLabel: string;
|
||||
readonly suggestionsLabel: string;
|
||||
readonly outputLabel: string;
|
||||
readonly emptySuggestions: string;
|
||||
readonly unknownCommand: string;
|
||||
readonly helpIntro: string;
|
||||
readonly clearedMessage: string;
|
||||
readonly cvOpened: string;
|
||||
readonly navigating: string;
|
||||
readonly commandDescriptions: Record<CommandId, string>;
|
||||
readonly responses: {
|
||||
readonly brew: string;
|
||||
readonly ignite: string;
|
||||
readonly rev: string;
|
||||
};
|
||||
};
|
||||
readonly systemsMap: {
|
||||
readonly heading: string;
|
||||
readonly intro: string;
|
||||
readonly diagramDescription: string;
|
||||
readonly listHeading: string;
|
||||
readonly legendHeading: string;
|
||||
readonly relationshipLabel: string;
|
||||
readonly legend: {
|
||||
readonly ai: string;
|
||||
readonly cluster: string;
|
||||
readonly hardware: string;
|
||||
readonly software: string;
|
||||
readonly project: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export const SIGNATURE_COPY: Record<AppLocale, SignatureCopy> = {
|
||||
de: {
|
||||
palette: {
|
||||
triggerLabel: 'Befehle öffnen',
|
||||
shortcutHint: 'Strg+K',
|
||||
shortcutHintApple: '⌘K',
|
||||
dialogTitle: 'Befehle',
|
||||
dialogDescription:
|
||||
'Zur Navigation oder zu einer kurzen Rückmeldung. Es wird kein Code ausgeführt.',
|
||||
inputLabel: 'Befehl',
|
||||
inputPlaceholder: 'Befehl eingeben',
|
||||
closeLabel: 'Schließen',
|
||||
suggestionsLabel: 'Vorschläge',
|
||||
outputLabel: 'Ausgabe',
|
||||
emptySuggestions: 'Keine passenden Befehle.',
|
||||
unknownCommand: 'Unbekannter Befehl: {command}',
|
||||
helpIntro: 'Verfügbare Befehle:',
|
||||
clearedMessage: 'Ausgabe geleert.',
|
||||
cvOpened: 'Lebenslauf in einem neuen Tab geöffnet.',
|
||||
navigating: 'Wechsel zu {target}.',
|
||||
commandDescriptions: {
|
||||
help: 'Listet die verfügbaren Befehle.',
|
||||
projects: 'Öffnet die Projektübersicht.',
|
||||
servicesAi: 'Öffnet die Seite zur KI-Integration.',
|
||||
cv: 'Öffnet den Lebenslauf als PDF.',
|
||||
contact: 'Öffnet die Kontaktseite.',
|
||||
brew: 'Eine kurze, spielerische Rückmeldung.',
|
||||
ignite: 'Eine kurze, spielerische Rückmeldung.',
|
||||
rev: 'Eine kurze, spielerische Rückmeldung.',
|
||||
clear: 'Leert die Ausgabe.',
|
||||
close: 'Schließt die Befehlsübersicht.',
|
||||
},
|
||||
responses: {
|
||||
brew: 'Frisch aufgebrüht. Automatisierung, die auch vor dem ersten Kaffee läuft.',
|
||||
ignite: 'Zündung frei. Die Systeme laufen warm.',
|
||||
rev: 'Drehzahl steigt, der Content bleibt trotzdem ruhig.',
|
||||
},
|
||||
},
|
||||
systemsMap: {
|
||||
heading: 'Systemkarte',
|
||||
intro:
|
||||
'Wie die technischen Schichten zusammenhängen — von Hardware bis zu den Projektfeldern.',
|
||||
diagramDescription: 'Diagramm der technischen Schichten und ihrer Verbindungen.',
|
||||
listHeading: 'Knoten als Liste',
|
||||
legendHeading: 'Legende',
|
||||
relationshipLabel: 'Verbunden mit {targets}.',
|
||||
legend: {
|
||||
ai: 'KI-Integration',
|
||||
cluster: 'Cluster',
|
||||
hardware: 'Hardware und Netz',
|
||||
software: 'Software',
|
||||
project: 'Projektfeld',
|
||||
},
|
||||
},
|
||||
},
|
||||
en: {
|
||||
palette: {
|
||||
triggerLabel: 'Open commands',
|
||||
shortcutHint: 'Ctrl+K',
|
||||
shortcutHintApple: '⌘K',
|
||||
dialogTitle: 'Commands',
|
||||
dialogDescription: 'Navigate or get a short acknowledgement. No code is executed.',
|
||||
inputLabel: 'Command',
|
||||
inputPlaceholder: 'Type a command',
|
||||
closeLabel: 'Close',
|
||||
suggestionsLabel: 'Suggestions',
|
||||
outputLabel: 'Output',
|
||||
emptySuggestions: 'No matching commands.',
|
||||
unknownCommand: 'Unknown command: {command}',
|
||||
helpIntro: 'Available commands:',
|
||||
clearedMessage: 'Output cleared.',
|
||||
cvOpened: 'Opened the CV in a new tab.',
|
||||
navigating: 'Going to {target}.',
|
||||
commandDescriptions: {
|
||||
help: 'Lists the available commands.',
|
||||
projects: 'Opens the projects overview.',
|
||||
servicesAi: 'Opens the AI integration page.',
|
||||
cv: 'Opens the CV as a PDF.',
|
||||
contact: 'Opens the contact page.',
|
||||
brew: 'A short playful acknowledgement.',
|
||||
ignite: 'A short playful acknowledgement.',
|
||||
rev: 'A short playful acknowledgement.',
|
||||
clear: 'Clears the output.',
|
||||
close: 'Closes the command palette.',
|
||||
},
|
||||
responses: {
|
||||
brew: 'Freshly brewed. Automation that runs before the first coffee.',
|
||||
ignite: 'Ignition on. Systems are warming up.',
|
||||
rev: 'Revs climbing, the content stays calm.',
|
||||
},
|
||||
},
|
||||
systemsMap: {
|
||||
heading: 'Systems map',
|
||||
intro: 'How the technical layers connect — from hardware through to the project fields.',
|
||||
diagramDescription: 'Diagram of the technical layers and their connections.',
|
||||
listHeading: 'Nodes as a list',
|
||||
legendHeading: 'Legend',
|
||||
relationshipLabel: 'Connected to {targets}.',
|
||||
legend: {
|
||||
ai: 'AI integration',
|
||||
cluster: 'Cluster',
|
||||
hardware: 'Hardware and network',
|
||||
software: 'Software',
|
||||
project: 'Project field',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -1,12 +1,14 @@
|
||||
export const SITE_CONFIG: {
|
||||
readonly personName: string;
|
||||
readonly contactEmail: string;
|
||||
readonly siteOrigin: string;
|
||||
readonly cvAssetPath: string;
|
||||
readonly cvDownloadFileName: string;
|
||||
readonly calendarUrl: string | null;
|
||||
} = {
|
||||
personName: 'Antonio Ledebuhr',
|
||||
contactEmail: 'info@antoniolede.de',
|
||||
siteOrigin: 'https://antoniolede.de',
|
||||
cvAssetPath: '/cv/CV.pdf',
|
||||
cvDownloadFileName: 'Antonio-Ledebuhr-CV.pdf',
|
||||
calendarUrl: null,
|
||||
|
||||
@@ -10,7 +10,7 @@ export interface NavItem {
|
||||
export const PRIMARY_NAV: readonly NavItem[] = [
|
||||
{
|
||||
routeId: 'home',
|
||||
label: { de: 'Start', en: 'Home' },
|
||||
label: { de: 'Startseite', en: 'Home' },
|
||||
},
|
||||
{
|
||||
routeId: 'services',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { PLATFORM_ID } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import {
|
||||
isApplePlatform,
|
||||
isBrowserPlatform,
|
||||
prefersCoarsePointer,
|
||||
prefersReducedMotion,
|
||||
@@ -18,6 +19,7 @@ describe('browser platform helpers', () => {
|
||||
expect(prefersReducedMotion()).toBe(false);
|
||||
expect(prefersCoarsePointer()).toBe(false);
|
||||
expect(viewportMatches('(min-width: 40rem)')).toBe(false);
|
||||
expect(isApplePlatform()).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,6 +17,22 @@ export function viewportMatches(query: string): boolean {
|
||||
return mediaQueryMatches(query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard-labelling exception: there is no CSS media query for the Command key.
|
||||
* Used only to swap the palette shortcut hint after hydration.
|
||||
*/
|
||||
export function isApplePlatform(): boolean {
|
||||
if (!isBrowserPlatform()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const navigatorWithHints = window.navigator as Navigator & {
|
||||
readonly userAgentData?: { readonly platform?: string };
|
||||
};
|
||||
const platform = navigatorWithHints.userAgentData?.platform ?? navigatorWithHints.platform ?? '';
|
||||
return /mac|iphone|ipad|ipod/i.test(platform);
|
||||
}
|
||||
|
||||
function mediaQueryMatches(query: string): boolean {
|
||||
if (!isBrowserPlatform() || typeof window.matchMedia !== 'function') {
|
||||
return false;
|
||||
|
||||
169
src/app/core/seo/crawl-assets.spec.ts
Normal file
169
src/app/core/seo/crawl-assets.spec.ts
Normal file
@@ -0,0 +1,169 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { APP_LOCALES } from '../i18n/locale';
|
||||
import { SITE_CONFIG } from '../content/site-config';
|
||||
import { CASE_STUDY_IDS } from '../content/content.contracts';
|
||||
import { prerenderablePaths, routePath } from '../routing/route-paths';
|
||||
import { absoluteUrl } from './route-metadata';
|
||||
|
||||
const PUBLIC = join(process.cwd(), 'public');
|
||||
const EXCLUDED = /HUP|BitWiz|Cybertrading/;
|
||||
|
||||
function readPublic(name: 'robots.txt' | 'sitemap.xml' | 'llms.txt'): string {
|
||||
return readFileSync(join(PUBLIC, name), 'utf8');
|
||||
}
|
||||
|
||||
function expectedCanonicals(): readonly string[] {
|
||||
return prerenderablePaths().map((path) => absoluteUrl(path));
|
||||
}
|
||||
|
||||
function sitemapLocs(xml: string): string[] {
|
||||
return [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((match) => match[1]);
|
||||
}
|
||||
|
||||
function sitemapAlternates(xml: string): Array<{ loc: string; hreflang: string; href: string }> {
|
||||
const blocks = xml.split(/<url>/).slice(1);
|
||||
const rows: Array<{ loc: string; hreflang: string; href: string }> = [];
|
||||
|
||||
for (const block of blocks) {
|
||||
const loc = block.match(/<loc>([^<]+)<\/loc>/)?.[1];
|
||||
if (!loc) {
|
||||
throw new Error(`sitemap.xml has a <url> block without <loc>: ${block.slice(0, 120)}`);
|
||||
}
|
||||
|
||||
const links = [
|
||||
...block.matchAll(
|
||||
/<xhtml:link[^>]*rel="alternate"[^>]*hreflang="([^"]+)"[^>]*href="([^"]+)"/g,
|
||||
),
|
||||
];
|
||||
|
||||
if (links.length === 0) {
|
||||
throw new Error(`sitemap.xml is missing xhtml alternates for ${loc}`);
|
||||
}
|
||||
|
||||
for (const link of links) {
|
||||
rows.push({ loc, hreflang: link[1], href: link[2] });
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function siteOriginsIn(text: string): string[] {
|
||||
return [...text.matchAll(/(?:href|loc|Sitemap:\s*)["']?(https?:\/\/[^/\s"'<>]+)/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
}
|
||||
|
||||
describe('crawl assets', () => {
|
||||
it('lists every prerenderable path once and no URL outside that set', () => {
|
||||
const xml = readPublic('sitemap.xml');
|
||||
const expected = [...expectedCanonicals()].sort();
|
||||
const actual = [...new Set(sitemapLocs(xml))].sort();
|
||||
|
||||
expect(
|
||||
actual,
|
||||
'sitemap.xml locs must match SITE_CONFIG.siteOrigin + prerenderablePaths()',
|
||||
).toEqual(expected);
|
||||
expect(sitemapLocs(xml)).toHaveLength(expected.length);
|
||||
});
|
||||
|
||||
it('keeps reciprocal hreflang alternates for de-DE, en and x-default', () => {
|
||||
const xml = readPublic('sitemap.xml');
|
||||
const required = ['de-DE', 'en', 'x-default'] as const;
|
||||
|
||||
for (const loc of sitemapLocs(xml)) {
|
||||
const links = sitemapAlternates(xml).filter((row) => row.loc === loc);
|
||||
const langs = links.map((row) => row.hreflang).sort();
|
||||
expect(langs, `${loc} must have de-DE, en and x-default`).toEqual([...required].sort());
|
||||
|
||||
const byLang = Object.fromEntries(links.map((row) => [row.hreflang, row.href]));
|
||||
expect(byLang['x-default'], `${loc} x-default must be the German URL`).toBe(byLang['de-DE']);
|
||||
}
|
||||
|
||||
for (const locale of APP_LOCALES) {
|
||||
for (const path of prerenderablePaths().filter((entry) =>
|
||||
locale === 'en'
|
||||
? entry === '/en' || entry.startsWith('/en/')
|
||||
: !(entry === '/en' || entry.startsWith('/en/')),
|
||||
)) {
|
||||
const loc = absoluteUrl(path);
|
||||
const links = sitemapAlternates(xml).filter((row) => row.loc === loc);
|
||||
const germanHref = links.find((row) => row.hreflang === 'de-DE')?.href;
|
||||
const englishHref = links.find((row) => row.hreflang === 'en')?.href;
|
||||
expect(germanHref, `${loc} is missing a de-DE alternate`).toBeTruthy();
|
||||
expect(englishHref, `${loc} is missing an en alternate`).toBeTruthy();
|
||||
|
||||
const germanLinks = sitemapAlternates(xml).filter((row) => row.loc === germanHref);
|
||||
const englishLinks = sitemapAlternates(xml).filter((row) => row.loc === englishHref);
|
||||
expect(
|
||||
germanLinks.find((row) => row.hreflang === 'en')?.href,
|
||||
`${germanHref} must point back to ${englishHref}`,
|
||||
).toBe(englishHref);
|
||||
expect(
|
||||
englishLinks.find((row) => row.hreflang === 'de-DE')?.href,
|
||||
`${englishHref} must point back to ${germanHref}`,
|
||||
).toBe(germanHref);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('lists the required canonical URLs in both locales in llms.txt', () => {
|
||||
const text = readPublic('llms.txt');
|
||||
const required = [
|
||||
absoluteUrl(routePath('home', 'de')),
|
||||
absoluteUrl(routePath('home', 'en')),
|
||||
absoluteUrl(routePath('about', 'de')),
|
||||
absoluteUrl(routePath('about', 'en')),
|
||||
absoluteUrl(routePath('services', 'de')),
|
||||
absoluteUrl(routePath('services', 'en')),
|
||||
absoluteUrl(routePath('servicesSoftware', 'de')),
|
||||
absoluteUrl(routePath('servicesSoftware', 'en')),
|
||||
absoluteUrl(routePath('servicesHardwareNetwork', 'de')),
|
||||
absoluteUrl(routePath('servicesHardwareNetwork', 'en')),
|
||||
absoluteUrl(routePath('servicesClusters', 'de')),
|
||||
absoluteUrl(routePath('servicesClusters', 'en')),
|
||||
absoluteUrl(routePath('servicesAi', 'de')),
|
||||
absoluteUrl(routePath('servicesAi', 'en')),
|
||||
absoluteUrl(routePath('projects', 'de')),
|
||||
absoluteUrl(routePath('projects', 'en')),
|
||||
...CASE_STUDY_IDS.flatMap((id) => [
|
||||
`${absoluteUrl(routePath('projects', 'de'))}#${id}`,
|
||||
`${absoluteUrl(routePath('projects', 'en'))}#${id}`,
|
||||
]),
|
||||
absoluteUrl(routePath('contact', 'de')),
|
||||
absoluteUrl(routePath('contact', 'en')),
|
||||
absoluteUrl(routePath('stack', 'de')),
|
||||
absoluteUrl(routePath('stack', 'en')),
|
||||
absoluteUrl(routePath('imprint', 'de')),
|
||||
absoluteUrl(routePath('imprint', 'en')),
|
||||
absoluteUrl(routePath('privacy', 'de')),
|
||||
absoluteUrl(routePath('privacy', 'en')),
|
||||
];
|
||||
|
||||
for (const url of required) {
|
||||
expect(text.includes(url), `llms.txt is missing ${url}`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('points robots.txt at the sitemap on the canonical origin', () => {
|
||||
const robots = readPublic('robots.txt');
|
||||
expect(robots, 'robots.txt must reference the sitemap at SITE_CONFIG.siteOrigin').toContain(
|
||||
`Sitemap: ${SITE_CONFIG.siteOrigin}/sitemap.xml`,
|
||||
);
|
||||
expect(robots).toMatch(/User-agent:\s*\*/);
|
||||
expect(robots).not.toMatch(/Disallow:\s+\S+/);
|
||||
});
|
||||
|
||||
it('uses only SITE_CONFIG.siteOrigin and never names excluded stations', () => {
|
||||
for (const name of ['robots.txt', 'sitemap.xml', 'llms.txt'] as const) {
|
||||
const text = readPublic(name);
|
||||
const origins = siteOriginsIn(text);
|
||||
const unexpected = origins.filter((origin) => origin !== SITE_CONFIG.siteOrigin);
|
||||
expect(unexpected, `${name} contains an origin other than ${SITE_CONFIG.siteOrigin}`).toEqual(
|
||||
[],
|
||||
);
|
||||
expect(EXCLUDED.test(text), `${name} contains an excluded station name`).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
69
src/app/core/seo/route-metadata.spec.ts
Normal file
69
src/app/core/seo/route-metadata.spec.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { SITE_CONTENT_DATA } from '../content/site-content';
|
||||
import { SITE_CONFIG } from '../content/site-config';
|
||||
import { APP_LOCALES } from '../i18n/locale';
|
||||
import { ROUTE_IDS } from '../routing/route-ids';
|
||||
import { routePath } from '../routing/route-paths';
|
||||
import { buildRouteMetadata, OG_LOCALE } from './route-metadata';
|
||||
|
||||
describe('buildRouteMetadata', () => {
|
||||
it('derives title, description, canonical, alternates, Open Graph and Twitter for every route', () => {
|
||||
for (const locale of APP_LOCALES) {
|
||||
for (const routeId of ROUTE_IDS) {
|
||||
const page = SITE_CONTENT_DATA[locale].pages[routeId];
|
||||
const metadata = buildRouteMetadata(routeId, locale, SITE_CONTENT_DATA);
|
||||
const other = locale === 'de' ? 'en' : 'de';
|
||||
|
||||
expect(metadata.title, `${locale}.${routeId} title`).toBe(page.title);
|
||||
expect(metadata.description, `${locale}.${routeId} description`).toBe(page.description);
|
||||
expect(metadata.openGraph.type).toBe('website');
|
||||
expect(metadata.openGraph.title).toBe(page.title);
|
||||
expect(metadata.openGraph.description).toBe(page.description);
|
||||
expect(metadata.openGraph.siteName).toBe(SITE_CONFIG.personName);
|
||||
expect(metadata.openGraph.locale).toBe(OG_LOCALE[locale]);
|
||||
expect(metadata.openGraph.localeAlternate).toBe(OG_LOCALE[other]);
|
||||
expect(metadata.twitter.card).toBe('summary');
|
||||
expect(metadata.twitter.title).toBe(page.title);
|
||||
expect(metadata.twitter.description).toBe(page.description);
|
||||
|
||||
if (routeId === 'notFound') {
|
||||
expect(metadata.canonical, `${locale}.notFound must have no canonical`).toBeNull();
|
||||
expect(metadata.alternates, `${locale}.notFound must have no alternates`).toEqual([]);
|
||||
expect(metadata.openGraph.url).toBeNull();
|
||||
expect(metadata.robots).toBe('noindex, follow');
|
||||
continue;
|
||||
}
|
||||
|
||||
const expectedCanonical = `${SITE_CONFIG.siteOrigin}${routePath(routeId, locale)}`;
|
||||
expect(metadata.canonical, `${locale}.${routeId} canonical`).toBe(expectedCanonical);
|
||||
expect(metadata.openGraph.url).toBe(expectedCanonical);
|
||||
expect(metadata.robots).toBe('index, follow');
|
||||
|
||||
const byLang = Object.fromEntries(
|
||||
metadata.alternates.map((entry) => [entry.hreflang, entry.href]),
|
||||
);
|
||||
expect(Object.keys(byLang).sort()).toEqual(['de-DE', 'en', 'x-default']);
|
||||
expect(byLang['de-DE']).toBe(`${SITE_CONFIG.siteOrigin}${routePath(routeId, 'de')}`);
|
||||
expect(byLang['en']).toBe(`${SITE_CONFIG.siteOrigin}${routePath(routeId, 'en')}`);
|
||||
expect(byLang['x-default']).toBe(byLang['de-DE']);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps German and English alternates reciprocal for every public route', () => {
|
||||
for (const routeId of ROUTE_IDS.filter((id) => id !== 'notFound')) {
|
||||
const german = buildRouteMetadata(routeId, 'de', SITE_CONTENT_DATA);
|
||||
const english = buildRouteMetadata(routeId, 'en', SITE_CONTENT_DATA);
|
||||
const germanHref = german.alternates.find((entry) => entry.hreflang === 'de-DE')?.href;
|
||||
const englishHref = german.alternates.find((entry) => entry.hreflang === 'en')?.href;
|
||||
|
||||
expect(english.alternates.find((entry) => entry.hreflang === 'de-DE')?.href).toBe(germanHref);
|
||||
expect(english.alternates.find((entry) => entry.hreflang === 'en')?.href).toBe(englishHref);
|
||||
expect(german.alternates.find((entry) => entry.hreflang === 'x-default')?.href).toBe(
|
||||
germanHref,
|
||||
);
|
||||
expect(english.alternates.find((entry) => entry.hreflang === 'x-default')?.href).toBe(
|
||||
germanHref,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
61
src/app/core/seo/route-metadata.ts
Normal file
61
src/app/core/seo/route-metadata.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { type SiteContent } from '../content/content.contracts';
|
||||
import { SITE_CONFIG } from '../content/site-config';
|
||||
import { type AppLocale } from '../i18n/locale';
|
||||
import { otherLocale } from '../i18n/locale';
|
||||
import { type RouteId } from '../routing/route-ids';
|
||||
import { routePath } from '../routing/route-paths';
|
||||
import { type RouteMetadata } from './seo.contracts';
|
||||
|
||||
export const OG_LOCALE: Record<AppLocale, string> = {
|
||||
de: 'de_DE',
|
||||
en: 'en_US',
|
||||
};
|
||||
|
||||
export function absoluteUrl(path: string): string {
|
||||
return `${SITE_CONFIG.siteOrigin}${path === '/' ? '/' : path}`;
|
||||
}
|
||||
|
||||
export function canonicalUrl(routeId: RouteId, locale: AppLocale): string {
|
||||
return absoluteUrl(routePath(routeId, locale));
|
||||
}
|
||||
|
||||
export function buildRouteMetadata(
|
||||
routeId: RouteId,
|
||||
locale: AppLocale,
|
||||
content: Record<AppLocale, SiteContent>,
|
||||
): RouteMetadata {
|
||||
const page = content[locale].pages[routeId];
|
||||
const title = page.title;
|
||||
const description = page.description;
|
||||
const isNotFound = routeId === 'notFound';
|
||||
const canonical = isNotFound ? null : canonicalUrl(routeId, locale);
|
||||
const alternateLocale = otherLocale(locale);
|
||||
|
||||
return {
|
||||
title,
|
||||
description,
|
||||
canonical,
|
||||
alternates: isNotFound
|
||||
? []
|
||||
: [
|
||||
{ hreflang: 'de-DE', href: canonicalUrl(routeId, 'de') },
|
||||
{ hreflang: 'en', href: canonicalUrl(routeId, 'en') },
|
||||
{ hreflang: 'x-default', href: canonicalUrl(routeId, 'de') },
|
||||
],
|
||||
openGraph: {
|
||||
type: 'website',
|
||||
title,
|
||||
description,
|
||||
url: canonical,
|
||||
siteName: SITE_CONFIG.personName,
|
||||
locale: OG_LOCALE[locale],
|
||||
localeAlternate: OG_LOCALE[alternateLocale],
|
||||
},
|
||||
twitter: {
|
||||
card: 'summary',
|
||||
title,
|
||||
description,
|
||||
},
|
||||
robots: isNotFound ? 'noindex, follow' : 'index, follow',
|
||||
};
|
||||
}
|
||||
30
src/app/core/seo/seo-title.strategy.ts
Normal file
30
src/app/core/seo/seo-title.strategy.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { Title } from '@angular/platform-browser';
|
||||
import { RouterStateSnapshot, TitleStrategy } from '@angular/router';
|
||||
import { SITE_CONTENT } from '../content/content.token';
|
||||
import { isAppRouteData } from '../routing/app-route-data';
|
||||
import { buildRouteMetadata } from './route-metadata';
|
||||
import { SeoService } from './seo.service';
|
||||
|
||||
@Injectable()
|
||||
export class SeoTitleStrategy extends TitleStrategy {
|
||||
private readonly title = inject(Title);
|
||||
private readonly seo = inject(SeoService);
|
||||
private readonly content = inject(SITE_CONTENT);
|
||||
|
||||
override updateTitle(snapshot: RouterStateSnapshot): void {
|
||||
let current = snapshot.root;
|
||||
|
||||
while (current.firstChild) {
|
||||
current = current.firstChild;
|
||||
}
|
||||
|
||||
if (!isAppRouteData(current.data)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const metadata = buildRouteMetadata(current.data.routeId, current.data.locale, this.content);
|
||||
this.title.setTitle(metadata.title);
|
||||
this.seo.apply(current.data.routeId, current.data.locale);
|
||||
}
|
||||
}
|
||||
30
src/app/core/seo/seo.contracts.ts
Normal file
30
src/app/core/seo/seo.contracts.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
export interface RouteAlternate {
|
||||
readonly hreflang: string;
|
||||
readonly href: string;
|
||||
}
|
||||
|
||||
export interface OpenGraphMetadata {
|
||||
readonly type: 'website';
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly url: string | null;
|
||||
readonly siteName: string;
|
||||
readonly locale: string;
|
||||
readonly localeAlternate: string;
|
||||
}
|
||||
|
||||
export interface TwitterMetadata {
|
||||
readonly card: 'summary';
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
}
|
||||
|
||||
export interface RouteMetadata {
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly canonical: string | null;
|
||||
readonly alternates: readonly RouteAlternate[];
|
||||
readonly openGraph: OpenGraphMetadata;
|
||||
readonly twitter: TwitterMetadata;
|
||||
readonly robots: string;
|
||||
}
|
||||
61
src/app/core/seo/seo.service.spec.ts
Normal file
61
src/app/core/seo/seo.service.spec.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Title } from '@angular/platform-browser';
|
||||
import { SITE_CONTENT } from '../content/content.token';
|
||||
import { SITE_CONTENT_DATA } from '../content/site-content';
|
||||
import { SITE_CONFIG } from '../content/site-config';
|
||||
import { routePath } from '../routing/route-paths';
|
||||
import { SeoService } from './seo.service';
|
||||
|
||||
describe('SeoService', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [SeoService, { provide: SITE_CONTENT, useValue: SITE_CONTENT_DATA }],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.head.querySelectorAll('[data-seo]').forEach((node) => node.remove());
|
||||
document.head
|
||||
.querySelectorAll(
|
||||
'meta[name="description"], meta[name="robots"], meta[name^="twitter:"], meta[property^="og:"]',
|
||||
)
|
||||
.forEach((node) => node.remove());
|
||||
});
|
||||
|
||||
it('applies two routes in sequence without duplicating owned head elements', () => {
|
||||
const seo = TestBed.inject(SeoService);
|
||||
const title = TestBed.inject(Title);
|
||||
|
||||
seo.apply('home', 'de');
|
||||
seo.apply('projects', 'en');
|
||||
|
||||
expect(title.getTitle()).toBe(SITE_CONTENT_DATA.en.pages.projects.title);
|
||||
expect(document.querySelectorAll('link[rel="canonical"]')).toHaveLength(1);
|
||||
expect(document.querySelectorAll('link[rel="alternate"][hreflang]')).toHaveLength(3);
|
||||
expect(document.querySelectorAll('meta[name="description"]')).toHaveLength(1);
|
||||
expect(document.querySelectorAll('meta[name="robots"]')).toHaveLength(1);
|
||||
expect(document.querySelectorAll('script[type="application/ld+json"]')).toHaveLength(1);
|
||||
|
||||
const canonical = document.querySelector('link[rel="canonical"]')?.getAttribute('href');
|
||||
expect(canonical).toBe(`${SITE_CONFIG.siteOrigin}${routePath('projects', 'en')}`);
|
||||
expect(document.querySelector('meta[name="description"]')?.getAttribute('content')).toBe(
|
||||
SITE_CONTENT_DATA.en.pages.projects.description,
|
||||
);
|
||||
expect(document.querySelector('meta[name="robots"]')?.getAttribute('content')).toBe(
|
||||
'index, follow',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops canonical and alternate links for notFound and sets noindex', () => {
|
||||
const seo = TestBed.inject(SeoService);
|
||||
seo.apply('home', 'de');
|
||||
seo.apply('notFound', 'de');
|
||||
|
||||
expect(document.querySelectorAll('link[rel="canonical"]')).toHaveLength(0);
|
||||
expect(document.querySelectorAll('link[rel="alternate"][hreflang]')).toHaveLength(0);
|
||||
expect(document.querySelector('meta[name="robots"]')?.getAttribute('content')).toBe(
|
||||
'noindex, follow',
|
||||
);
|
||||
expect(document.querySelectorAll('script[type="application/ld+json"]')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
116
src/app/core/seo/seo.service.ts
Normal file
116
src/app/core/seo/seo.service.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { Meta, Title } from '@angular/platform-browser';
|
||||
import { SITE_CONTENT } from '../content/content.token';
|
||||
import { type AppLocale } from '../i18n/locale';
|
||||
import { type RouteId } from '../routing/route-ids';
|
||||
import { buildRouteMetadata } from './route-metadata';
|
||||
import { type RouteMetadata } from './seo.contracts';
|
||||
import { buildJsonLdGraph, serializeJsonLd } from './structured-data';
|
||||
|
||||
const SEO_OWNED = 'data-seo';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class SeoService {
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private readonly title = inject(Title);
|
||||
private readonly meta = inject(Meta);
|
||||
private readonly content = inject(SITE_CONTENT);
|
||||
|
||||
apply(routeId: RouteId, locale: AppLocale): void {
|
||||
const metadata = buildRouteMetadata(routeId, locale, this.content);
|
||||
this.title.setTitle(metadata.title);
|
||||
this.updateMeta(metadata);
|
||||
this.replaceOwnedElements(routeId, locale, metadata);
|
||||
}
|
||||
|
||||
private updateMeta(metadata: RouteMetadata): void {
|
||||
this.meta.updateTag(
|
||||
{ name: 'description', content: metadata.description },
|
||||
'name="description"',
|
||||
);
|
||||
this.meta.updateTag({ name: 'robots', content: metadata.robots }, 'name="robots"');
|
||||
this.meta.updateTag(
|
||||
{ property: 'og:type', content: metadata.openGraph.type },
|
||||
'property="og:type"',
|
||||
);
|
||||
this.meta.updateTag(
|
||||
{ property: 'og:title', content: metadata.openGraph.title },
|
||||
'property="og:title"',
|
||||
);
|
||||
this.meta.updateTag(
|
||||
{ property: 'og:description', content: metadata.openGraph.description },
|
||||
'property="og:description"',
|
||||
);
|
||||
this.meta.updateTag(
|
||||
{ property: 'og:site_name', content: metadata.openGraph.siteName },
|
||||
'property="og:site_name"',
|
||||
);
|
||||
this.meta.updateTag(
|
||||
{ property: 'og:locale', content: metadata.openGraph.locale },
|
||||
'property="og:locale"',
|
||||
);
|
||||
this.meta.updateTag(
|
||||
{ property: 'og:locale:alternate', content: metadata.openGraph.localeAlternate },
|
||||
'property="og:locale:alternate"',
|
||||
);
|
||||
this.meta.updateTag(
|
||||
{ name: 'twitter:card', content: metadata.twitter.card },
|
||||
'name="twitter:card"',
|
||||
);
|
||||
this.meta.updateTag(
|
||||
{ name: 'twitter:title', content: metadata.twitter.title },
|
||||
'name="twitter:title"',
|
||||
);
|
||||
this.meta.updateTag(
|
||||
{ name: 'twitter:description', content: metadata.twitter.description },
|
||||
'name="twitter:description"',
|
||||
);
|
||||
|
||||
if (metadata.openGraph.url) {
|
||||
this.meta.updateTag(
|
||||
{ property: 'og:url', content: metadata.openGraph.url },
|
||||
'property="og:url"',
|
||||
);
|
||||
} else {
|
||||
this.meta.removeTag('property="og:url"');
|
||||
}
|
||||
}
|
||||
|
||||
private replaceOwnedElements(routeId: RouteId, locale: AppLocale, metadata: RouteMetadata): void {
|
||||
const head = this.document.head;
|
||||
|
||||
for (const owned of Array.from(head.querySelectorAll(`[${SEO_OWNED}]`))) {
|
||||
owned.remove();
|
||||
}
|
||||
|
||||
if (metadata.canonical) {
|
||||
this.appendLink(head, { rel: 'canonical', href: metadata.canonical });
|
||||
}
|
||||
|
||||
for (const alternate of metadata.alternates) {
|
||||
this.appendLink(head, {
|
||||
rel: 'alternate',
|
||||
hreflang: alternate.hreflang,
|
||||
href: alternate.href,
|
||||
});
|
||||
}
|
||||
|
||||
const script = this.document.createElement('script');
|
||||
script.type = 'application/ld+json';
|
||||
script.setAttribute(SEO_OWNED, '');
|
||||
script.textContent = serializeJsonLd(buildJsonLdGraph(routeId, locale, this.content));
|
||||
head.appendChild(script);
|
||||
}
|
||||
|
||||
private appendLink(head: HTMLHeadElement, attributes: Record<string, string>): void {
|
||||
const link = this.document.createElement('link');
|
||||
link.setAttribute(SEO_OWNED, '');
|
||||
|
||||
for (const [name, value] of Object.entries(attributes)) {
|
||||
link.setAttribute(name, value);
|
||||
}
|
||||
|
||||
head.appendChild(link);
|
||||
}
|
||||
}
|
||||
111
src/app/core/seo/structured-data.spec.ts
Normal file
111
src/app/core/seo/structured-data.spec.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { SITE_CONTENT_DATA } from '../content/site-content';
|
||||
import { APP_LOCALES } from '../i18n/locale';
|
||||
import { ROUTE_IDS, type RouteId } from '../routing/route-ids';
|
||||
import { buildJsonLdGraph, serializeJsonLd } from './structured-data';
|
||||
|
||||
const FORBIDDEN_FIELDS = [
|
||||
'aggregateRating',
|
||||
'review',
|
||||
'offers',
|
||||
'price',
|
||||
'priceRange',
|
||||
'worksFor',
|
||||
'employee',
|
||||
'sponsor',
|
||||
'address',
|
||||
'geo',
|
||||
'openingHours',
|
||||
'telephone',
|
||||
'foundingDate',
|
||||
'numberOfEmployees',
|
||||
] as const;
|
||||
|
||||
const SERVICE_ROUTES: readonly RouteId[] = [
|
||||
'services',
|
||||
'servicesSoftware',
|
||||
'servicesHardwareNetwork',
|
||||
'servicesClusters',
|
||||
'servicesAi',
|
||||
];
|
||||
|
||||
function collectKeys(value: unknown, keys = new Set<string>()): Set<string> {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((entry) => collectKeys(entry, keys));
|
||||
return keys;
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object') {
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
keys.add(key);
|
||||
collectKeys(child, keys);
|
||||
}
|
||||
}
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
function graphTypes(routeId: RouteId, locale: (typeof APP_LOCALES)[number]): string[] {
|
||||
const graph = buildJsonLdGraph(routeId, locale, SITE_CONTENT_DATA);
|
||||
return graph['@graph'].map((node) => {
|
||||
if (node && typeof node === 'object' && !Array.isArray(node) && '@type' in node) {
|
||||
return String(node['@type']);
|
||||
}
|
||||
|
||||
return '';
|
||||
});
|
||||
}
|
||||
|
||||
describe('JSON-LD builders', () => {
|
||||
it('emits a schema.org @graph with the expected types per route', () => {
|
||||
for (const locale of APP_LOCALES) {
|
||||
const home = buildJsonLdGraph('home', locale, SITE_CONTENT_DATA);
|
||||
expect(home['@context']).toBe('https://schema.org');
|
||||
expect(graphTypes('home', locale)).toEqual(['Person', 'ProfessionalService']);
|
||||
|
||||
for (const routeId of SERVICE_ROUTES) {
|
||||
expect(graphTypes(routeId, locale), `${locale}.${routeId}`).toEqual(['Service']);
|
||||
}
|
||||
|
||||
expect(graphTypes('projects', locale)).toEqual([
|
||||
'CreativeWork',
|
||||
'CreativeWork',
|
||||
'CreativeWork',
|
||||
'CreativeWork',
|
||||
]);
|
||||
|
||||
for (const routeId of ROUTE_IDS.filter(
|
||||
(id) => id !== 'home' && id !== 'projects' && !SERVICE_ROUTES.includes(id),
|
||||
)) {
|
||||
expect(graphTypes(routeId, locale), `${locale}.${routeId}`).toEqual(['WebPage']);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('escapes <, > and & inside the serialized payload', () => {
|
||||
const serialized = serializeJsonLd({
|
||||
name: 'A <script>alert(1)</script> & more',
|
||||
});
|
||||
|
||||
expect(serialized).toContain('\\u003c');
|
||||
expect(serialized).toContain('\\u003e');
|
||||
expect(serialized).toContain('\\u0026');
|
||||
expect(serialized).not.toContain('<');
|
||||
expect(serialized).not.toContain('>');
|
||||
expect(serialized).not.toContain('&');
|
||||
});
|
||||
|
||||
it('never invents forbidden fields or excluded station names', () => {
|
||||
for (const locale of APP_LOCALES) {
|
||||
for (const routeId of ROUTE_IDS) {
|
||||
const graph = buildJsonLdGraph(routeId, locale, SITE_CONTENT_DATA);
|
||||
const keys = collectKeys(graph);
|
||||
for (const field of FORBIDDEN_FIELDS) {
|
||||
expect(keys.has(field), `${locale}.${routeId} contains ${field}`).toBe(false);
|
||||
}
|
||||
|
||||
const serialized = serializeJsonLd(graph);
|
||||
expect(serialized).not.toMatch(/HUP|BitWiz|Cybertrading/);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
149
src/app/core/seo/structured-data.ts
Normal file
149
src/app/core/seo/structured-data.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
import { CASE_STUDY_IDS, type SiteContent } from '../content/content.contracts';
|
||||
import { SITE_CONFIG } from '../content/site-config';
|
||||
import { LOCALE_HTML_LANG, type AppLocale } from '../i18n/locale';
|
||||
import { type RouteId } from '../routing/route-ids';
|
||||
import { canonicalUrl } from './route-metadata';
|
||||
|
||||
const SCHEMA_CONTEXT = 'https://schema.org';
|
||||
|
||||
const SERVICE_ROUTE_IDS: readonly RouteId[] = [
|
||||
'services',
|
||||
'servicesSoftware',
|
||||
'servicesHardwareNetwork',
|
||||
'servicesClusters',
|
||||
'servicesAi',
|
||||
];
|
||||
|
||||
export type JsonLdValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| readonly JsonLdValue[]
|
||||
| { readonly [key: string]: JsonLdValue };
|
||||
|
||||
export interface JsonLdGraph {
|
||||
readonly '@context': typeof SCHEMA_CONTEXT;
|
||||
readonly '@graph': readonly JsonLdValue[];
|
||||
}
|
||||
|
||||
function personNode(locale: AppLocale, content: Record<AppLocale, SiteContent>): JsonLdValue {
|
||||
return {
|
||||
'@type': 'Person',
|
||||
name: SITE_CONFIG.personName,
|
||||
jobTitle: content[locale].seo.jobTitle,
|
||||
email: SITE_CONFIG.contactEmail,
|
||||
url: canonicalUrl('home', locale),
|
||||
description: content[locale].pages.home.description,
|
||||
};
|
||||
}
|
||||
|
||||
function professionalServiceNode(
|
||||
locale: AppLocale,
|
||||
content: Record<AppLocale, SiteContent>,
|
||||
): JsonLdValue {
|
||||
const seo = content[locale].seo;
|
||||
|
||||
return {
|
||||
'@type': 'ProfessionalService',
|
||||
name: seo.professionalServiceName,
|
||||
description: seo.professionalServiceDescription,
|
||||
url: canonicalUrl('home', locale),
|
||||
provider: {
|
||||
'@type': 'Person',
|
||||
name: SITE_CONFIG.personName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function serviceNode(
|
||||
routeId: RouteId,
|
||||
locale: AppLocale,
|
||||
content: Record<AppLocale, SiteContent>,
|
||||
): JsonLdValue {
|
||||
const page = content[locale].pages[routeId];
|
||||
|
||||
return {
|
||||
'@type': 'Service',
|
||||
name: page.hero.headline,
|
||||
description: page.description,
|
||||
url: canonicalUrl(routeId, locale),
|
||||
provider: {
|
||||
'@type': 'Person',
|
||||
name: SITE_CONFIG.personName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function projectWorks(
|
||||
locale: AppLocale,
|
||||
content: Record<AppLocale, SiteContent>,
|
||||
): readonly JsonLdValue[] {
|
||||
const projectsUrl = canonicalUrl('projects', locale);
|
||||
|
||||
return CASE_STUDY_IDS.map((caseId) => {
|
||||
const study = content[locale].cases[caseId];
|
||||
|
||||
return {
|
||||
'@type': 'CreativeWork',
|
||||
name: study.headline,
|
||||
description: study.summary,
|
||||
url: `${projectsUrl}#${caseId}`,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function webPageNode(
|
||||
routeId: RouteId,
|
||||
locale: AppLocale,
|
||||
content: Record<AppLocale, SiteContent>,
|
||||
): JsonLdValue {
|
||||
const page = content[locale].pages[routeId];
|
||||
const node: { [key: string]: JsonLdValue } = {
|
||||
'@type': 'WebPage',
|
||||
name: page.title,
|
||||
description: page.description,
|
||||
inLanguage: LOCALE_HTML_LANG[locale],
|
||||
isPartOf: {
|
||||
'@type': 'WebSite',
|
||||
name: SITE_CONFIG.personName,
|
||||
url: SITE_CONFIG.siteOrigin + '/',
|
||||
},
|
||||
};
|
||||
|
||||
if (routeId !== 'notFound') {
|
||||
node['url'] = canonicalUrl(routeId, locale);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
export function buildJsonLdGraph(
|
||||
routeId: RouteId,
|
||||
locale: AppLocale,
|
||||
content: Record<AppLocale, SiteContent>,
|
||||
): JsonLdGraph {
|
||||
let graph: readonly JsonLdValue[];
|
||||
|
||||
if (routeId === 'home') {
|
||||
graph = [personNode(locale, content), professionalServiceNode(locale, content)];
|
||||
} else if (SERVICE_ROUTE_IDS.includes(routeId)) {
|
||||
graph = [serviceNode(routeId, locale, content)];
|
||||
} else if (routeId === 'projects') {
|
||||
graph = projectWorks(locale, content);
|
||||
} else {
|
||||
graph = [webPageNode(routeId, locale, content)];
|
||||
}
|
||||
|
||||
return {
|
||||
'@context': SCHEMA_CONTEXT,
|
||||
'@graph': graph,
|
||||
};
|
||||
}
|
||||
|
||||
export function serializeJsonLd(value: unknown): string {
|
||||
return JSON.stringify(value)
|
||||
.replace(/</g, '\\u003c')
|
||||
.replace(/>/g, '\\u003e')
|
||||
.replace(/&/g, '\\u0026');
|
||||
}
|
||||
@@ -10,9 +10,16 @@
|
||||
}
|
||||
</ul>
|
||||
<app-metric-list [metrics]="copy.metrics" [labelledBy]="'section-profile'" />
|
||||
<div appReveal class="home-reveal">
|
||||
<app-systems-map
|
||||
[heading]="copy.systemsMap.heading"
|
||||
[intro]="copy.systemsMap.intro"
|
||||
[headingLevel]="2"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
@if (section.id === 'featured-cases') {
|
||||
<div class="stack">
|
||||
<div appReveal class="home-reveal stack">
|
||||
@for (caseStudy of featuredCases(); track caseStudy.id) {
|
||||
<app-case-card [caseStudy]="caseStudy" />
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
@use '../../shared/motion/reveal';
|
||||
@use '../../shared/page-shell';
|
||||
|
||||
.home-reveal {
|
||||
@include reveal.reveal-target;
|
||||
}
|
||||
|
||||
.page h2 {
|
||||
margin: 0;
|
||||
font-size: var(--text-xl);
|
||||
|
||||
@@ -4,12 +4,14 @@ import { CaseCard } from '../../shared/case-card/case-card';
|
||||
import { ContentSection } from '../../shared/content-section/content-section';
|
||||
import { CtaRow } from '../../shared/cta-row/cta-row';
|
||||
import { MetricList } from '../../shared/metric-list/metric-list';
|
||||
import { RevealDirective } from '../../shared/motion/reveal.directive';
|
||||
import { PageHero } from '../../shared/page-hero/page-hero';
|
||||
import { SystemsMap } from '../../shared/systems-map/systems-map';
|
||||
|
||||
@Component({
|
||||
selector: 'app-home-page',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [PageHero, ContentSection, MetricList, CaseCard, CtaRow],
|
||||
imports: [PageHero, ContentSection, MetricList, CaseCard, CtaRow, SystemsMap, RevealDirective],
|
||||
templateUrl: './home.html',
|
||||
styleUrl: './home.scss',
|
||||
})
|
||||
|
||||
@@ -26,6 +26,17 @@ function accessibleName(root: HTMLElement, element: Element): string {
|
||||
return (element.getAttribute('aria-label') ?? element.textContent ?? '').trim();
|
||||
}
|
||||
|
||||
function assertNoDanglingReferences(root: HTMLElement): void {
|
||||
for (const attribute of ['aria-labelledby', 'aria-describedby'] as const) {
|
||||
for (const element of root.querySelectorAll(`[${attribute}]`)) {
|
||||
const ids = (element.getAttribute(attribute) ?? '').split(/\s+/).filter(Boolean);
|
||||
for (const id of ids) {
|
||||
expect(root.querySelector(`[id="${id}"]`), `${attribute} -> #${id}`).toBeTruthy();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertPageSemantics(root: HTMLElement): void {
|
||||
const headings = [...root.querySelectorAll('h1, h2, h3, h4, h5, h6')];
|
||||
expect(headings.filter((heading) => heading.tagName === 'H1')).toHaveLength(1);
|
||||
@@ -69,6 +80,34 @@ describe('page rendering, semantics and accessibility', () => {
|
||||
const root = harness.routeNativeElement as HTMLElement;
|
||||
expect(root).toBeTruthy();
|
||||
assertPageSemantics(root);
|
||||
assertNoDanglingReferences(root);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps every aria-labelledby and aria-describedby target in the document', async () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter(routes), { provide: SITE_CONTENT, useValue: SITE_CONTENT_DATA }],
|
||||
});
|
||||
|
||||
const harness = await RouterTestingHarness.create();
|
||||
const paths = [
|
||||
'/',
|
||||
'/en',
|
||||
'/projekte',
|
||||
'/en/projects',
|
||||
'/leistungen/ai-integration',
|
||||
'/en/services/ai-integration',
|
||||
'/kontakt',
|
||||
'/en/contact',
|
||||
'/stack',
|
||||
'/en/stack',
|
||||
];
|
||||
|
||||
for (const path of paths) {
|
||||
await harness.navigateByUrl(path);
|
||||
const root = harness.routeNativeElement as HTMLElement;
|
||||
expect(root).toBeTruthy();
|
||||
assertNoDanglingReferences(root);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -98,6 +137,33 @@ describe('page rendering, semantics and accessibility', () => {
|
||||
expect(SITE_CONTENT_DATA.de.pages.notFound.hero.headline).toBeTruthy();
|
||||
});
|
||||
|
||||
it('places the Systems Map between the profile block and the featured cases', async () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter(routes), { provide: SITE_CONTENT, useValue: SITE_CONTENT_DATA }],
|
||||
});
|
||||
|
||||
const harness = await RouterTestingHarness.create();
|
||||
|
||||
for (const path of ['/', '/en']) {
|
||||
await harness.navigateByUrl(path);
|
||||
const root = harness.routeNativeElement as HTMLElement;
|
||||
const metrics = root.querySelector('app-metric-list');
|
||||
const map = root.querySelector('app-systems-map');
|
||||
const firstCase = root.querySelector('app-case-card');
|
||||
|
||||
expect(metrics).toBeTruthy();
|
||||
expect(map).toBeTruthy();
|
||||
expect(firstCase).toBeTruthy();
|
||||
|
||||
const position = metrics!.compareDocumentPosition(map!);
|
||||
expect(position & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
const afterMap = map!.compareDocumentPosition(firstCase!);
|
||||
expect(afterMap & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
|
||||
assertPageSemantics(root);
|
||||
}
|
||||
});
|
||||
|
||||
it('sends the software service case CTA to the innofocus project anchor', async () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter(routes), { provide: SITE_CONTENT, useValue: SITE_CONTENT_DATA }],
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
[situationLabel]="copy.caseLabels.situation"
|
||||
[approachLabel]="copy.caseLabels.approach"
|
||||
[outcomeLabel]="copy.caseLabels.outcome"
|
||||
[metricsLabel]="copy.caseLabels.metrics"
|
||||
[stackLabel]="copy.caseLabels.stack"
|
||||
[tagsLabel]="copy.caseLabels.tags"
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { RouterTestingHarness } from '@angular/router/testing';
|
||||
import { routes } from '../../../app.routes';
|
||||
import { SITE_CONTENT } from '../../../core/content/content.token';
|
||||
import { SITE_CONTENT_DATA } from '../../../core/content/site-content';
|
||||
import { APP_LOCALES } from '../../../core/i18n/locale';
|
||||
import { routePath } from '../../../core/routing/route-paths';
|
||||
|
||||
describe('AI service offering groups', () => {
|
||||
it('renders delivered work and offers under their own localized labels', async () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter(routes), { provide: SITE_CONTENT, useValue: SITE_CONTENT_DATA }],
|
||||
});
|
||||
|
||||
const harness = await RouterTestingHarness.create();
|
||||
|
||||
for (const locale of APP_LOCALES) {
|
||||
const copy = SITE_CONTENT_DATA[locale].services.servicesAi;
|
||||
const delivered = copy.offerings.filter((offering) => offering.status === 'delivered');
|
||||
const offers = copy.offerings.filter((offering) => offering.status === 'offer');
|
||||
expect(delivered.length).toBeGreaterThan(0);
|
||||
expect(offers.length).toBeGreaterThan(0);
|
||||
|
||||
await harness.navigateByUrl(routePath('servicesAi', locale));
|
||||
const root = harness.routeNativeElement as HTMLElement;
|
||||
expect(root).toBeTruthy();
|
||||
|
||||
const deliveredGroup = root.querySelector(
|
||||
`[aria-labelledby="offerings-delivered-servicesAi"]`,
|
||||
);
|
||||
const offerGroup = root.querySelector(`[aria-labelledby="offerings-offer-servicesAi"]`);
|
||||
expect(deliveredGroup).toBeTruthy();
|
||||
expect(offerGroup).toBeTruthy();
|
||||
expect(deliveredGroup?.textContent).toContain(copy.deliveredOfferingsHeading);
|
||||
expect(offerGroup?.textContent).toContain(copy.offerOfferingsHeading);
|
||||
|
||||
for (const offering of delivered) {
|
||||
expect(deliveredGroup?.textContent).toContain(offering.title);
|
||||
expect(offerGroup?.textContent).not.toContain(offering.title);
|
||||
const note = copy.offeringCaseBackedLabel.replace(
|
||||
'{case}',
|
||||
SITE_CONTENT_DATA[locale].cases[offering.referenceCaseId!].client,
|
||||
);
|
||||
expect(deliveredGroup?.textContent).toContain(note);
|
||||
}
|
||||
|
||||
for (const offering of offers) {
|
||||
expect(offerGroup?.textContent).toContain(offering.title);
|
||||
expect(deliveredGroup?.textContent).not.toContain(offering.title);
|
||||
}
|
||||
|
||||
expect(deliveredGroup?.querySelector('[data-offering-status="offer"]')).toBeNull();
|
||||
expect(offerGroup?.querySelector('[data-offering-status="delivered"]')).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -6,15 +6,34 @@
|
||||
@if (section.id === 'sequence') {
|
||||
<app-process-steps [steps]="steps()" [labelledBy]="sequenceHeadingId()" />
|
||||
}
|
||||
@if (section.id === 'offer-boundary' && copy.offerings.length > 0) {
|
||||
<ul class="stack offerings">
|
||||
@for (offering of copy.offerings; track offering.id) {
|
||||
<li class="glass-surface">
|
||||
<h3>{{ offering.title }}</h3>
|
||||
<p>{{ offering.body }}</p>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
@if (section.id === 'scope' && deliveredOfferings().length > 0) {
|
||||
<section class="stack offerings-group" [attr.aria-labelledby]="deliveredHeadingId()">
|
||||
<h3 [id]="deliveredHeadingId()">{{ copy.deliveredOfferingsHeading }}</h3>
|
||||
<ul class="stack offerings">
|
||||
@for (offering of deliveredOfferings(); track offering.id) {
|
||||
<li class="glass-surface" [attr.data-offering-status]="offering.status">
|
||||
<h4>{{ offering.title }}</h4>
|
||||
<p>{{ offering.body }}</p>
|
||||
@if (caseBackedNote(offering); as note) {
|
||||
<p class="case-backed">{{ note }}</p>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
}
|
||||
@if (section.id === 'offer-boundary' && offerOfferings().length > 0) {
|
||||
<section class="stack offerings-group" [attr.aria-labelledby]="offerHeadingId()">
|
||||
<h3 [id]="offerHeadingId()">{{ copy.offerOfferingsHeading }}</h3>
|
||||
<ul class="stack offerings">
|
||||
@for (offering of offerOfferings(); track offering.id) {
|
||||
<li class="glass-surface" [attr.data-offering-status]="offering.status">
|
||||
<h4>{{ offering.title }}</h4>
|
||||
<p>{{ offering.body }}</p>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
}
|
||||
}
|
||||
<section class="stack" [attr.aria-labelledby]="'reference-' + copy.routeId">
|
||||
|
||||
@@ -12,12 +12,21 @@
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.offerings h3 {
|
||||
.offerings-group h3,
|
||||
.offerings h4 {
|
||||
margin: 0 0 var(--space-2);
|
||||
font-size: var(--text-lg);
|
||||
}
|
||||
|
||||
.offerings h4 {
|
||||
font-size: var(--text-md);
|
||||
}
|
||||
|
||||
.offerings p {
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.offerings .case-backed {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, inject, input } from '@angular/core';
|
||||
import {
|
||||
type OfferingCopy,
|
||||
type ProcessStepCopy,
|
||||
type ServicePageId,
|
||||
type ServiceSequenceCopy,
|
||||
@@ -42,4 +43,24 @@ export class ServicePageView {
|
||||
const section = this.page().sections.find((item) => item.id === 'sequence');
|
||||
return section ? `section-${section.id}` : null;
|
||||
});
|
||||
protected readonly deliveredOfferings = computed(() =>
|
||||
this.page().offerings.filter((offering) => offering.status === 'delivered'),
|
||||
);
|
||||
protected readonly offerOfferings = computed(() =>
|
||||
this.page().offerings.filter((offering) => offering.status === 'offer'),
|
||||
);
|
||||
protected readonly deliveredHeadingId = computed(() => `offerings-delivered-${this.routeId()}`);
|
||||
protected readonly offerHeadingId = computed(() => `offerings-offer-${this.routeId()}`);
|
||||
|
||||
protected caseBackedNote(offering: OfferingCopy): string | null {
|
||||
const caseId = offering.referenceCaseId;
|
||||
if (!caseId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.page().offeringCaseBackedLabel.replace(
|
||||
'{case}',
|
||||
this.content.caseStudy(caseId)().client,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
90
src/app/features/stack/stack-evidence.spec.ts
Normal file
90
src/app/features/stack/stack-evidence.spec.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { RouterTestingHarness } from '@angular/router/testing';
|
||||
import { routes } from '../../app.routes';
|
||||
import { SKILL_GRID_ITEM_NAMES } from '../../components/pages/skills/skills-grid/skills-grid';
|
||||
import { SITE_CONTENT } from '../../core/content/content.token';
|
||||
import { SITE_CONTENT_DATA } from '../../core/content/site-content';
|
||||
import { APP_LOCALES } from '../../core/i18n/locale';
|
||||
import { routePath } from '../../core/routing/route-paths';
|
||||
|
||||
const OVERCLAIMS = [
|
||||
'Der Stack, der auf diesen Seiten vorkommt',
|
||||
'The stack that appears on these pages',
|
||||
'Auswahl aus der öffentlichen Arbeit',
|
||||
'selection from the public work',
|
||||
];
|
||||
|
||||
function walkStrings(value: unknown, visit: (text: string) => void): void {
|
||||
if (typeof value === 'string') {
|
||||
visit(value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item) => walkStrings(item, visit));
|
||||
return;
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object') {
|
||||
Object.values(value).forEach((child) => walkStrings(child, visit));
|
||||
}
|
||||
}
|
||||
|
||||
function contentMentions(name: string): boolean {
|
||||
let found = false;
|
||||
walkStrings(SITE_CONTENT_DATA, (text) => {
|
||||
if (text.includes(name)) {
|
||||
found = true;
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
describe('stack evidence framing', () => {
|
||||
it('backs every skills-grid name with public copy or the evidence note', () => {
|
||||
for (const locale of APP_LOCALES) {
|
||||
const note = SITE_CONTENT_DATA[locale].stack.evidenceNote;
|
||||
expect(note.trim().length).toBeGreaterThan(40);
|
||||
|
||||
for (const name of SKILL_GRID_ITEM_NAMES) {
|
||||
expect(
|
||||
contentMentions(name) || note.length > 0,
|
||||
`${locale} skill "${name}" must appear in copy or be covered by the evidence note`,
|
||||
).toBe(true);
|
||||
}
|
||||
}
|
||||
|
||||
expect(SITE_CONTENT_DATA.de.stack.evidenceNote).not.toBe(
|
||||
SITE_CONTENT_DATA.en.stack.evidenceNote,
|
||||
);
|
||||
});
|
||||
|
||||
it('renders the evidence note and drops the old overclaiming sentences', async () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [provideRouter(routes), { provide: SITE_CONTENT, useValue: SITE_CONTENT_DATA }],
|
||||
});
|
||||
|
||||
const harness = await RouterTestingHarness.create();
|
||||
|
||||
for (const locale of APP_LOCALES) {
|
||||
const note = SITE_CONTENT_DATA[locale].stack.evidenceNote;
|
||||
await harness.navigateByUrl(routePath('stack', locale));
|
||||
const root = harness.routeNativeElement as HTMLElement;
|
||||
const rendered = root.querySelector('[role="note"]');
|
||||
|
||||
expect(rendered?.textContent).toContain(note);
|
||||
expect(root.textContent).toContain(note);
|
||||
|
||||
for (const claim of OVERCLAIMS) {
|
||||
expect(root.textContent).not.toContain(claim);
|
||||
expect(SITE_CONTENT_DATA[locale].stack.hero.headline).not.toContain(claim);
|
||||
expect(
|
||||
SITE_CONTENT_DATA[locale].stack.sections
|
||||
.map((section) => section.body?.join(' ') ?? '')
|
||||
.join(' '),
|
||||
).not.toContain(claim);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@
|
||||
@for (section of copy.sections; track section.id) {
|
||||
<app-content-section [section]="section" />
|
||||
}
|
||||
<p class="evidence-note" role="note">{{ copy.evidenceNote }}</p>
|
||||
<app-skills-grid [categoryTitles]="categoryTitles()" />
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -36,7 +36,10 @@
|
||||
</section>
|
||||
|
||||
@if (caseStudy().metrics.length > 0) {
|
||||
<app-metric-list [metrics]="caseStudy().metrics" [labelledBy]="metricsLabelId()" />
|
||||
<section class="stack" [attr.aria-labelledby]="metricsLabelId()">
|
||||
<h3 [id]="metricsLabelId()">{{ metricsLabel() }}</h3>
|
||||
<app-metric-list [metrics]="caseStudy().metrics" [labelledBy]="metricsLabelId()" />
|
||||
</section>
|
||||
}
|
||||
|
||||
<section class="stack" [attr.aria-labelledby]="caseStudy().id + '-stack'">
|
||||
|
||||
@@ -14,6 +14,7 @@ export class CaseStudy {
|
||||
readonly situationLabel = input.required<string>();
|
||||
readonly approachLabel = input.required<string>();
|
||||
readonly outcomeLabel = input.required<string>();
|
||||
readonly metricsLabel = input.required<string>();
|
||||
readonly stackLabel = input.required<string>();
|
||||
readonly tagsLabel = input.required<string>();
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<button
|
||||
#trigger
|
||||
type="button"
|
||||
class="command-palette-trigger"
|
||||
aria-haspopup="dialog"
|
||||
[attr.aria-expanded]="open()"
|
||||
[attr.aria-controls]="open() ? dialogId : null"
|
||||
[attr.aria-label]="copy().triggerLabel"
|
||||
(click)="onTriggerClick()"
|
||||
>
|
||||
<span>{{ copy().triggerLabel }}</span>
|
||||
<kbd>{{ shortcutHint() }}</kbd>
|
||||
</button>
|
||||
@@ -0,0 +1,32 @@
|
||||
:host {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.command-palette-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: 1px solid var(--surface-glass-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--color-text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.command-palette-trigger kbd {
|
||||
padding: 0.1rem var(--space-2);
|
||||
border: 1px solid var(--surface-glass-border);
|
||||
border-radius: var(--radius-sm);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--text-xs);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.command-palette-trigger:hover {
|
||||
border-color: var(--surface-glass-border-strong);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
afterNextRender,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
ElementRef,
|
||||
inject,
|
||||
Injector,
|
||||
signal,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { SIGNATURE_COPY } from '../../../core/content/signature-copy';
|
||||
import { LocaleService } from '../../../core/i18n/locale.service';
|
||||
import { isApplePlatform, isBrowserPlatform } from '../../../core/platform/browser';
|
||||
import { CommandPaletteService } from '../command-palette.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-command-palette-trigger',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './command-palette-trigger.html',
|
||||
styleUrl: './command-palette-trigger.scss',
|
||||
})
|
||||
export class CommandPaletteTrigger {
|
||||
private readonly palette = inject(CommandPaletteService);
|
||||
private readonly localeService = inject(LocaleService);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly isBrowser = isBrowserPlatform();
|
||||
private readonly applePlatform = isApplePlatform();
|
||||
|
||||
protected readonly triggerRef = viewChild<ElementRef<HTMLButtonElement>>('trigger');
|
||||
protected readonly useAppleHint = signal(false);
|
||||
protected readonly copy = computed(() => SIGNATURE_COPY[this.localeService.locale()].palette);
|
||||
protected readonly shortcutHint = computed(() =>
|
||||
this.useAppleHint() ? this.copy().shortcutHintApple : this.copy().shortcutHint,
|
||||
);
|
||||
protected readonly open = this.palette.open;
|
||||
protected readonly dialogId = this.palette.dialogId;
|
||||
|
||||
constructor() {
|
||||
afterNextRender(
|
||||
() => {
|
||||
if (this.isBrowser) {
|
||||
this.useAppleHint.set(this.applePlatform);
|
||||
}
|
||||
},
|
||||
{ injector: this.injector },
|
||||
);
|
||||
}
|
||||
|
||||
protected onTriggerClick(): void {
|
||||
const trigger = this.triggerRef()?.nativeElement;
|
||||
trigger?.focus();
|
||||
this.palette.openPalette(trigger ?? null);
|
||||
}
|
||||
}
|
||||
72
src/app/shared/command-palette/command-palette.html
Normal file
72
src/app/shared/command-palette/command-palette.html
Normal file
@@ -0,0 +1,72 @@
|
||||
@if (open()) {
|
||||
<div class="command-palette-overlay">
|
||||
<div class="command-palette-scrim" aria-hidden="true"></div>
|
||||
<div
|
||||
#dialog
|
||||
class="command-palette-dialog glass-surface"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
[id]="dialogId"
|
||||
[attr.aria-labelledby]="titleId"
|
||||
[attr.aria-describedby]="descriptionId"
|
||||
(keydown)="onDialogKeydown($event, dialog)"
|
||||
>
|
||||
<div class="command-palette-header">
|
||||
<div>
|
||||
<h2 [id]="titleId" class="command-palette-title">{{ copy().dialogTitle }}</h2>
|
||||
<p [id]="descriptionId" class="command-palette-description">
|
||||
{{ copy().dialogDescription }}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" class="command-palette-close" (click)="closePalette()">
|
||||
{{ copy().closeLabel }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form class="command-palette-form" (submit)="onSubmit($event)">
|
||||
<label [attr.for]="inputId">{{ copy().inputLabel }}</label>
|
||||
<input
|
||||
#commandInput
|
||||
[id]="inputId"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
autocapitalize="off"
|
||||
spellcheck="false"
|
||||
[attr.placeholder]="copy().inputPlaceholder"
|
||||
[value]="query()"
|
||||
(input)="onQueryInput($event)"
|
||||
/>
|
||||
|
||||
<p class="command-palette-kicker" [id]="suggestionsId">{{ copy().suggestionsLabel }}</p>
|
||||
@if (suggestions().length === 0) {
|
||||
<p class="command-palette-empty">{{ copy().emptySuggestions }}</p>
|
||||
} @else {
|
||||
<ul class="command-palette-suggestions" [attr.aria-labelledby]="suggestionsId">
|
||||
@for (command of suggestions(); track command.id) {
|
||||
<li>
|
||||
<button type="button" (click)="runDefinition(command)">
|
||||
<span>{{ command.input }}</span>
|
||||
<span>{{ copy().commandDescriptions[command.id] }}</span>
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</form>
|
||||
|
||||
<div
|
||||
class="command-palette-output"
|
||||
role="log"
|
||||
aria-live="polite"
|
||||
aria-atomic="false"
|
||||
[attr.aria-label]="copy().outputLabel"
|
||||
>
|
||||
<ul>
|
||||
@for (line of output(); track line.id) {
|
||||
<li>{{ line.text }}</li>
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
144
src/app/shared/command-palette/command-palette.scss
Normal file
144
src/app/shared/command-palette/command-palette.scss
Normal file
@@ -0,0 +1,144 @@
|
||||
:host {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
.command-palette-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 40;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: var(--space-4);
|
||||
}
|
||||
|
||||
.command-palette-scrim {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: var(--color-surface);
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.command-palette-dialog {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
width: min(100%, 40rem);
|
||||
max-height: min(36rem, 90vh);
|
||||
overflow: auto;
|
||||
padding: var(--space-5);
|
||||
border-radius: var(--radius-lg);
|
||||
}
|
||||
|
||||
.command-palette-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.command-palette-title,
|
||||
.command-palette-description,
|
||||
.command-palette-kicker,
|
||||
.command-palette-empty,
|
||||
.command-palette-output ul,
|
||||
.command-palette-suggestions {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.command-palette-title {
|
||||
font-size: var(--text-lg);
|
||||
line-height: var(--leading-tight);
|
||||
}
|
||||
|
||||
.command-palette-description,
|
||||
.command-palette-empty,
|
||||
.command-palette-output {
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.command-palette-close {
|
||||
min-height: 2.75rem;
|
||||
padding-inline: var(--space-3);
|
||||
border: 1px solid var(--surface-glass-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
color: var(--color-text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.command-palette-form {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.command-palette-form input {
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: 1px solid var(--surface-glass-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-surface-raised);
|
||||
color: var(--color-text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.command-palette-kicker {
|
||||
font-size: var(--text-xs);
|
||||
letter-spacing: var(--tracking-wide);
|
||||
text-transform: uppercase;
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.command-palette-suggestions,
|
||||
.command-palette-output ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.command-palette-suggestions {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.command-palette-suggestions button {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
width: 100%;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: 1px solid var(--surface-glass-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-surface-raised);
|
||||
color: var(--color-text);
|
||||
font: inherit;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.command-palette-suggestions button span:first-child {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.command-palette-suggestions button span:last-child,
|
||||
.command-palette-output {
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.command-palette-output {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.command-palette-close:hover,
|
||||
.command-palette-suggestions button:hover {
|
||||
border-color: var(--surface-glass-border-strong);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.command-palette-overlay,
|
||||
.command-palette-dialog {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
115
src/app/shared/command-palette/command-palette.service.ts
Normal file
115
src/app/shared/command-palette/command-palette.service.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
|
||||
import {
|
||||
afterNextRender,
|
||||
DestroyRef,
|
||||
inject,
|
||||
Injectable,
|
||||
Injector,
|
||||
PLATFORM_ID,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CommandPaletteService {
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
|
||||
|
||||
readonly open = signal(false);
|
||||
readonly dialogId = 'command-palette-dialog';
|
||||
readonly titleId = 'command-palette-title';
|
||||
readonly descriptionId = 'command-palette-description';
|
||||
readonly inputId = 'command-palette-input';
|
||||
readonly suggestionsId = 'command-palette-suggestions';
|
||||
|
||||
private opener: HTMLElement | null = null;
|
||||
private previousOverflow = '';
|
||||
private scrollLocked = false;
|
||||
|
||||
constructor() {
|
||||
afterNextRender(
|
||||
() => {
|
||||
if (!this.isBrowser) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.document.addEventListener('keydown', this.onDocumentKeydown);
|
||||
},
|
||||
{ injector: this.injector },
|
||||
);
|
||||
|
||||
this.destroyRef.onDestroy(() => this.teardown());
|
||||
}
|
||||
|
||||
openPalette(opener?: HTMLElement | null): void {
|
||||
if (this.open()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const active = opener ?? this.document.activeElement;
|
||||
this.opener = active instanceof HTMLElement ? active : null;
|
||||
this.lockScroll();
|
||||
this.open.set(true);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (!this.open()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.open.set(false);
|
||||
this.unlockScroll();
|
||||
this.restoreFocus();
|
||||
}
|
||||
|
||||
private restoreFocus(): void {
|
||||
const opener = this.opener;
|
||||
this.opener = null;
|
||||
|
||||
afterNextRender(
|
||||
() => {
|
||||
if (opener instanceof HTMLElement && opener.isConnected) {
|
||||
opener.focus();
|
||||
}
|
||||
},
|
||||
{ injector: this.injector },
|
||||
);
|
||||
}
|
||||
|
||||
private lockScroll(): void {
|
||||
if (!this.isBrowser || this.scrollLocked) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.previousOverflow = this.document.body.style.overflow;
|
||||
this.document.body.style.overflow = 'hidden';
|
||||
this.scrollLocked = true;
|
||||
}
|
||||
|
||||
private unlockScroll(): void {
|
||||
if (!this.isBrowser || !this.scrollLocked) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.document.body.style.overflow = this.previousOverflow;
|
||||
this.previousOverflow = '';
|
||||
this.scrollLocked = false;
|
||||
}
|
||||
|
||||
private teardown(): void {
|
||||
this.document.removeEventListener('keydown', this.onDocumentKeydown);
|
||||
this.unlockScroll();
|
||||
this.open.set(false);
|
||||
this.opener = null;
|
||||
}
|
||||
|
||||
private readonly onDocumentKeydown = (event: KeyboardEvent): void => {
|
||||
if (event.key.toLowerCase() !== 'k' || !(event.ctrlKey || event.metaKey) || event.altKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
this.openPalette();
|
||||
};
|
||||
}
|
||||
334
src/app/shared/command-palette/command-palette.spec.ts
Normal file
334
src/app/shared/command-palette/command-palette.spec.ts
Normal file
@@ -0,0 +1,334 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { ApplicationRef, Component, inject, PLATFORM_ID } from '@angular/core';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import { SIGNATURE_COPY } from '../../core/content/signature-copy';
|
||||
import { SITE_CONFIG } from '../../core/content/site-config';
|
||||
import { APP_LOCALES, type AppLocale } from '../../core/i18n/locale';
|
||||
import { LocaleService } from '../../core/i18n/locale.service';
|
||||
import { NavigationService } from '../../core/navigation/navigation.service';
|
||||
import { CommandPalette } from './command-palette';
|
||||
import { CommandPaletteTrigger } from './command-palette-trigger/command-palette-trigger';
|
||||
import { CommandPaletteService } from './command-palette.service';
|
||||
import { COMMAND_IDS, COMMANDS } from './commands';
|
||||
|
||||
@Component({
|
||||
selector: 'app-palette-host',
|
||||
imports: [CommandPaletteTrigger, CommandPalette],
|
||||
template: `
|
||||
<div class="site" [attr.inert]="palette.open() ? '' : null">
|
||||
<app-command-palette-trigger></app-command-palette-trigger>
|
||||
</div>
|
||||
<app-command-palette></app-command-palette>
|
||||
`,
|
||||
})
|
||||
class PaletteHost {
|
||||
readonly palette = inject(CommandPaletteService);
|
||||
}
|
||||
|
||||
describe('CommandPalette', () => {
|
||||
afterEach(() => {
|
||||
document.body.style.overflow = '';
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function createFixture(
|
||||
locale: AppLocale = 'de',
|
||||
extraProviders: { provide: unknown; useValue: unknown }[] = [],
|
||||
): Promise<ComponentFixture<PaletteHost>> {
|
||||
TestBed.resetTestingModule();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [PaletteHost],
|
||||
providers: [provideRouter([]), ...extraProviders],
|
||||
}).compileComponents();
|
||||
|
||||
TestBed.inject(LocaleService).setLocale(locale);
|
||||
const fixture = TestBed.createComponent(PaletteHost);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
async function flush(fixture: ComponentFixture<PaletteHost>): Promise<void> {
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
TestBed.inject(ApplicationRef).tick();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
}
|
||||
|
||||
function trigger(fixture: ComponentFixture<PaletteHost>): HTMLButtonElement {
|
||||
return fixture.nativeElement.querySelector('.command-palette-trigger');
|
||||
}
|
||||
|
||||
function dialog(fixture: ComponentFixture<PaletteHost>): HTMLElement | null {
|
||||
return fixture.nativeElement.querySelector('[role="dialog"]');
|
||||
}
|
||||
|
||||
function site(fixture: ComponentFixture<PaletteHost>): HTMLElement {
|
||||
return fixture.nativeElement.querySelector('.site');
|
||||
}
|
||||
|
||||
async function openViaTrigger(fixture: ComponentFixture<PaletteHost>): Promise<void> {
|
||||
trigger(fixture).click();
|
||||
await flush(fixture);
|
||||
}
|
||||
|
||||
async function submitQuery(fixture: ComponentFixture<PaletteHost>, value: string): Promise<void> {
|
||||
const input = fixture.nativeElement.querySelector('input');
|
||||
expect(input).toBeTruthy();
|
||||
input.value = value;
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
fixture.nativeElement
|
||||
.querySelector('form')
|
||||
.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
|
||||
await flush(fixture);
|
||||
}
|
||||
|
||||
function outputText(fixture: ComponentFixture<PaletteHost>): string {
|
||||
return fixture.nativeElement.querySelector('.command-palette-output')?.textContent ?? '';
|
||||
}
|
||||
|
||||
function focusable(container: HTMLElement): HTMLElement[] {
|
||||
return Array.from(
|
||||
container.querySelectorAll<HTMLElement>(
|
||||
'a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
|
||||
),
|
||||
).filter((element) => element.tabIndex >= 0);
|
||||
}
|
||||
|
||||
it.each(APP_LOCALES)(
|
||||
'renders the trigger and not the dialog on the server (%s)',
|
||||
async (locale) => {
|
||||
const fixture = await createFixture(locale, [{ provide: PLATFORM_ID, useValue: 'server' }]);
|
||||
expect(trigger(fixture)).toBeTruthy();
|
||||
expect(dialog(fixture)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(APP_LOCALES)('opens from the trigger and focuses the input (%s)', async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
await openViaTrigger(fixture);
|
||||
const input = fixture.nativeElement.querySelector('input');
|
||||
expect(dialog(fixture)).toBeTruthy();
|
||||
expect(document.activeElement).toBe(input);
|
||||
});
|
||||
|
||||
it.each(APP_LOCALES)(
|
||||
'opens from Ctrl+K and Meta+K and prevents the default (%s)',
|
||||
async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
await flush(fixture);
|
||||
|
||||
for (const modifier of [{ ctrlKey: true }, { metaKey: true }] as const) {
|
||||
const openDialog = dialog(fixture);
|
||||
if (openDialog) {
|
||||
openDialog.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
await flush(fixture);
|
||||
}
|
||||
|
||||
const event = new KeyboardEvent('keydown', {
|
||||
key: 'k',
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
...modifier,
|
||||
});
|
||||
const prevent = vi.spyOn(event, 'preventDefault');
|
||||
document.dispatchEvent(event);
|
||||
await flush(fixture);
|
||||
|
||||
expect(prevent).toHaveBeenCalled();
|
||||
expect(dialog(fixture)).toBeTruthy();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(APP_LOCALES)('closes on Escape and returns focus to the trigger (%s)', async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
await openViaTrigger(fixture);
|
||||
const openDialog = dialog(fixture);
|
||||
expect(openDialog).toBeTruthy();
|
||||
|
||||
openDialog?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
await flush(fixture);
|
||||
|
||||
expect(dialog(fixture)).toBeNull();
|
||||
expect(document.activeElement).toBe(trigger(fixture));
|
||||
});
|
||||
|
||||
it.each(APP_LOCALES)('closes from the close button and restores focus (%s)', async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
await openViaTrigger(fixture);
|
||||
const closeButton = fixture.nativeElement.querySelector('.command-palette-close');
|
||||
closeButton.click();
|
||||
await flush(fixture);
|
||||
|
||||
expect(dialog(fixture)).toBeNull();
|
||||
expect(document.activeElement).toBe(trigger(fixture));
|
||||
});
|
||||
|
||||
it.each(APP_LOCALES)('wraps Tab and Shift+Tab inside the dialog (%s)', async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
await openViaTrigger(fixture);
|
||||
const openDialog = dialog(fixture);
|
||||
expect(openDialog).toBeTruthy();
|
||||
|
||||
const items = focusable(openDialog as HTMLElement);
|
||||
const first = items[0];
|
||||
const last = items[items.length - 1];
|
||||
|
||||
last.focus();
|
||||
openDialog?.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true }),
|
||||
);
|
||||
expect(document.activeElement).toBe(first);
|
||||
|
||||
first.focus();
|
||||
openDialog?.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, bubbles: true, cancelable: true }),
|
||||
);
|
||||
expect(document.activeElement).toBe(last);
|
||||
});
|
||||
|
||||
it.each(APP_LOCALES)(
|
||||
'marks .site inert while open and removes it on close (%s)',
|
||||
async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
expect(site(fixture).hasAttribute('inert')).toBe(false);
|
||||
|
||||
await openViaTrigger(fixture);
|
||||
expect(site(fixture).hasAttribute('inert')).toBe(true);
|
||||
|
||||
fixture.nativeElement.querySelector('.command-palette-close').click();
|
||||
await flush(fixture);
|
||||
expect(site(fixture).hasAttribute('inert')).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(APP_LOCALES)(
|
||||
'locks body overflow while open and restores it on close (%s)',
|
||||
async (locale) => {
|
||||
document.body.style.overflow = 'auto';
|
||||
const fixture = await createFixture(locale);
|
||||
await openViaTrigger(fixture);
|
||||
expect(document.body.style.overflow).toBe('hidden');
|
||||
|
||||
fixture.nativeElement.querySelector('.command-palette-close').click();
|
||||
await flush(fixture);
|
||||
expect(document.body.style.overflow).toBe('auto');
|
||||
document.body.style.overflow = '';
|
||||
},
|
||||
);
|
||||
|
||||
it.each(APP_LOCALES)('writes localized help, playful replies and clear (%s)', async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
await openViaTrigger(fixture);
|
||||
const copy = SIGNATURE_COPY[locale].palette;
|
||||
|
||||
await submitQuery(fixture, 'help');
|
||||
const helpText = outputText(fixture);
|
||||
expect(helpText).toContain(copy.helpIntro);
|
||||
for (const command of COMMANDS) {
|
||||
expect(helpText).toContain(command.input);
|
||||
expect(helpText).toContain(copy.commandDescriptions[command.id]);
|
||||
}
|
||||
expect(COMMAND_IDS.every((id) => helpText.includes(copy.commandDescriptions[id]))).toBe(true);
|
||||
|
||||
await submitQuery(fixture, 'brew');
|
||||
expect(outputText(fixture)).toContain(copy.responses.brew);
|
||||
await submitQuery(fixture, 'ignite');
|
||||
expect(outputText(fixture)).toContain(copy.responses.ignite);
|
||||
await submitQuery(fixture, 'rev');
|
||||
expect(outputText(fixture)).toContain(copy.responses.rev);
|
||||
|
||||
await submitQuery(fixture, 'clear');
|
||||
expect(outputText(fixture).trim()).toBe(copy.clearedMessage);
|
||||
});
|
||||
|
||||
it.each(APP_LOCALES)(
|
||||
'navigates projects, services ai and contact through NavigationService (%s)',
|
||||
async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
const router = TestBed.inject(Router);
|
||||
const navigation = TestBed.inject(NavigationService);
|
||||
const navigate = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||
|
||||
await openViaTrigger(fixture);
|
||||
await submitQuery(fixture, 'projects');
|
||||
expect(navigate).toHaveBeenCalledWith(navigation.link('projects'));
|
||||
expect(dialog(fixture)).toBeNull();
|
||||
|
||||
await openViaTrigger(fixture);
|
||||
await submitQuery(fixture, 'services ai');
|
||||
expect(navigate).toHaveBeenCalledWith(navigation.link('servicesAi'));
|
||||
|
||||
await openViaTrigger(fixture);
|
||||
await submitQuery(fixture, 'contact');
|
||||
expect(navigate).toHaveBeenCalledWith(navigation.link('contact'));
|
||||
},
|
||||
);
|
||||
|
||||
it.each(APP_LOCALES)('opens the CV in a new tab and never navigates (%s)', async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
const router = TestBed.inject(Router);
|
||||
const navigate = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||
const view = TestBed.inject(DOCUMENT).defaultView;
|
||||
const open = vi.spyOn(view as Window, 'open').mockReturnValue(null);
|
||||
|
||||
await openViaTrigger(fixture);
|
||||
await submitQuery(fixture, 'cv');
|
||||
|
||||
expect(open).toHaveBeenCalledWith(SITE_CONFIG.cvAssetPath, '_blank', 'noopener,noreferrer');
|
||||
expect(navigate).not.toHaveBeenCalled();
|
||||
expect(outputText(fixture)).toContain(SIGNATURE_COPY[locale].palette.cvOpened);
|
||||
});
|
||||
|
||||
it.each(APP_LOCALES)(
|
||||
'reports unknown input without navigating or opening a window (%s)',
|
||||
async (locale) => {
|
||||
const fixture = await createFixture(locale);
|
||||
const router = TestBed.inject(Router);
|
||||
const navigate = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||
const view = TestBed.inject(DOCUMENT).defaultView;
|
||||
const open = vi.spyOn(view as Window, 'open').mockReturnValue(null);
|
||||
const raw = 'rm -rf /';
|
||||
|
||||
await openViaTrigger(fixture);
|
||||
await submitQuery(fixture, raw);
|
||||
|
||||
expect(outputText(fixture)).toContain(
|
||||
SIGNATURE_COPY[locale].palette.unknownCommand.replace('{command}', raw),
|
||||
);
|
||||
expect(navigate).not.toHaveBeenCalled();
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('removes the document keydown listener on destroy', async () => {
|
||||
const add = vi.spyOn(document, 'addEventListener');
|
||||
const fixture = await createFixture();
|
||||
await flush(fixture);
|
||||
|
||||
const added = add.mock.calls.find((call) => call[0] === 'keydown');
|
||||
expect(added).toBeTruthy();
|
||||
|
||||
const remove = vi.spyOn(document, 'removeEventListener');
|
||||
fixture.destroy();
|
||||
TestBed.resetTestingModule();
|
||||
|
||||
expect(remove).toHaveBeenCalledWith('keydown', added?.[1]);
|
||||
});
|
||||
|
||||
it('registers no document listener on the server', async () => {
|
||||
const add = vi.spyOn(document, 'addEventListener');
|
||||
await createFixture('de', [{ provide: PLATFORM_ID, useValue: 'server' }]);
|
||||
expect(add.mock.calls.some((call) => call[0] === 'keydown')).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the trigger aria-label stable and shows the Ctrl hint before hydration', async () => {
|
||||
const fixture = await createFixture('de', [{ provide: PLATFORM_ID, useValue: 'server' }]);
|
||||
const button = trigger(fixture);
|
||||
expect(button.getAttribute('aria-label')).toBe(SIGNATURE_COPY.de.palette.triggerLabel);
|
||||
expect(button.querySelector('kbd')?.textContent).toBe(SIGNATURE_COPY.de.palette.shortcutHint);
|
||||
});
|
||||
});
|
||||
209
src/app/shared/command-palette/command-palette.ts
Normal file
209
src/app/shared/command-palette/command-palette.ts
Normal file
@@ -0,0 +1,209 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import {
|
||||
afterNextRender,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
ElementRef,
|
||||
inject,
|
||||
Injector,
|
||||
signal,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { SIGNATURE_COPY } from '../../core/content/signature-copy';
|
||||
import { SITE_CONFIG } from '../../core/content/site-config';
|
||||
import { LocaleService } from '../../core/i18n/locale.service';
|
||||
import { NavigationService } from '../../core/navigation/navigation.service';
|
||||
import { isBrowserPlatform } from '../../core/platform/browser';
|
||||
import { CommandPaletteService } from './command-palette.service';
|
||||
import {
|
||||
COMMAND_IDS,
|
||||
COMMANDS,
|
||||
parseCommand,
|
||||
suggestCommands,
|
||||
type CommandDefinition,
|
||||
} from './commands';
|
||||
|
||||
let commandPaletteOutputId = 0;
|
||||
|
||||
@Component({
|
||||
selector: 'app-command-palette',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './command-palette.html',
|
||||
styleUrl: './command-palette.scss',
|
||||
})
|
||||
export class CommandPalette {
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly router = inject(Router);
|
||||
private readonly navigation = inject(NavigationService);
|
||||
private readonly localeService = inject(LocaleService);
|
||||
private readonly palette = inject(CommandPaletteService);
|
||||
private readonly isBrowser = isBrowserPlatform();
|
||||
|
||||
private readonly inputRef = viewChild<ElementRef<HTMLInputElement>>('commandInput');
|
||||
|
||||
protected readonly dialogId = this.palette.dialogId;
|
||||
protected readonly titleId = this.palette.titleId;
|
||||
protected readonly descriptionId = this.palette.descriptionId;
|
||||
protected readonly inputId = this.palette.inputId;
|
||||
protected readonly suggestionsId = this.palette.suggestionsId;
|
||||
protected readonly open = this.palette.open;
|
||||
|
||||
protected readonly query = signal('');
|
||||
protected readonly output = signal<readonly { id: number; text: string }[]>([]);
|
||||
|
||||
protected readonly copy = computed(() => SIGNATURE_COPY[this.localeService.locale()].palette);
|
||||
protected readonly suggestions = computed(() =>
|
||||
suggestCommands(this.query(), this.localeService.locale()),
|
||||
);
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
if (!this.open()) {
|
||||
return;
|
||||
}
|
||||
|
||||
afterNextRender(
|
||||
() => {
|
||||
this.inputRef()?.nativeElement.focus();
|
||||
},
|
||||
{ injector: this.injector },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
protected onQueryInput(event: Event): void {
|
||||
const target = event.target;
|
||||
|
||||
if (!(target instanceof HTMLInputElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.query.set(target.value);
|
||||
}
|
||||
|
||||
protected onSubmit(event: Event): void {
|
||||
event.preventDefault();
|
||||
this.runRaw(this.query());
|
||||
}
|
||||
|
||||
protected onDialogKeydown(event: KeyboardEvent, dialog: HTMLElement): void {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
this.closePalette();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key !== 'Tab') {
|
||||
return;
|
||||
}
|
||||
|
||||
const focusable = this.focusableElements(dialog);
|
||||
|
||||
if (focusable.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const first = focusable[0];
|
||||
const last = focusable[focusable.length - 1];
|
||||
const active = this.document.activeElement;
|
||||
|
||||
if (event.shiftKey && active === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!event.shiftKey && active === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
protected runDefinition(definition: CommandDefinition): void {
|
||||
const copy = this.copy();
|
||||
|
||||
switch (definition.action.kind) {
|
||||
case 'navigate': {
|
||||
void this.router.navigate(this.navigation.link(definition.action.routeId));
|
||||
this.append(copy.navigating.replace('{target}', definition.input));
|
||||
this.closePalette();
|
||||
return;
|
||||
}
|
||||
case 'openCv': {
|
||||
if (this.isBrowser) {
|
||||
this.document.defaultView?.open(SITE_CONFIG.cvAssetPath, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
|
||||
this.append(copy.cvOpened);
|
||||
return;
|
||||
}
|
||||
case 'message': {
|
||||
this.appendMessage(definition.action.messageKey);
|
||||
return;
|
||||
}
|
||||
case 'clear': {
|
||||
this.output.set([]);
|
||||
this.append(copy.clearedMessage);
|
||||
return;
|
||||
}
|
||||
case 'close': {
|
||||
this.closePalette();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected closePalette(): void {
|
||||
this.palette.close();
|
||||
}
|
||||
|
||||
private runRaw(raw: string): void {
|
||||
const match = parseCommand(raw);
|
||||
|
||||
if (match.kind === 'empty') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (match.kind === 'unknown') {
|
||||
this.append(this.copy().unknownCommand.replace('{command}', match.input));
|
||||
return;
|
||||
}
|
||||
|
||||
this.runDefinition(match.definition);
|
||||
}
|
||||
|
||||
private appendMessage(key: 'help' | 'brew' | 'ignite' | 'rev'): void {
|
||||
const copy = this.copy();
|
||||
|
||||
if (key === 'help') {
|
||||
const lines = [
|
||||
copy.helpIntro,
|
||||
...COMMAND_IDS.map((id) => {
|
||||
const command = COMMANDS.find((entry) => entry.id === id);
|
||||
const input = command?.input ?? id;
|
||||
return `${input} — ${copy.commandDescriptions[id]}`;
|
||||
}),
|
||||
];
|
||||
this.append(lines.join('\n'));
|
||||
return;
|
||||
}
|
||||
|
||||
this.append(copy.responses[key]);
|
||||
}
|
||||
|
||||
private append(text: string): void {
|
||||
this.output.update((lines) => [...lines, { id: commandPaletteOutputId++, text }]);
|
||||
}
|
||||
|
||||
private focusableElements(container: HTMLElement): HTMLElement[] {
|
||||
return Array.from(
|
||||
container.querySelectorAll<HTMLElement>(
|
||||
'a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
|
||||
),
|
||||
).filter((element) => !element.hasAttribute('disabled') && element.tabIndex >= 0);
|
||||
}
|
||||
}
|
||||
79
src/app/shared/command-palette/commands.spec.ts
Normal file
79
src/app/shared/command-palette/commands.spec.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { APP_LOCALES } from '../../core/i18n/locale';
|
||||
import {
|
||||
COMMAND_IDS,
|
||||
COMMANDS,
|
||||
normalizeCommandInput,
|
||||
parseCommand,
|
||||
suggestCommands,
|
||||
type CommandId,
|
||||
} from './commands';
|
||||
|
||||
describe('command parsing', () => {
|
||||
it('collapses whitespace and lowercases input', () => {
|
||||
expect(normalizeCommandInput(' Services AI ')).toBe('services ai');
|
||||
expect(normalizeCommandInput('HELP')).toBe('help');
|
||||
});
|
||||
|
||||
it('resolves every CommandId from its canonical input and aliases in both locales', () => {
|
||||
for (const command of COMMANDS) {
|
||||
const canonical = parseCommand(command.input);
|
||||
expect(canonical).toEqual({ kind: 'command', definition: command });
|
||||
|
||||
for (const locale of APP_LOCALES) {
|
||||
for (const alias of command.aliases[locale]) {
|
||||
expect(parseCommand(alias)).toEqual({ kind: 'command', definition: command });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(COMMANDS.map((command) => command.id)).toEqual([...COMMAND_IDS]);
|
||||
});
|
||||
|
||||
it('treats hostile and prototype inputs as unknown without side effects', () => {
|
||||
const prototypeNames = Object.getOwnPropertyNames(Object.prototype);
|
||||
const hostile = [
|
||||
'rm -rf /',
|
||||
'eval(1+1)',
|
||||
'new Function()',
|
||||
'<script>alert(1)</script>',
|
||||
'__proto__',
|
||||
'constructor',
|
||||
'toString',
|
||||
'hasOwnProperty',
|
||||
];
|
||||
|
||||
for (const input of hostile) {
|
||||
expect(parseCommand(input)).toEqual({ kind: 'unknown', input });
|
||||
}
|
||||
|
||||
expect(parseCommand('')).toEqual({ kind: 'empty' });
|
||||
expect(parseCommand(' ')).toEqual({ kind: 'empty' });
|
||||
expect(Object.getOwnPropertyNames(Object.prototype)).toEqual(prototypeNames);
|
||||
expect(Object.prototype).not.toHaveProperty('polluted');
|
||||
});
|
||||
|
||||
it('returns an equal result for the same input across repeated calls', () => {
|
||||
const samples = ['help', 'services ai', ' ', 'unknown-token', '__proto__'];
|
||||
|
||||
for (const sample of samples) {
|
||||
expect(parseCommand(sample)).toEqual(parseCommand(sample));
|
||||
}
|
||||
});
|
||||
|
||||
it('suggests commands in a stable COMMAND_IDS order and filters by prefix', () => {
|
||||
const emptyDe = suggestCommands('', 'de').map((command) => command.id);
|
||||
const emptyEn = suggestCommands('', 'en').map((command) => command.id);
|
||||
const expectedIds: CommandId[] = [...COMMAND_IDS];
|
||||
|
||||
expect(emptyDe).toEqual(expectedIds);
|
||||
expect(emptyEn).toEqual(expectedIds);
|
||||
expect(suggestCommands('c', 'en').map((command) => command.id)).toEqual([
|
||||
'cv',
|
||||
'contact',
|
||||
'clear',
|
||||
'close',
|
||||
]);
|
||||
expect(suggestCommands('lei', 'de').map((command) => command.id)).toEqual(['servicesAi']);
|
||||
expect(suggestCommands('c', 'de')).toEqual(suggestCommands('c', 'de'));
|
||||
});
|
||||
});
|
||||
145
src/app/shared/command-palette/commands.ts
Normal file
145
src/app/shared/command-palette/commands.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import { type CommandId } from '../../core/commands/command-ids';
|
||||
import { APP_LOCALES, type AppLocale } from '../../core/i18n/locale';
|
||||
import { type RouteId } from '../../core/routing/route-ids';
|
||||
|
||||
export { COMMAND_IDS, type CommandId } from '../../core/commands/command-ids';
|
||||
|
||||
export type CommandAction =
|
||||
| { readonly kind: 'navigate'; readonly routeId: RouteId }
|
||||
| { readonly kind: 'openCv' }
|
||||
| { readonly kind: 'message'; readonly messageKey: 'help' | 'brew' | 'ignite' | 'rev' }
|
||||
| { readonly kind: 'clear' }
|
||||
| { readonly kind: 'close' };
|
||||
|
||||
export interface CommandDefinition {
|
||||
readonly id: CommandId;
|
||||
readonly input: string;
|
||||
readonly aliases: Record<AppLocale, readonly string[]>;
|
||||
readonly action: CommandAction;
|
||||
}
|
||||
|
||||
export type CommandMatch =
|
||||
| { readonly kind: 'command'; readonly definition: CommandDefinition }
|
||||
| { readonly kind: 'empty' }
|
||||
| { readonly kind: 'unknown'; readonly input: string };
|
||||
|
||||
export const COMMANDS: readonly CommandDefinition[] = [
|
||||
{
|
||||
id: 'help',
|
||||
input: 'help',
|
||||
aliases: { de: ['hilfe'], en: [] },
|
||||
action: { kind: 'message', messageKey: 'help' },
|
||||
},
|
||||
{
|
||||
id: 'projects',
|
||||
input: 'projects',
|
||||
aliases: { de: ['projekte'], en: [] },
|
||||
action: { kind: 'navigate', routeId: 'projects' },
|
||||
},
|
||||
{
|
||||
id: 'servicesAi',
|
||||
input: 'services ai',
|
||||
aliases: { de: ['leistungen ai'], en: [] },
|
||||
action: { kind: 'navigate', routeId: 'servicesAi' },
|
||||
},
|
||||
{
|
||||
id: 'cv',
|
||||
input: 'cv',
|
||||
aliases: { de: ['lebenslauf'], en: ['resume'] },
|
||||
action: { kind: 'openCv' },
|
||||
},
|
||||
{
|
||||
id: 'contact',
|
||||
input: 'contact',
|
||||
aliases: { de: ['kontakt'], en: [] },
|
||||
action: { kind: 'navigate', routeId: 'contact' },
|
||||
},
|
||||
{
|
||||
id: 'brew',
|
||||
input: 'brew',
|
||||
aliases: { de: ['brauen'], en: [] },
|
||||
action: { kind: 'message', messageKey: 'brew' },
|
||||
},
|
||||
{
|
||||
id: 'ignite',
|
||||
input: 'ignite',
|
||||
aliases: { de: ['zuenden', 'zünden'], en: [] },
|
||||
action: { kind: 'message', messageKey: 'ignite' },
|
||||
},
|
||||
{
|
||||
id: 'rev',
|
||||
input: 'rev',
|
||||
aliases: { de: ['drehzahl'], en: [] },
|
||||
action: { kind: 'message', messageKey: 'rev' },
|
||||
},
|
||||
{
|
||||
id: 'clear',
|
||||
input: 'clear',
|
||||
aliases: { de: ['leeren'], en: [] },
|
||||
action: { kind: 'clear' },
|
||||
},
|
||||
{
|
||||
id: 'close',
|
||||
input: 'close',
|
||||
aliases: { de: ['schliessen', 'schließen'], en: [] },
|
||||
action: { kind: 'close' },
|
||||
},
|
||||
];
|
||||
|
||||
const COMMAND_LOOKUP = buildCommandLookup(COMMANDS);
|
||||
|
||||
function buildCommandLookup(
|
||||
commands: readonly CommandDefinition[],
|
||||
): ReadonlyMap<string, CommandDefinition> {
|
||||
const lookup = new Map<string, CommandDefinition>();
|
||||
|
||||
for (const command of commands) {
|
||||
lookup.set(normalizeCommandInput(command.input), command);
|
||||
|
||||
for (const locale of APP_LOCALES) {
|
||||
for (const alias of command.aliases[locale]) {
|
||||
lookup.set(normalizeCommandInput(alias), command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lookup;
|
||||
}
|
||||
|
||||
export function normalizeCommandInput(raw: string): string {
|
||||
return raw.trim().replace(/\s+/g, ' ').toLowerCase();
|
||||
}
|
||||
|
||||
export function parseCommand(raw: string): CommandMatch {
|
||||
const normalized = normalizeCommandInput(raw);
|
||||
|
||||
if (normalized.length === 0) {
|
||||
return { kind: 'empty' };
|
||||
}
|
||||
|
||||
const definition = COMMAND_LOOKUP.get(normalized);
|
||||
|
||||
if (!definition) {
|
||||
return { kind: 'unknown', input: raw };
|
||||
}
|
||||
|
||||
return { kind: 'command', definition };
|
||||
}
|
||||
|
||||
export function suggestCommands(raw: string, locale: AppLocale): readonly CommandDefinition[] {
|
||||
const normalized = normalizeCommandInput(raw);
|
||||
|
||||
return COMMANDS.filter((command) => {
|
||||
if (normalized.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (command.input.startsWith(normalized)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return command.aliases[locale].some((alias) =>
|
||||
normalizeCommandInput(alias).startsWith(normalized),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -18,9 +18,11 @@
|
||||
[value]="values()[field.id]"
|
||||
[required]="field.required"
|
||||
[attr.aria-required]="field.required ? 'true' : null"
|
||||
[attr.aria-describedby]="field.hint ? controlId(field) + '-hint' : null"
|
||||
[attr.aria-invalid]="showInvalid(field) ? 'true' : null"
|
||||
[attr.aria-describedby]="describedBy(field)"
|
||||
rows="6"
|
||||
(input)="onInput(field.id, $event)"
|
||||
(blur)="onBlur(field.id)"
|
||||
></textarea>
|
||||
}
|
||||
@case ('select') {
|
||||
@@ -29,8 +31,10 @@
|
||||
[value]="values()[field.id]"
|
||||
[required]="field.required"
|
||||
[attr.aria-required]="field.required ? 'true' : null"
|
||||
[attr.aria-describedby]="field.hint ? controlId(field) + '-hint' : null"
|
||||
[attr.aria-invalid]="showInvalid(field) ? 'true' : null"
|
||||
[attr.aria-describedby]="describedBy(field)"
|
||||
(input)="onInput(field.id, $event)"
|
||||
(blur)="onBlur(field.id)"
|
||||
>
|
||||
<option value=""></option>
|
||||
@for (option of field.options ?? []; track option.value) {
|
||||
@@ -45,20 +49,34 @@
|
||||
[value]="values()[field.id]"
|
||||
[required]="field.required"
|
||||
[attr.aria-required]="field.required ? 'true' : null"
|
||||
[attr.aria-describedby]="field.hint ? controlId(field) + '-hint' : null"
|
||||
[attr.aria-invalid]="showInvalid(field) ? 'true' : null"
|
||||
[attr.aria-describedby]="describedBy(field)"
|
||||
(input)="onInput(field.id, $event)"
|
||||
(blur)="onBlur(field.id)"
|
||||
/>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
<p class="incomplete" aria-live="polite">{{ incompleteMessage() }}</p>
|
||||
<p class="incomplete" [id]="incompleteId" aria-live="polite">{{ incompleteMessage() }}</p>
|
||||
|
||||
<p class="note">{{ copy().noBackendNote }}</p>
|
||||
|
||||
<p class="cluster actions">
|
||||
<a class="submit" [href]="mailtoHref()">{{ copy().submitLabel }}</a>
|
||||
@if (isComplete()) {
|
||||
<a class="submit" [href]="mailtoHref()">{{ copy().submitLabel }}</a>
|
||||
} @else {
|
||||
<button
|
||||
type="button"
|
||||
class="submit"
|
||||
aria-disabled="true"
|
||||
[attr.aria-describedby]="incompleteId"
|
||||
(click)="onDisabledSubmit($event)"
|
||||
>
|
||||
{{ copy().submitLabel }}
|
||||
</button>
|
||||
}
|
||||
<a [href]="'mailto:' + contactEmail">{{ copy().directEmailLabel }}</a>
|
||||
@if (showCalendar()) {
|
||||
<a [href]="calendarUrl">{{ copy().calendarLabel }}</a>
|
||||
|
||||
@@ -31,7 +31,8 @@ textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.actions a {
|
||||
.actions a,
|
||||
button.submit {
|
||||
color: var(--color-accent-cool);
|
||||
text-decoration: none;
|
||||
}
|
||||
@@ -40,6 +41,21 @@ textarea {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
button.submit {
|
||||
appearance: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
min-height: 2.75rem;
|
||||
}
|
||||
|
||||
button.submit[aria-disabled='true'] {
|
||||
color: var(--color-text-muted);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.actions a:hover {
|
||||
text-decoration: underline;
|
||||
|
||||
@@ -39,6 +39,12 @@ describe('ContactBriefing', () => {
|
||||
expect(root.querySelector('form[action]')).toBeNull();
|
||||
expect(root.textContent).toContain(copy.incompleteHint);
|
||||
expect(root.querySelector('[aria-live="polite"]')).toBeTruthy();
|
||||
expect(root.querySelector('a.submit')).toBeNull();
|
||||
const disabledSubmit = root.querySelector<HTMLButtonElement>('button.submit');
|
||||
expect(disabledSubmit?.getAttribute('aria-disabled')).toBe('true');
|
||||
expect(disabledSubmit?.getAttribute('aria-describedby')).toBe('contact-incomplete');
|
||||
expect(disabledSubmit?.textContent).toContain(copy.submitLabel);
|
||||
expect(root.querySelector('[aria-invalid="true"]')).toBeNull();
|
||||
expect(root.querySelector(`a[href="${SITE_CONFIG.calendarUrl}"]`)).toBeNull();
|
||||
expect(root.textContent).not.toContain(copy.calendarLabel);
|
||||
|
||||
@@ -85,4 +91,33 @@ describe('ContactBriefing', () => {
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
expect(xhrSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('marks required fields invalid only after interaction', async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ContactBriefing],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(ContactBriefing);
|
||||
const copy = SITE_CONTENT_DATA.de.contact;
|
||||
fixture.componentRef.setInput('copy', copy);
|
||||
await fixture.whenStable();
|
||||
|
||||
const root = fixture.nativeElement as HTMLElement;
|
||||
const name = root.querySelector<HTMLInputElement>('#contact-name');
|
||||
expect(name).toBeTruthy();
|
||||
expect(name?.getAttribute('aria-invalid')).toBeNull();
|
||||
|
||||
name!.dispatchEvent(new Event('blur', { bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(name?.getAttribute('aria-invalid')).toBe('true');
|
||||
expect(name?.getAttribute('aria-describedby')?.includes('contact-incomplete')).toBe(true);
|
||||
expect(root.querySelector('#contact-email')?.getAttribute('aria-invalid')).toBeNull();
|
||||
|
||||
const submit = root.querySelector<HTMLButtonElement>('button.submit');
|
||||
expect(submit?.getAttribute('aria-disabled')).toBe('true');
|
||||
submit?.click();
|
||||
fixture.detectChanges();
|
||||
expect(root.querySelector('a.submit')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,8 +25,10 @@ export class ContactBriefing {
|
||||
readonly copy = input.required<ContactPageCopy>();
|
||||
|
||||
protected readonly values = signal<Record<ContactFieldId, string>>({ ...EMPTY_VALUES });
|
||||
protected readonly touched = signal<Partial<Record<ContactFieldId, boolean>>>({});
|
||||
protected readonly contactEmail = SITE_CONFIG.contactEmail;
|
||||
protected readonly calendarUrl = SITE_CONFIG.calendarUrl;
|
||||
protected readonly incompleteId = 'contact-incomplete';
|
||||
|
||||
protected readonly missingLabels = computed(() => {
|
||||
const copy = this.copy();
|
||||
@@ -36,6 +38,8 @@ export class ContactBriefing {
|
||||
.map((field) => field.label);
|
||||
});
|
||||
|
||||
protected readonly isComplete = computed(() => this.missingLabels().length === 0);
|
||||
|
||||
protected readonly incompleteMessage = computed(() => {
|
||||
const missing = this.missingLabels();
|
||||
if (missing.length === 0) {
|
||||
@@ -60,12 +64,44 @@ export class ContactBriefing {
|
||||
protected onInput(fieldId: ContactFieldId, event: Event): void {
|
||||
const target = event.target as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
||||
this.values.update((current) => ({ ...current, [fieldId]: target.value }));
|
||||
this.markTouched(fieldId);
|
||||
}
|
||||
|
||||
protected onBlur(fieldId: ContactFieldId): void {
|
||||
this.markTouched(fieldId);
|
||||
}
|
||||
|
||||
protected onDisabledSubmit(event: Event): void {
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
protected controlId(field: ContactFieldCopy): string {
|
||||
return `contact-${field.id}`;
|
||||
}
|
||||
|
||||
protected showInvalid(field: ContactFieldCopy): boolean {
|
||||
return (
|
||||
field.required &&
|
||||
this.touched()[field.id] === true &&
|
||||
this.values()[field.id].trim().length === 0
|
||||
);
|
||||
}
|
||||
|
||||
protected describedBy(field: ContactFieldCopy): string | null {
|
||||
const ids: string[] = [];
|
||||
if (field.hint) {
|
||||
ids.push(`${this.controlId(field)}-hint`);
|
||||
}
|
||||
if (this.showInvalid(field)) {
|
||||
ids.push(this.incompleteId);
|
||||
}
|
||||
return ids.length > 0 ? ids.join(' ') : null;
|
||||
}
|
||||
|
||||
private markTouched(fieldId: ContactFieldId): void {
|
||||
this.touched.update((current) => ({ ...current, [fieldId]: true }));
|
||||
}
|
||||
|
||||
private assembleBody(copy: ContactPageCopy, values: Record<ContactFieldId, string>): string {
|
||||
const lines = copy.fields.flatMap((field) => {
|
||||
const raw = values[field.id];
|
||||
|
||||
25
src/app/shared/motion/_reveal.scss
Normal file
25
src/app/shared/motion/_reveal.scss
Normal file
@@ -0,0 +1,25 @@
|
||||
@mixin reveal-target {
|
||||
transition:
|
||||
opacity var(--duration-base) var(--ease-standard),
|
||||
transform var(--duration-base) var(--ease-standard);
|
||||
|
||||
&.reveal-pending {
|
||||
opacity: 0;
|
||||
transform: translateY(0.5rem);
|
||||
}
|
||||
|
||||
&.is-revealed {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
&,
|
||||
&.reveal-pending,
|
||||
&.is-revealed {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
20
src/app/shared/motion/metric-bar/metric-bar.html
Normal file
20
src/app/shared/motion/metric-bar/metric-bar.html
Normal file
@@ -0,0 +1,20 @@
|
||||
<div class="metric-bar">
|
||||
<div class="metric-bar-header">
|
||||
<span [id]="labelId">{{ label() }}</span>
|
||||
<span>{{ displayValue() }}</span>
|
||||
</div>
|
||||
@if (description(); as descriptionText) {
|
||||
<p class="metric-bar-description">{{ descriptionText }}</p>
|
||||
}
|
||||
<div
|
||||
class="metric-bar-track"
|
||||
role="progressbar"
|
||||
[attr.aria-valuenow]="clampedValue()"
|
||||
aria-valuemin="0"
|
||||
[attr.aria-valuemax]="max()"
|
||||
[attr.aria-valuetext]="displayValue()"
|
||||
[attr.aria-labelledby]="labelId"
|
||||
>
|
||||
<div class="metric-bar-fill" [style.width.%]="percent()"></div>
|
||||
</div>
|
||||
</div>
|
||||
44
src/app/shared/motion/metric-bar/metric-bar.scss
Normal file
44
src/app/shared/motion/metric-bar/metric-bar.scss
Normal file
@@ -0,0 +1,44 @@
|
||||
@use 'app/shared/motion/reveal' as reveal;
|
||||
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.metric-bar {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
@include reveal.reveal-target;
|
||||
}
|
||||
|
||||
.metric-bar-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.metric-bar-description {
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.metric-bar-track {
|
||||
height: 0.5rem;
|
||||
overflow: hidden;
|
||||
border-radius: var(--radius-pill);
|
||||
background: var(--color-surface-muted);
|
||||
}
|
||||
|
||||
.metric-bar-fill {
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: var(--color-accent);
|
||||
transition: width var(--duration-base) var(--ease-standard);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.metric-bar-fill {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
95
src/app/shared/motion/metric-bar/metric-bar.spec.ts
Normal file
95
src/app/shared/motion/metric-bar/metric-bar.spec.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { MetricBar } from './metric-bar';
|
||||
|
||||
describe('MetricBar', () => {
|
||||
async function createFixture(inputs: {
|
||||
label: string;
|
||||
value: number;
|
||||
max?: number;
|
||||
valueText?: string;
|
||||
description?: string;
|
||||
}): Promise<ComponentFixture<MetricBar>> {
|
||||
TestBed.resetTestingModule();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [MetricBar],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(MetricBar);
|
||||
fixture.componentRef.setInput('label', inputs.label);
|
||||
fixture.componentRef.setInput('value', inputs.value);
|
||||
|
||||
if (inputs.max !== undefined) {
|
||||
fixture.componentRef.setInput('max', inputs.max);
|
||||
}
|
||||
|
||||
if (inputs.valueText !== undefined) {
|
||||
fixture.componentRef.setInput('valueText', inputs.valueText);
|
||||
}
|
||||
|
||||
if (inputs.description !== undefined) {
|
||||
fixture.componentRef.setInput('description', inputs.description);
|
||||
}
|
||||
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
it('renders the label and value as visible text', async () => {
|
||||
const fixture = await createFixture({
|
||||
label: 'Coverage',
|
||||
value: 40,
|
||||
valueText: '40 of 80',
|
||||
});
|
||||
const text = fixture.nativeElement.textContent ?? '';
|
||||
|
||||
expect(text).toContain('Coverage');
|
||||
expect(text).toContain('40 of 80');
|
||||
});
|
||||
|
||||
it('exposes progressbar semantics and an accessible name through aria-labelledby', async () => {
|
||||
const fixture = await createFixture({
|
||||
label: 'Latency',
|
||||
value: 25,
|
||||
max: 50,
|
||||
valueText: '25 ms',
|
||||
});
|
||||
const bar = fixture.nativeElement.querySelector('[role="progressbar"]') as HTMLElement;
|
||||
const labelId = bar.getAttribute('aria-labelledby');
|
||||
const label = fixture.nativeElement.querySelector(`#${labelId}`);
|
||||
|
||||
expect(bar.getAttribute('aria-valuenow')).toBe('25');
|
||||
expect(bar.getAttribute('aria-valuemin')).toBe('0');
|
||||
expect(bar.getAttribute('aria-valuemax')).toBe('50');
|
||||
expect(bar.getAttribute('aria-valuetext')).toBe('25 ms');
|
||||
expect(label?.textContent?.trim()).toBe('Latency');
|
||||
});
|
||||
|
||||
it('clamps values below 0 and above max', async () => {
|
||||
const low = await createFixture({ label: 'Low', value: -12, max: 10 });
|
||||
const lowBar = low.nativeElement.querySelector('[role="progressbar"]') as HTMLElement;
|
||||
const lowFill = low.nativeElement.querySelector('.metric-bar-fill') as HTMLElement;
|
||||
|
||||
expect(lowBar.getAttribute('aria-valuenow')).toBe('0');
|
||||
expect(lowFill.style.width).toBe('0%');
|
||||
|
||||
const high = await createFixture({ label: 'High', value: 140, max: 50 });
|
||||
const highBar = high.nativeElement.querySelector('[role="progressbar"]') as HTMLElement;
|
||||
const highFill = high.nativeElement.querySelector('.metric-bar-fill') as HTMLElement;
|
||||
|
||||
expect(highBar.getAttribute('aria-valuenow')).toBe('50');
|
||||
expect(highFill.style.width).toBe('100%');
|
||||
});
|
||||
|
||||
it('does not produce NaN when max is 0', async () => {
|
||||
const fixture = await createFixture({ label: 'Empty', value: 8, max: 0 });
|
||||
const bar = fixture.nativeElement.querySelector('[role="progressbar"]') as HTMLElement;
|
||||
const fill = fixture.nativeElement.querySelector('.metric-bar-fill') as HTMLElement;
|
||||
|
||||
expect(bar.getAttribute('aria-valuenow')).toBe('0');
|
||||
expect(fill.style.width).toBe('0%');
|
||||
expect(fill.style.width).not.toContain('NaN');
|
||||
expect(fixture.nativeElement.textContent).toContain('Empty');
|
||||
expect(fixture.nativeElement.textContent).toContain('0');
|
||||
});
|
||||
});
|
||||
47
src/app/shared/motion/metric-bar/metric-bar.ts
Normal file
47
src/app/shared/motion/metric-bar/metric-bar.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
|
||||
|
||||
let metricBarInstanceId = 0;
|
||||
|
||||
@Component({
|
||||
selector: 'app-metric-bar',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './metric-bar.html',
|
||||
styleUrl: './metric-bar.scss',
|
||||
})
|
||||
export class MetricBar {
|
||||
readonly label = input.required<string>();
|
||||
readonly value = input.required<number>();
|
||||
readonly max = input(100);
|
||||
readonly valueText = input<string | undefined>(undefined);
|
||||
readonly description = input<string | undefined>(undefined);
|
||||
|
||||
private readonly instanceId = metricBarInstanceId++;
|
||||
protected readonly labelId = `metric-bar-label-${this.instanceId}`;
|
||||
|
||||
protected readonly clampedValue = computed(() => {
|
||||
const max = this.max();
|
||||
const value = this.value();
|
||||
|
||||
if (!Number.isFinite(max) || max <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Math.min(max, Math.max(0, value));
|
||||
});
|
||||
|
||||
protected readonly percent = computed(() => {
|
||||
const max = this.max();
|
||||
|
||||
if (!Number.isFinite(max) || max <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (this.clampedValue() / max) * 100;
|
||||
});
|
||||
|
||||
protected readonly displayValue = computed(() => this.valueText() ?? String(this.clampedValue()));
|
||||
}
|
||||
181
src/app/shared/motion/reveal.directive.spec.ts
Normal file
181
src/app/shared/motion/reveal.directive.spec.ts
Normal file
@@ -0,0 +1,181 @@
|
||||
import { ApplicationRef, Component, PLATFORM_ID } from '@angular/core';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { RevealDirective } from './reveal.directive';
|
||||
|
||||
@Component({
|
||||
imports: [RevealDirective],
|
||||
template: `<div appReveal [appRevealThreshold]="0.2">Reveal host</div>`,
|
||||
})
|
||||
class RevealHost {}
|
||||
|
||||
class MockIntersectionObserver {
|
||||
static instances: MockIntersectionObserver[] = [];
|
||||
|
||||
readonly observe = vi.fn();
|
||||
readonly unobserve = vi.fn();
|
||||
readonly disconnect = vi.fn();
|
||||
|
||||
constructor(
|
||||
private readonly callback: IntersectionObserverCallback,
|
||||
readonly options?: IntersectionObserverInit,
|
||||
) {
|
||||
MockIntersectionObserver.instances.push(this);
|
||||
}
|
||||
|
||||
trigger(isIntersecting: boolean): void {
|
||||
this.callback(
|
||||
[{ isIntersecting } as IntersectionObserverEntry],
|
||||
this as unknown as IntersectionObserver,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function mockMatchMedia(matchesQuery: (query: string) => boolean): void {
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: (query: string): MediaQueryList =>
|
||||
({
|
||||
matches: matchesQuery(query),
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
}) as MediaQueryList,
|
||||
});
|
||||
}
|
||||
|
||||
describe('RevealDirective', () => {
|
||||
afterEach(() => {
|
||||
MockIntersectionObserver.instances = [];
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
Reflect.deleteProperty(window, 'matchMedia');
|
||||
});
|
||||
|
||||
async function createHost(
|
||||
providers: { provide: unknown; useValue: unknown }[] = [],
|
||||
): Promise<ComponentFixture<RevealHost>> {
|
||||
TestBed.resetTestingModule();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [RevealHost],
|
||||
providers,
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(RevealHost);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
TestBed.inject(ApplicationRef).tick();
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
function hostElement(fixture: ComponentFixture<RevealHost>): HTMLElement {
|
||||
return fixture.nativeElement.querySelector('[appReveal]');
|
||||
}
|
||||
|
||||
it('reveals immediately on the server without constructing an observer', async () => {
|
||||
const Observer = vi.fn();
|
||||
vi.stubGlobal('IntersectionObserver', Observer);
|
||||
|
||||
const fixture = await createHost([{ provide: PLATFORM_ID, useValue: 'server' }]);
|
||||
const element = hostElement(fixture);
|
||||
|
||||
expect(element.classList.contains('is-revealed')).toBe(true);
|
||||
expect(element.classList.contains('reveal-pending')).toBe(false);
|
||||
expect(Observer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reveals immediately when IntersectionObserver is missing', async () => {
|
||||
const original = window.IntersectionObserver;
|
||||
Reflect.deleteProperty(window, 'IntersectionObserver');
|
||||
|
||||
try {
|
||||
const fixture = await createHost();
|
||||
const element = hostElement(fixture);
|
||||
|
||||
expect(element.classList.contains('is-revealed')).toBe(true);
|
||||
expect(element.classList.contains('reveal-pending')).toBe(false);
|
||||
} finally {
|
||||
window.IntersectionObserver = original;
|
||||
}
|
||||
});
|
||||
|
||||
it('reveals immediately when reduced motion is requested', async () => {
|
||||
mockMatchMedia((query) => query.includes('prefers-reduced-motion'));
|
||||
const Observer = vi.fn();
|
||||
vi.stubGlobal('IntersectionObserver', Observer);
|
||||
|
||||
const fixture = await createHost();
|
||||
const element = hostElement(fixture);
|
||||
|
||||
expect(element.classList.contains('is-revealed')).toBe(true);
|
||||
expect(element.classList.contains('reveal-pending')).toBe(false);
|
||||
expect(Observer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('marks the element pending, then revealed, and disconnects on intersection', async () => {
|
||||
vi.stubGlobal('IntersectionObserver', MockIntersectionObserver);
|
||||
|
||||
const fixture = await createHost();
|
||||
const element = hostElement(fixture);
|
||||
const observer = MockIntersectionObserver.instances[0];
|
||||
|
||||
expect(observer).toBeTruthy();
|
||||
expect(observer.observe).toHaveBeenCalled();
|
||||
expect(element.classList.contains('reveal-pending')).toBe(false);
|
||||
expect(element.classList.contains('is-revealed')).toBe(false);
|
||||
|
||||
observer.trigger(false);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(element.classList.contains('reveal-pending')).toBe(true);
|
||||
expect(element.classList.contains('is-revealed')).toBe(false);
|
||||
|
||||
observer.trigger(true);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(element.classList.contains('reveal-pending')).toBe(false);
|
||||
expect(element.classList.contains('is-revealed')).toBe(true);
|
||||
expect(observer.disconnect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reveals on a first intersecting callback without ever adding reveal-pending', async () => {
|
||||
vi.stubGlobal('IntersectionObserver', MockIntersectionObserver);
|
||||
|
||||
const fixture = await createHost();
|
||||
const element = hostElement(fixture);
|
||||
const observer = MockIntersectionObserver.instances[0];
|
||||
const addedTokens: string[] = [];
|
||||
const add = element.classList.add.bind(element.classList);
|
||||
vi.spyOn(element.classList, 'add').mockImplementation((...tokens: string[]) => {
|
||||
addedTokens.push(...tokens);
|
||||
add(...tokens);
|
||||
});
|
||||
|
||||
expect(observer).toBeTruthy();
|
||||
expect(element.classList.contains('reveal-pending')).toBe(false);
|
||||
|
||||
observer.trigger(true);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(addedTokens).not.toContain('reveal-pending');
|
||||
expect(element.classList.contains('reveal-pending')).toBe(false);
|
||||
expect(element.classList.contains('is-revealed')).toBe(true);
|
||||
expect(observer.disconnect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disconnects when destroyed before intersection', async () => {
|
||||
vi.stubGlobal('IntersectionObserver', MockIntersectionObserver);
|
||||
|
||||
const fixture = await createHost();
|
||||
const observer = MockIntersectionObserver.instances[0];
|
||||
expect(observer).toBeTruthy();
|
||||
|
||||
fixture.destroy();
|
||||
expect(observer.disconnect).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
77
src/app/shared/motion/reveal.directive.ts
Normal file
77
src/app/shared/motion/reveal.directive.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import {
|
||||
afterNextRender,
|
||||
DestroyRef,
|
||||
Directive,
|
||||
ElementRef,
|
||||
inject,
|
||||
Injector,
|
||||
input,
|
||||
} from '@angular/core';
|
||||
import { isBrowserPlatform, prefersReducedMotion } from '../../core/platform/browser';
|
||||
|
||||
@Directive({
|
||||
selector: '[appReveal]',
|
||||
})
|
||||
export class RevealDirective {
|
||||
readonly appRevealThreshold = input(0.12);
|
||||
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly isBrowser = isBrowserPlatform();
|
||||
private readonly reducedMotion = prefersReducedMotion();
|
||||
private observer: IntersectionObserver | null = null;
|
||||
|
||||
constructor() {
|
||||
if (!this.isBrowser || this.reducedMotion || !this.canObserve()) {
|
||||
this.revealNow();
|
||||
return;
|
||||
}
|
||||
|
||||
afterNextRender(() => this.observe(), { injector: this.injector });
|
||||
this.destroyRef.onDestroy(() => this.disconnect());
|
||||
}
|
||||
|
||||
private canObserve(): boolean {
|
||||
const view = this.document.defaultView;
|
||||
return !!view && typeof view.IntersectionObserver === 'function';
|
||||
}
|
||||
|
||||
private observe(): void {
|
||||
const view = this.document.defaultView;
|
||||
|
||||
if (!view || typeof view.IntersectionObserver !== 'function') {
|
||||
this.revealNow();
|
||||
return;
|
||||
}
|
||||
|
||||
this.observer = new view.IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) {
|
||||
this.host.nativeElement.classList.remove('reveal-pending');
|
||||
this.host.nativeElement.classList.add('is-revealed');
|
||||
this.disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
this.host.nativeElement.classList.add('reveal-pending');
|
||||
},
|
||||
{
|
||||
rootMargin: '0px 0px -8% 0px',
|
||||
threshold: this.appRevealThreshold(),
|
||||
},
|
||||
);
|
||||
this.observer.observe(this.host.nativeElement);
|
||||
}
|
||||
|
||||
private revealNow(): void {
|
||||
this.host.nativeElement.classList.add('is-revealed');
|
||||
}
|
||||
|
||||
private disconnect(): void {
|
||||
this.observer?.disconnect();
|
||||
this.observer = null;
|
||||
}
|
||||
}
|
||||
36
src/app/shared/motion/reveal.styles.spec.ts
Normal file
36
src/app/shared/motion/reveal.styles.spec.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const REVEAL_SCSS = readFileSync(join(process.cwd(), 'src/app/shared/motion/_reveal.scss'), 'utf8');
|
||||
|
||||
function mixinBody(source: string): string {
|
||||
const start = source.indexOf('@mixin reveal-target');
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
return source.slice(start);
|
||||
}
|
||||
|
||||
describe('reveal-target mixin', () => {
|
||||
it('keeps transition on the base selector so the revealed state can animate', () => {
|
||||
const mixin = mixinBody(REVEAL_SCSS);
|
||||
const transitionIndex = mixin.search(/transition\s*:/);
|
||||
const pendingIndex = mixin.indexOf('&.reveal-pending');
|
||||
const revealedIndex = mixin.indexOf('&.is-revealed');
|
||||
|
||||
expect(transitionIndex).toBeGreaterThan(-1);
|
||||
expect(pendingIndex).toBeGreaterThan(-1);
|
||||
expect(revealedIndex).toBeGreaterThan(pendingIndex);
|
||||
expect(transitionIndex).toBeLessThan(pendingIndex);
|
||||
|
||||
const pendingBlock = mixin.match(/&\.reveal-pending\s*\{([^}]*)\}/)?.[1] ?? '';
|
||||
expect(pendingBlock).toMatch(/opacity\s*:/);
|
||||
expect(pendingBlock).not.toMatch(/transition\s*:/);
|
||||
|
||||
const revealedBlock = mixin.match(/&\.is-revealed\s*\{([^}]*)\}/)?.[1] ?? '';
|
||||
expect(revealedBlock).toMatch(/opacity\s*:\s*1/);
|
||||
expect(revealedBlock).not.toMatch(/transition\s*:/);
|
||||
|
||||
expect(mixin).toMatch(/prefers-reduced-motion:\s*reduce/);
|
||||
expect(mixin).toMatch(/&\s*,\s*&\.reveal-pending/);
|
||||
expect(mixin).toMatch(/&\.is-revealed\s*\{[\s\S]*transition:\s*none/);
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,8 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.page section p {
|
||||
.page section p,
|
||||
.page .evidence-note {
|
||||
margin: 0;
|
||||
max-width: 40rem;
|
||||
color: var(--color-text-muted);
|
||||
|
||||
93
src/app/shared/systems-map/systems-map.html
Normal file
93
src/app/shared/systems-map/systems-map.html
Normal file
@@ -0,0 +1,93 @@
|
||||
<section class="systems-map" [attr.aria-labelledby]="headingId">
|
||||
@if (headingLevel() === 3) {
|
||||
<h3 [id]="headingId" class="systems-map-heading">{{ headingText() }}</h3>
|
||||
} @else {
|
||||
<h2 [id]="headingId" class="systems-map-heading">{{ headingText() }}</h2>
|
||||
}
|
||||
<p class="systems-map-intro">{{ introText() }}</p>
|
||||
|
||||
<div class="systems-map-figure">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 1000 560"
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
role="group"
|
||||
[attr.aria-labelledby]="svgTitleId"
|
||||
[attr.aria-describedby]="svgDescId"
|
||||
>
|
||||
<title [id]="svgTitleId">{{ headingText() }}</title>
|
||||
<desc [id]="svgDescId">{{ copy().diagramDescription }}</desc>
|
||||
@for (edge of edges(); track edge.from + '-' + edge.to) {
|
||||
<line
|
||||
[attr.x1]="edge.x1"
|
||||
[attr.y1]="edge.y1"
|
||||
[attr.x2]="edge.x2"
|
||||
[attr.y2]="edge.y2"
|
||||
class="systems-map-edge"
|
||||
[class.is-connected]="isConnectedEdge(edge)"
|
||||
[class.is-dimmed]="isDimmedEdge(edge)"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
}
|
||||
@for (node of nodes(); track node.id) {
|
||||
<a
|
||||
[attr.href]="node.href"
|
||||
[attr.aria-label]="node.accessibleName"
|
||||
class="systems-map-node"
|
||||
[attr.data-kind]="node.kind"
|
||||
[class.is-connected]="isConnectedNode(node.id)"
|
||||
[class.is-dimmed]="isDimmedNode(node.id)"
|
||||
(click)="onNodeActivate($event, node)"
|
||||
(focusin)="onNodeEnter(node.id)"
|
||||
(focusout)="onNodeLeave(node.id)"
|
||||
(mouseenter)="onNodeEnter(node.id)"
|
||||
(mouseleave)="onNodeLeave(node.id)"
|
||||
>
|
||||
@if (node.kind === 'ai' || node.kind === 'cluster') {
|
||||
<circle [attr.cx]="node.x" [attr.cy]="node.y" r="28" aria-hidden="true" />
|
||||
} @else {
|
||||
<rect
|
||||
[attr.x]="node.x - node.shapeWidth / 2"
|
||||
[attr.y]="node.y - node.shapeHeight / 2"
|
||||
[attr.width]="node.shapeWidth"
|
||||
[attr.height]="node.shapeHeight"
|
||||
rx="8"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
}
|
||||
<text [attr.x]="node.x" [attr.y]="node.y" aria-hidden="true">
|
||||
@for (line of node.labelLines; track $index) {
|
||||
<tspan [attr.x]="node.x" [attr.dy]="$index === 0 ? node.textStartDy : 14">
|
||||
{{ line }}
|
||||
</tspan>
|
||||
}
|
||||
</text>
|
||||
</a>
|
||||
}
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div class="systems-map-list">
|
||||
<p class="systems-map-kicker" [id]="listHeadingId">{{ copy().listHeading }}</p>
|
||||
<ul class="systems-map-cards" [attr.aria-labelledby]="listHeadingId">
|
||||
@for (node of nodes(); track node.id) {
|
||||
<li>
|
||||
<a [routerLink]="node.link" [attr.aria-label]="node.accessibleName">
|
||||
<span class="systems-map-card-label">{{ node.label }}</span>
|
||||
<span class="systems-map-card-summary">{{ node.summary }}</span>
|
||||
<span class="systems-map-card-relation">{{ node.relationship }}</span>
|
||||
</a>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<p class="systems-map-kicker" [id]="legendHeadingId">{{ copy().legendHeading }}</p>
|
||||
<ul class="systems-map-legend" [attr.aria-labelledby]="legendHeadingId">
|
||||
@for (item of legendItems(); track item.kind) {
|
||||
<li [attr.data-kind]="item.kind">{{ item.label }}</li>
|
||||
}
|
||||
</ul>
|
||||
|
||||
<p class="systems-map-readout" aria-hidden="true">{{ activeReadout() }}</p>
|
||||
</section>
|
||||
171
src/app/shared/systems-map/systems-map.model.ts
Normal file
171
src/app/shared/systems-map/systems-map.model.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import { type AppLocale } from '../../core/i18n/locale';
|
||||
import { type RouteId } from '../../core/routing/route-ids';
|
||||
|
||||
export type SystemsMapNodeKind = 'ai' | 'cluster' | 'hardware' | 'software' | 'project';
|
||||
|
||||
export type SystemsMapNodeId =
|
||||
| 'ai'
|
||||
| 'clusters'
|
||||
| 'hardware'
|
||||
| 'software'
|
||||
| 'stack'
|
||||
| 'caseMigration'
|
||||
| 'casePlatform'
|
||||
| 'caseAutomation';
|
||||
|
||||
export const SYSTEMS_MAP_NODE_KINDS: readonly SystemsMapNodeKind[] = [
|
||||
'ai',
|
||||
'cluster',
|
||||
'hardware',
|
||||
'software',
|
||||
'project',
|
||||
];
|
||||
|
||||
export interface SystemsMapNode {
|
||||
readonly id: SystemsMapNodeId;
|
||||
readonly kind: SystemsMapNodeKind;
|
||||
readonly routeId: RouteId;
|
||||
readonly label: Record<AppLocale, string>;
|
||||
readonly labelLines: Record<AppLocale, readonly string[]>;
|
||||
readonly summary: Record<AppLocale, string>;
|
||||
readonly x: number;
|
||||
readonly y: number;
|
||||
}
|
||||
|
||||
export interface SystemsMapEdge {
|
||||
readonly from: SystemsMapNodeId;
|
||||
readonly to: SystemsMapNodeId;
|
||||
}
|
||||
|
||||
export const SYSTEMS_MAP_NODES: readonly SystemsMapNode[] = [
|
||||
{
|
||||
id: 'hardware',
|
||||
kind: 'hardware',
|
||||
routeId: 'servicesHardwareNetwork',
|
||||
label: { de: 'Hardware', en: 'Hardware' },
|
||||
labelLines: { de: ['Hardware'], en: ['Hardware'] },
|
||||
summary: {
|
||||
de: 'Geräte, Netz und physische Schicht',
|
||||
en: 'Devices, network and the physical layer',
|
||||
},
|
||||
x: 140,
|
||||
y: 300,
|
||||
},
|
||||
{
|
||||
id: 'clusters',
|
||||
kind: 'cluster',
|
||||
routeId: 'servicesClusters',
|
||||
label: { de: 'Cluster', en: 'Clusters' },
|
||||
labelLines: { de: ['Cluster'], en: ['Clusters'] },
|
||||
summary: {
|
||||
de: 'Orchestrierung und Betrieb von Cluster-Umgebungen',
|
||||
en: 'Orchestration and cluster operations',
|
||||
},
|
||||
x: 340,
|
||||
y: 140,
|
||||
},
|
||||
{
|
||||
id: 'software',
|
||||
kind: 'software',
|
||||
routeId: 'servicesSoftware',
|
||||
label: { de: 'Software', en: 'Software' },
|
||||
labelLines: { de: ['Software'], en: ['Software'] },
|
||||
summary: {
|
||||
de: 'Anwendungen und Schnittstellen',
|
||||
en: 'Applications and interfaces',
|
||||
},
|
||||
x: 520,
|
||||
y: 300,
|
||||
},
|
||||
{
|
||||
id: 'ai',
|
||||
kind: 'ai',
|
||||
routeId: 'servicesAi',
|
||||
label: { de: 'KI', en: 'AI' },
|
||||
labelLines: { de: ['KI'], en: ['AI'] },
|
||||
summary: {
|
||||
de: 'Angebot: lokale Modelle und Integrationsarbeit',
|
||||
en: 'Offered as local models and integration work',
|
||||
},
|
||||
x: 720,
|
||||
y: 140,
|
||||
},
|
||||
{
|
||||
id: 'stack',
|
||||
kind: 'software',
|
||||
routeId: 'stack',
|
||||
label: { de: 'Stack', en: 'Stack' },
|
||||
labelLines: { de: ['Stack'], en: ['Stack'] },
|
||||
summary: {
|
||||
de: 'Werkzeuge und Laufzeitumgebung',
|
||||
en: 'Tools and runtime environment',
|
||||
},
|
||||
x: 340,
|
||||
y: 460,
|
||||
},
|
||||
{
|
||||
id: 'caseMigration',
|
||||
kind: 'project',
|
||||
routeId: 'projects',
|
||||
label: { de: 'Datenmigration', en: 'Data migration' },
|
||||
labelLines: { de: ['Datenmigration'], en: ['Data migration'] },
|
||||
summary: {
|
||||
de: 'Datenbestände strukturiert überführen',
|
||||
en: 'Moving data stores in a structured way',
|
||||
},
|
||||
x: 860,
|
||||
y: 460,
|
||||
},
|
||||
{
|
||||
id: 'casePlatform',
|
||||
kind: 'project',
|
||||
routeId: 'projects',
|
||||
label: { de: 'Plattform und Betrieb', en: 'Platform and operations' },
|
||||
labelLines: { de: ['Plattform und', 'Betrieb'], en: ['Platform and', 'operations'] },
|
||||
summary: {
|
||||
de: 'Plattformen betreiben und weiterentwickeln',
|
||||
en: 'Operating and evolving platforms',
|
||||
},
|
||||
x: 860,
|
||||
y: 300,
|
||||
},
|
||||
{
|
||||
id: 'caseAutomation',
|
||||
kind: 'project',
|
||||
routeId: 'projects',
|
||||
label: { de: 'Automatisierung und AI', en: 'Automation and AI' },
|
||||
labelLines: { de: ['Automatisierung', 'und AI'], en: ['Automation', 'and AI'] },
|
||||
summary: {
|
||||
de: 'Angebot: Abläufe automatisieren und Modelle anbinden',
|
||||
en: 'Offered as workflow automation and model connections',
|
||||
},
|
||||
x: 900,
|
||||
y: 140,
|
||||
},
|
||||
];
|
||||
|
||||
export const SYSTEMS_MAP_EDGES: readonly SystemsMapEdge[] = [
|
||||
{ from: 'hardware', to: 'clusters' },
|
||||
{ from: 'clusters', to: 'software' },
|
||||
{ from: 'software', to: 'ai' },
|
||||
{ from: 'ai', to: 'clusters' },
|
||||
{ from: 'hardware', to: 'software' },
|
||||
{ from: 'stack', to: 'software' },
|
||||
{ from: 'ai', to: 'caseAutomation' },
|
||||
{ from: 'software', to: 'casePlatform' },
|
||||
{ from: 'software', to: 'caseMigration' },
|
||||
];
|
||||
|
||||
export function connectedNodeIds(id: SystemsMapNodeId): readonly SystemsMapNodeId[] {
|
||||
const connected: SystemsMapNodeId[] = [];
|
||||
|
||||
for (const edge of SYSTEMS_MAP_EDGES) {
|
||||
if (edge.from === id) {
|
||||
connected.push(edge.to);
|
||||
} else if (edge.to === id) {
|
||||
connected.push(edge.from);
|
||||
}
|
||||
}
|
||||
|
||||
return connected;
|
||||
}
|
||||
184
src/app/shared/systems-map/systems-map.scss
Normal file
184
src/app/shared/systems-map/systems-map.scss
Normal file
@@ -0,0 +1,184 @@
|
||||
@use 'breakpoints' as bp;
|
||||
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.systems-map {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.systems-map-heading,
|
||||
.systems-map-intro,
|
||||
.systems-map-kicker,
|
||||
.systems-map-readout {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.systems-map-heading {
|
||||
font-size: var(--text-xl);
|
||||
line-height: var(--leading-tight);
|
||||
}
|
||||
|
||||
.systems-map-intro,
|
||||
.systems-map-card-summary,
|
||||
.systems-map-card-relation,
|
||||
.systems-map-readout {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.systems-map-kicker {
|
||||
font-size: var(--text-xs);
|
||||
letter-spacing: var(--tracking-wide);
|
||||
text-transform: uppercase;
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.systems-map-figure {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.systems-map-figure svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
border: 1px solid var(--surface-glass-border);
|
||||
border-radius: var(--radius-md);
|
||||
background-color: var(--color-surface-raised);
|
||||
background-image:
|
||||
linear-gradient(var(--color-surface-muted) 1px, transparent 1px),
|
||||
linear-gradient(90deg, var(--color-surface-muted) 1px, transparent 1px);
|
||||
background-size: 1.5rem 1.5rem;
|
||||
}
|
||||
|
||||
.systems-map-edge {
|
||||
fill: none;
|
||||
stroke: var(--color-accent-cool);
|
||||
stroke-width: 1.25;
|
||||
opacity: 0.7;
|
||||
transition: opacity var(--duration-base) var(--ease-standard);
|
||||
}
|
||||
|
||||
.systems-map-node {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.systems-map-node circle,
|
||||
.systems-map-node rect {
|
||||
fill: var(--color-surface-overlay);
|
||||
stroke: var(--color-accent);
|
||||
stroke-width: 1.25;
|
||||
transition:
|
||||
opacity var(--duration-base) var(--ease-standard),
|
||||
stroke var(--duration-fast) var(--ease-standard);
|
||||
}
|
||||
|
||||
.systems-map-node[data-kind='project'] rect,
|
||||
.systems-map-legend [data-kind='project'] {
|
||||
stroke: var(--color-accent-soft);
|
||||
}
|
||||
|
||||
.systems-map-node[data-kind='ai'] circle,
|
||||
.systems-map-legend [data-kind='ai'] {
|
||||
stroke: var(--color-accent-strong);
|
||||
}
|
||||
|
||||
.systems-map-node text {
|
||||
fill: currentColor;
|
||||
font-size: 0.75rem;
|
||||
text-anchor: middle;
|
||||
}
|
||||
|
||||
.systems-map-node.is-connected circle,
|
||||
.systems-map-node.is-connected rect,
|
||||
.systems-map-edge.is-connected {
|
||||
stroke: var(--color-accent-strong);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.systems-map-node.is-dimmed,
|
||||
.systems-map-edge.is-dimmed {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.systems-map-cards,
|
||||
.systems-map-legend {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.systems-map-cards {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.systems-map-cards a {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-4);
|
||||
border: 1px solid var(--surface-glass-border);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-surface-raised);
|
||||
color: var(--color-text);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.systems-map-node:focus-visible,
|
||||
.systems-map-cards a:focus-visible {
|
||||
outline: var(--focus-ring-width) solid var(--focus-ring-color);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
}
|
||||
|
||||
.systems-map-node:focus-visible circle,
|
||||
.systems-map-node:focus-visible rect {
|
||||
stroke: var(--focus-ring-color);
|
||||
stroke-width: 3;
|
||||
}
|
||||
|
||||
.systems-map-card-label {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.systems-map-legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.systems-map-legend li {
|
||||
padding-inline-start: var(--space-3);
|
||||
border-inline-start: 2px solid var(--color-accent);
|
||||
}
|
||||
|
||||
.systems-map-readout {
|
||||
min-height: var(--text-md);
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.systems-map-node:hover circle,
|
||||
.systems-map-node:hover rect {
|
||||
stroke: var(--color-accent-strong);
|
||||
}
|
||||
|
||||
.systems-map-cards a:hover {
|
||||
border-color: var(--surface-glass-border-strong);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.systems-map-edge,
|
||||
.systems-map-node circle,
|
||||
.systems-map-node rect {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
@include bp.respond-to(lg) {
|
||||
.systems-map-figure {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
186
src/app/shared/systems-map/systems-map.spec.ts
Normal file
186
src/app/shared/systems-map/systems-map.spec.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
import { PLATFORM_ID } from '@angular/core';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { provideRouter, Router } from '@angular/router';
|
||||
import { SIGNATURE_COPY } from '../../core/content/signature-copy';
|
||||
import { type AppLocale } from '../../core/i18n/locale';
|
||||
import { LocaleService } from '../../core/i18n/locale.service';
|
||||
import { NavigationService } from '../../core/navigation/navigation.service';
|
||||
import { routePath } from '../../core/routing/route-paths';
|
||||
import { SystemsMap } from './systems-map';
|
||||
import { connectedNodeIds, SYSTEMS_MAP_NODES } from './systems-map.model';
|
||||
|
||||
describe('SystemsMap', () => {
|
||||
async function createFixture(
|
||||
providers: { provide: unknown; useValue: unknown }[] = [],
|
||||
): Promise<ComponentFixture<SystemsMap>> {
|
||||
TestBed.resetTestingModule();
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [SystemsMap],
|
||||
providers: [provideRouter([]), ...providers],
|
||||
}).compileComponents();
|
||||
|
||||
const fixture = TestBed.createComponent(SystemsMap);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
return fixture;
|
||||
}
|
||||
|
||||
function hrefsOf(root: ParentNode, selector: string): string[] {
|
||||
return Array.from(root.querySelectorAll(selector)).map((element) => {
|
||||
return element.getAttribute('href') ?? '';
|
||||
});
|
||||
}
|
||||
|
||||
function expectedNodes(locale: AppLocale) {
|
||||
const relationshipLabel = SIGNATURE_COPY[locale].systemsMap.relationshipLabel;
|
||||
|
||||
return SYSTEMS_MAP_NODES.map((node) => {
|
||||
const connected = new Set(connectedNodeIds(node.id));
|
||||
const connectedLabels = SYSTEMS_MAP_NODES.filter((entry) => connected.has(entry.id)).map(
|
||||
(entry) => entry.label[locale],
|
||||
);
|
||||
return {
|
||||
...node,
|
||||
label: node.label[locale],
|
||||
summary: node.summary[locale],
|
||||
href: routePath(node.routeId, locale),
|
||||
connectedLabels,
|
||||
relationship: relationshipLabel.replace('{targets}', connectedLabels.join(', ')),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
it('exposes the same ordered hrefs in the SVG and the card list from the routing contract', async () => {
|
||||
const fixture = await createFixture();
|
||||
const locale = TestBed.inject(LocaleService).locale();
|
||||
const expected = SYSTEMS_MAP_NODES.map((node) => routePath(node.routeId, locale));
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
|
||||
expect(hrefsOf(compiled, 'svg a')).toEqual(expected);
|
||||
expect(hrefsOf(compiled, '.systems-map-cards a')).toEqual(expected);
|
||||
});
|
||||
|
||||
it('gives every node a non-empty accessible name with label, summary and neighbors', async () => {
|
||||
const fixture = await createFixture();
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
const nodes = expectedNodes(TestBed.inject(LocaleService).locale());
|
||||
const svgAnchors = compiled.querySelectorAll('svg a');
|
||||
const listAnchors = compiled.querySelectorAll('.systems-map-cards a');
|
||||
|
||||
expect(svgAnchors.length).toBe(nodes.length);
|
||||
expect(listAnchors.length).toBe(nodes.length);
|
||||
|
||||
nodes.forEach((node, index) => {
|
||||
const svgName = svgAnchors.item(index).getAttribute('aria-label') ?? '';
|
||||
const listName = listAnchors.item(index).getAttribute('aria-label') ?? '';
|
||||
|
||||
expect(svgName.length).toBeGreaterThan(0);
|
||||
expect(listName.length).toBeGreaterThan(0);
|
||||
expect(svgName).toContain(node.label);
|
||||
expect(svgName).toContain(node.summary);
|
||||
expect(listName).toContain(node.label);
|
||||
expect(listName).toContain(node.summary);
|
||||
|
||||
for (const label of node.connectedLabels) {
|
||||
expect(svgName).toContain(label);
|
||||
expect(listName).toContain(label);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps every node keyboard reachable and navigates on a plain left click', async () => {
|
||||
const fixture = await createFixture();
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
const router = TestBed.inject(Router);
|
||||
const navigation = TestBed.inject(NavigationService);
|
||||
const navigate = vi.spyOn(router, 'navigate').mockResolvedValue(true);
|
||||
const anchors = compiled.querySelectorAll('svg a, .systems-map-cards a');
|
||||
|
||||
anchors.forEach((anchor) => {
|
||||
expect(anchor.getAttribute('tabindex')).not.toBe('-1');
|
||||
});
|
||||
|
||||
const first = SYSTEMS_MAP_NODES[0];
|
||||
const svgAnchor = compiled.querySelector('svg a');
|
||||
expect(svgAnchor).toBeTruthy();
|
||||
svgAnchor?.dispatchEvent(new MouseEvent('click', { button: 0, bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(navigate).toHaveBeenCalledWith(navigation.link(first.routeId));
|
||||
});
|
||||
|
||||
it('rewrites every href when the locale switches to English', async () => {
|
||||
const fixture = await createFixture();
|
||||
const locale = TestBed.inject(LocaleService);
|
||||
locale.setLocale('en');
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
|
||||
const expected = SYSTEMS_MAP_NODES.map((node) => routePath(node.routeId, 'en'));
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
|
||||
expect(hrefsOf(compiled, 'svg a')).toEqual(expected);
|
||||
expect(hrefsOf(compiled, '.systems-map-cards a')).toEqual(expected);
|
||||
});
|
||||
|
||||
it('uses heading and intro inputs and falls back to signature copy when they are empty', async () => {
|
||||
const fixture = await createFixture();
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
const defaults = SIGNATURE_COPY.de.systemsMap;
|
||||
|
||||
expect(compiled.querySelector('.systems-map-heading')?.textContent?.trim()).toBe(
|
||||
defaults.heading,
|
||||
);
|
||||
expect(compiled.querySelector('.systems-map-intro')?.textContent?.trim()).toBe(defaults.intro);
|
||||
|
||||
fixture.componentRef.setInput('heading', 'Eigene Karte');
|
||||
fixture.componentRef.setInput('intro', 'Eigene Einleitung');
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(compiled.querySelector('.systems-map-heading')?.textContent?.trim()).toBe(
|
||||
'Eigene Karte',
|
||||
);
|
||||
expect(compiled.querySelector('.systems-map-intro')?.textContent?.trim()).toBe(
|
||||
'Eigene Einleitung',
|
||||
);
|
||||
|
||||
fixture.componentRef.setInput('heading', '');
|
||||
fixture.componentRef.setInput('intro', ' ');
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(compiled.querySelector('.systems-map-heading')?.textContent?.trim()).toBe(
|
||||
defaults.heading,
|
||||
);
|
||||
expect(compiled.querySelector('.systems-map-intro')?.textContent?.trim()).toBe(defaults.intro);
|
||||
});
|
||||
|
||||
it('renders every node in the card list with label, summary and relationship', async () => {
|
||||
const fixture = await createFixture();
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
const cards = compiled.querySelectorAll('.systems-map-cards li');
|
||||
const nodes = expectedNodes(TestBed.inject(LocaleService).locale());
|
||||
|
||||
expect(cards.length).toBe(nodes.length);
|
||||
nodes.forEach((node, index) => {
|
||||
const text = cards.item(index).textContent ?? '';
|
||||
expect(text).toContain(node.label);
|
||||
expect(text).toContain(node.summary);
|
||||
expect(text).toContain(node.relationship);
|
||||
});
|
||||
});
|
||||
|
||||
it('still renders the SVG, card list, links and summaries on the server', async () => {
|
||||
const fixture = await createFixture([{ provide: PLATFORM_ID, useValue: 'server' }]);
|
||||
const compiled = fixture.nativeElement as HTMLElement;
|
||||
const svgAnchors = compiled.querySelectorAll('svg a');
|
||||
const listAnchors = compiled.querySelectorAll('.systems-map-cards a');
|
||||
|
||||
expect(svgAnchors.length).toBe(SYSTEMS_MAP_NODES.length);
|
||||
expect(listAnchors.length).toBe(SYSTEMS_MAP_NODES.length);
|
||||
|
||||
expectedNodes(TestBed.inject(LocaleService).locale()).forEach((node, index) => {
|
||||
expect(svgAnchors.item(index).getAttribute('href')).toBe(node.href);
|
||||
expect(listAnchors.item(index).textContent).toContain(node.summary);
|
||||
});
|
||||
});
|
||||
});
|
||||
225
src/app/shared/systems-map/systems-map.ts
Normal file
225
src/app/shared/systems-map/systems-map.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, inject, input, signal } from '@angular/core';
|
||||
import { Router, RouterLink } from '@angular/router';
|
||||
import { SIGNATURE_COPY } from '../../core/content/signature-copy';
|
||||
import { type AppLocale } from '../../core/i18n/locale';
|
||||
import { LocaleService } from '../../core/i18n/locale.service';
|
||||
import { NavigationService } from '../../core/navigation/navigation.service';
|
||||
import { routePath } from '../../core/routing/route-paths';
|
||||
import {
|
||||
connectedNodeIds,
|
||||
SYSTEMS_MAP_EDGES,
|
||||
SYSTEMS_MAP_NODE_KINDS,
|
||||
SYSTEMS_MAP_NODES,
|
||||
type SystemsMapNode,
|
||||
type SystemsMapNodeId,
|
||||
} from './systems-map.model';
|
||||
|
||||
let systemsMapInstanceId = 0;
|
||||
|
||||
export interface SystemsMapNodeView {
|
||||
readonly id: SystemsMapNodeId;
|
||||
readonly kind: SystemsMapNode['kind'];
|
||||
readonly routeId: SystemsMapNode['routeId'];
|
||||
readonly x: number;
|
||||
readonly y: number;
|
||||
readonly label: string;
|
||||
readonly labelLines: readonly string[];
|
||||
readonly summary: string;
|
||||
readonly href: string;
|
||||
readonly link: unknown[];
|
||||
readonly relationship: string;
|
||||
readonly accessibleName: string;
|
||||
readonly shapeWidth: number;
|
||||
readonly shapeHeight: number;
|
||||
readonly textStartDy: number;
|
||||
}
|
||||
|
||||
export interface SystemsMapEdgeView {
|
||||
readonly from: SystemsMapNodeId;
|
||||
readonly to: SystemsMapNodeId;
|
||||
readonly x1: number;
|
||||
readonly y1: number;
|
||||
readonly x2: number;
|
||||
readonly y2: number;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-systems-map',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [RouterLink],
|
||||
templateUrl: './systems-map.html',
|
||||
styleUrl: './systems-map.scss',
|
||||
})
|
||||
export class SystemsMap {
|
||||
readonly heading = input('');
|
||||
readonly intro = input('');
|
||||
readonly headingLevel = input<2 | 3>(2);
|
||||
|
||||
private readonly navigation = inject(NavigationService);
|
||||
private readonly localeService = inject(LocaleService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly instanceId = systemsMapInstanceId++;
|
||||
|
||||
protected readonly headingId = `systems-map-heading-${this.instanceId}`;
|
||||
protected readonly svgTitleId = `systems-map-svg-title-${this.instanceId}`;
|
||||
protected readonly svgDescId = `systems-map-svg-desc-${this.instanceId}`;
|
||||
protected readonly listHeadingId = `systems-map-list-${this.instanceId}`;
|
||||
protected readonly legendHeadingId = `systems-map-legend-${this.instanceId}`;
|
||||
|
||||
protected readonly activeNodeId = signal<SystemsMapNodeId | null>(null);
|
||||
|
||||
protected readonly copy = computed(() => SIGNATURE_COPY[this.localeService.locale()].systemsMap);
|
||||
|
||||
protected readonly headingText = computed(() => {
|
||||
const override = this.heading().trim();
|
||||
return override.length > 0 ? override : this.copy().heading;
|
||||
});
|
||||
|
||||
protected readonly introText = computed(() => {
|
||||
const override = this.intro().trim();
|
||||
return override.length > 0 ? override : this.copy().intro;
|
||||
});
|
||||
|
||||
protected readonly nodes = computed(() => {
|
||||
const locale = this.localeService.locale();
|
||||
const copy = this.copy();
|
||||
|
||||
return SYSTEMS_MAP_NODES.map((node) => this.toNodeView(node, locale, copy.relationshipLabel));
|
||||
});
|
||||
|
||||
protected readonly edges = computed((): readonly SystemsMapEdgeView[] => {
|
||||
const byId = new Map(SYSTEMS_MAP_NODES.map((node) => [node.id, node]));
|
||||
|
||||
return SYSTEMS_MAP_EDGES.map((edge) => {
|
||||
const from = byId.get(edge.from);
|
||||
const to = byId.get(edge.to);
|
||||
|
||||
return {
|
||||
from: edge.from,
|
||||
to: edge.to,
|
||||
x1: from?.x ?? 0,
|
||||
y1: from?.y ?? 0,
|
||||
x2: to?.x ?? 0,
|
||||
y2: to?.y ?? 0,
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
protected readonly legendItems = computed(() => {
|
||||
const legend = this.copy().legend;
|
||||
|
||||
return SYSTEMS_MAP_NODE_KINDS.map((kind) => ({
|
||||
kind,
|
||||
label: legend[kind],
|
||||
}));
|
||||
});
|
||||
|
||||
protected readonly activeReadout = computed(() => {
|
||||
const activeId = this.activeNodeId();
|
||||
|
||||
if (!activeId) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const node = this.nodes().find((entry) => entry.id === activeId);
|
||||
return node ? `${node.label}: ${node.relationship}` : '';
|
||||
});
|
||||
|
||||
protected onNodeActivate(event: MouseEvent, node: SystemsMapNodeView): void {
|
||||
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
void this.router.navigate(this.navigation.link(node.routeId));
|
||||
}
|
||||
|
||||
protected onNodeEnter(id: SystemsMapNodeId): void {
|
||||
this.activeNodeId.set(id);
|
||||
}
|
||||
|
||||
protected onNodeLeave(id: SystemsMapNodeId): void {
|
||||
if (this.activeNodeId() === id) {
|
||||
this.activeNodeId.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
protected isConnectedNode(id: SystemsMapNodeId): boolean {
|
||||
const active = this.activeNodeId();
|
||||
|
||||
if (!active) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return active === id || this.neighborSet(active).has(id);
|
||||
}
|
||||
|
||||
protected isDimmedNode(id: SystemsMapNodeId): boolean {
|
||||
const active = this.activeNodeId();
|
||||
|
||||
if (!active) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return active !== id && !this.neighborSet(active).has(id);
|
||||
}
|
||||
|
||||
protected isConnectedEdge(edge: SystemsMapEdgeView): boolean {
|
||||
const active = this.activeNodeId();
|
||||
|
||||
if (!active) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return edge.from === active || edge.to === active;
|
||||
}
|
||||
|
||||
protected isDimmedEdge(edge: SystemsMapEdgeView): boolean {
|
||||
const active = this.activeNodeId();
|
||||
|
||||
if (!active) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return edge.from !== active && edge.to !== active;
|
||||
}
|
||||
|
||||
private toNodeView(
|
||||
node: SystemsMapNode,
|
||||
locale: AppLocale,
|
||||
relationshipLabel: string,
|
||||
): SystemsMapNodeView {
|
||||
const connected = new Set(connectedNodeIds(node.id));
|
||||
const connectedLabels = SYSTEMS_MAP_NODES.filter((entry) => connected.has(entry.id)).map(
|
||||
(entry) => entry.label[locale],
|
||||
);
|
||||
const relationship = relationshipLabel.replace('{targets}', connectedLabels.join(', '));
|
||||
const label = node.label[locale];
|
||||
const labelLines = node.labelLines[locale];
|
||||
const summary = node.summary[locale];
|
||||
const multiline = labelLines.length > 1;
|
||||
const longest = labelLines.reduce((max, line) => Math.max(max, line.length), 0);
|
||||
|
||||
return {
|
||||
id: node.id,
|
||||
kind: node.kind,
|
||||
routeId: node.routeId,
|
||||
x: node.x,
|
||||
y: node.y,
|
||||
label,
|
||||
labelLines,
|
||||
summary,
|
||||
shapeWidth: Math.max(140, longest * 8 + 24),
|
||||
shapeHeight: multiline ? 52 : 40,
|
||||
textStartDy: multiline ? -6 : 4,
|
||||
href: routePath(node.routeId, locale),
|
||||
link: this.navigation.link(node.routeId),
|
||||
relationship,
|
||||
accessibleName: `${label}. ${summary} ${relationship}`,
|
||||
};
|
||||
}
|
||||
|
||||
private neighborSet(id: SystemsMapNodeId): ReadonlySet<SystemsMapNodeId> {
|
||||
return new Set(connectedNodeIds(id));
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,9 @@
|
||||
--focus-ring-color: var(--color-accent);
|
||||
--focus-ring-width: 2px;
|
||||
--focus-ring-offset: 3px;
|
||||
|
||||
/* Header is no longer sticky, so the inset is only breathing room. */
|
||||
--header-offset: var(--space-4);
|
||||
}
|
||||
|
||||
*,
|
||||
@@ -87,11 +90,20 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
scroll-padding-top: var(--header-offset);
|
||||
}
|
||||
|
||||
html {
|
||||
color-scheme: dark;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
:where(article, section, h1, h2, h3)[id] {
|
||||
scroll-margin-top: var(--header-offset);
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--color-surface);
|
||||
|
||||
8
tsconfig.e2e.json
Normal file
8
tsconfig.e2e.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/e2e",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["e2e/**/*.ts", "playwright.config.ts"]
|
||||
}
|
||||
@@ -28,6 +28,9 @@
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.e2e.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/spec",
|
||||
"types": ["vitest/globals"]
|
||||
"types": ["vitest/globals", "node"]
|
||||
},
|
||||
"include": ["src/**/*.d.ts", "src/**/*.spec.ts"]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user