diff --git a/.github/workflows/build-pull-request.yml b/.github/workflows/build-pull-request.yml index 964add54..e74946bc 100644 --- a/.github/workflows/build-pull-request.yml +++ b/.github/workflows/build-pull-request.yml @@ -18,10 +18,14 @@ jobs: - name: Setup node uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - node-version-file: ".node-version" + node-version-file: '.node-version' package-manager-cache: false - name: Install dependencies run: npm ci + - name: Ridge asset gate + run: | + npx vitest run src/app/features/scene/ridge/ridgeAssets.test.ts + echo "ridge assets: $(find public/ridge -type f | wc -l) files, $(du -sb public/ridge | cut -f1) bytes" - name: Build app env: NODE_OPTIONS: '--max_old_space_size=4096' diff --git a/src/app/features/scene/SkyStateControl.tsx b/src/app/features/scene/SkyStateControl.tsx index bac36f00..82c442a8 100644 --- a/src/app/features/scene/SkyStateControl.tsx +++ b/src/app/features/scene/SkyStateControl.tsx @@ -1,4 +1,4 @@ -import React, { MouseEventHandler, useState } from 'react'; +import React, { MouseEventHandler, useEffect, useState } from 'react'; import { Box, config, @@ -15,7 +15,9 @@ import FocusTrap from 'focus-trap-react'; import { stopPropagation } from '../../utils/keyboard'; import { useSkyState } from '../../hooks/useSkyState'; import { SKY_STATES, setSkyState, type SkyState } from './skyState'; +import { loadManifest } from './ridge/manifest'; import { + terrainCredit, WEATHER_CREDIT, WEATHER_CREDIT_URL, WEATHER_DATASET, @@ -50,6 +52,20 @@ export function SkyStateControl() { const sceneStyle: ServedSceneStyle = getSceneStyleOverride() ?? (configuredStyle === 'terrain' ? 'terrain' : 'ridge'); + const place = backgroundScene?.place; + const [credit, setCredit] = useState(); + const ridgeOn = !!backgroundScene && sceneStyle === 'ridge'; + useEffect(() => { + if (!ridgeOn) return undefined; + let live = true; + loadManifest(import.meta.env.BASE_URL, place).then( + (m) => live && setCredit(terrainCredit(m)), + () => live && setCredit(undefined) + ); + return () => { + live = false; + }; + }, [ridgeOn, place]); const open: MouseEventHandler = (evt) => { setCords(evt.currentTarget.getBoundingClientRect()); }; @@ -131,6 +147,11 @@ export function SkyStateControl() { Data + {credit && ( + + {credit} + + )} Datenquelle: GeoSphere Austria -{' '} diff --git a/src/app/features/scene/ridge/credits.test.ts b/src/app/features/scene/ridge/credits.test.ts index 3f7c8bb6..c03be043 100644 --- a/src/app/features/scene/ridge/credits.test.ts +++ b/src/app/features/scene/ridge/credits.test.ts @@ -1,5 +1,9 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { WEATHER_CREDIT, WEATHER_CREDIT_URL, WEATHER_DATASET } from './credits'; +import { WEATHER_CREDIT, WEATHER_CREDIT_URL, WEATHER_DATASET, terrainCredit } from './credits'; +import { parseIndex, parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; import { WEATHER_ATTRIBUTION } from './weatherFeed'; describe('the credits the Sky menu shows', () => { @@ -12,3 +16,26 @@ describe('the credits the Sky menu shows', () => { expect(WEATHER_DATASET).toMatch(/TAWES.*10-minute.*CC BY 4\.0/); }); }); + +describe('the terrain credit', () => { + const shipped = (): { attribution: { credit_line: string; licence: string } } | undefined => { + const root = join(process.cwd(), 'public', 'ridge'); + const index = parseIndex(JSON.parse(readFileSync(join(root, 'index.json'), 'utf8'))); + return JSON.parse( + readFileSync(join(root, index.places[index.default], 'manifest.json'), 'utf8') + ); + }; + + it("is the shipped manifest's attribution, credit line then licence", () => { + const wire = shipped(); + const manifest = parseManifest(wireManifest({ attribution: wire?.attribution }), '/d/'); + expect(terrainCredit(manifest)).toBe( + `${wire?.attribution.credit_line} ${wire?.attribution.licence}` + ); + expect(terrainCredit(manifest)).toMatch(/Copernicus/); + }); + + it('is absent without a manifest', () => { + expect(terrainCredit(undefined)).toBeUndefined(); + }); +}); diff --git a/src/app/features/scene/ridge/credits.ts b/src/app/features/scene/ridge/credits.ts index 6c9138b7..bfe16a72 100644 --- a/src/app/features/scene/ridge/credits.ts +++ b/src/app/features/scene/ridge/credits.ts @@ -1,8 +1,16 @@ // What the Ridge background owes its data sources, shown in the Sky menu (SkyStateControl). Plain strings in their own module so the -// main chunk carries these and not the weather parser; credits.test.ts holds them equal to the sources'. +// main chunk carries these and not the weather parser; credits.test.ts holds them equal to the sources'. The terrain credit is the loaded +// manifest's own `attribution` (terrainCredit): the baker writes it, so no constant here can drift from the bake. +import type { RidgeManifest } from './manifest'; /** GeoSphere's own requested credit line. It names no licence: that is the dataset's (below). */ export const WEATHER_CREDIT = 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at'; export const WEATHER_CREDIT_URL = 'https://data.hub.geosphere.at'; /** The dataset the weather is read from, and its licence as the dataset page names it (data.hub.geosphere.at, tawes-v1-10min). */ export const WEATHER_DATASET = 'TAWES weather stations, 10-minute data (station 11035), CC BY 4.0'; + +/** The terrain's credit line and licence as the loaded bake states them; undefined until a manifest has loaded (no manifest, no line). */ +export const terrainCredit = ( + manifest: Pick | undefined +): string | undefined => + manifest ? `${manifest.attribution.creditLine} ${manifest.attribution.licence}` : undefined; diff --git a/src/app/features/scene/ridge/frameLuma.test.ts b/src/app/features/scene/ridge/frameLuma.test.ts new file mode 100644 index 00000000..271c55c8 --- /dev/null +++ b/src/app/features/scene/ridge/frameLuma.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; +import { inkContrast, themeInk } from './frameLuma'; +import { luminance } from '../../../../sky/skyTokens.js'; + +describe('inkContrast', () => { + it('reads the ink from the themes: dark Noonday ink by day and dusk, light Midnight ink at night', () => { + expect(themeInk('day')).toBe('#342d25'); + expect(themeInk('dusk')).toBe('#342d25'); + expect(themeInk('night')).toBe('#aeccff'); + }); + + it('gives the known ratios on a white and on a black ridge', () => { + const dark = luminance('#342d25'); + const light = luminance('#aeccff'); + const day = inkContrast({ min: 1, max: 1 }, 'day'); + expect(day.atMax).toBeCloseTo(1.05 / (dark + 0.05), 10); + expect(day.atMax).toBeCloseTo(13.6, 0); + const night = inkContrast({ min: 0, max: 0 }, 'night'); + expect(night.atMin).toBeCloseTo((light + 0.05) / 0.05, 10); + expect(night.atMin).toBeCloseTo(12.9, 0); + }); + + it('the worst contrast is where the range comes closest to the ink', () => { + const ink = luminance('#342d25'); + const across = inkContrast({ min: 0, max: 1 }, 'day'); + expect(across.worst).toBe(1); + expect(inkContrast({ min: ink + 0.2, max: 0.9 }, 'day').worst).toBeCloseTo( + (ink + 0.2 + 0.05) / (ink + 0.05), + 10 + ); + }); +}); diff --git a/src/app/features/scene/ridge/frameLuma.ts b/src/app/features/scene/ridge/frameLuma.ts new file mode 100644 index 00000000..e2bd1e0d --- /dev/null +++ b/src/app/features/scene/ridge/frameLuma.ts @@ -0,0 +1,33 @@ +// What a baked frame's recorded luma (manifest `frames[].luma`, WCAG linear relative luminance of the composited planes where they are +// solid enough, export.py) means for the text over it: the contrast of the state's theme ink against the ridge's own extremes, no scrim. +// Data for ridge-ad-legibility, which sizes the scrim from it and owns the 4.5:1 pass/fail; nothing here gates. +import { baked } from '../../../../sky/baked'; +import { luminance } from '../../../../sky/skyTokens.js'; +import type { FixedSkyState } from '../skyBand'; + +export interface FrameLuma { + min: number; + max: number; +} + +/** The theme text ink skyBand.ts's header derives: Noonday Sky's for day and dusk, Midnight Sky's for night. */ +export const themeInk = (state: FixedSkyState): string => + (state === 'night' ? baked.midnight : baked.noonday).tokens.Surface.OnContainer; + +const ratio = (a: number, b: number): number => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); + +/** + * WCAG contrast of the state's ink over a plain backdrop of the ridge's darkest and of its lightest luminance, and `worst`: the lowest + * contrast over every luminance between them (the ink's own luminance clamped into the range, where the two are closest). + */ +export function inkContrast( + luma: FrameLuma, + state: FixedSkyState +): { atMin: number; atMax: number; worst: number } { + const ink = luminance(themeInk(state)); + return { + atMin: ratio(ink, luma.min), + atMax: ratio(ink, luma.max), + worst: ratio(ink, Math.min(luma.max, Math.max(luma.min, ink))), + }; +} diff --git a/src/app/features/scene/ridge/ridgeAssets.test.ts b/src/app/features/scene/ridge/ridgeAssets.test.ts new file mode 100644 index 00000000..d56ffce8 --- /dev/null +++ b/src/app/features/scene/ridge/ridgeAssets.test.ts @@ -0,0 +1,122 @@ +// The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on +// (export.py PAIR_BYTES_MAX, DECODE_BYTES_MAX). Reads with node fs; no decoder: plane sizes come from the manifest. +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { FRAME_KEYS, PLANE_NAMES, parseIndex, parseManifest } from './manifest'; + +/** The same two constants as scripts/ridge-bake/export.py: two adjacent frames, fetched and decoded. */ +export const PAIR_BYTES_MAX = 800_000; +export const DECODE_BYTES_MAX = 20_000_000; + +interface WirePlane { + file: string; + bytes: number; + w: number; + h: number; +} +interface WireFrame { + key: string; + planes: Record; + luma: { min: number; max: number }; +} +export interface WireManifest { + bake_id: string; + frames: WireFrame[]; +} + +const planes = (f: WireFrame): WirePlane[] => PLANE_NAMES.map((n) => f.planes[n]); + +/** Why a manifest breaks the size gate, or undefined. Frames are taken in FRAME_KEYS order; the pairs are neighbours, and night meets dawn. */ +export function sizeGate(m: WireManifest): string | undefined { + const byKey = FRAME_KEYS.map((k) => m.frames.find((f) => f.key === k) as WireFrame); + for (let i = 0; i < byKey.length; i += 1) { + const pair = [byKey[i], byKey[(i + 1) % byKey.length]]; + const ps = pair.flatMap(planes); + const fetched = ps.reduce((a, p) => a + p.bytes, 0); + const decoded = ps.reduce((a, p) => a + p.w * p.h * 4, 0); + if (fetched > PAIR_BYTES_MAX) return `${pair[0].key}+${pair[1].key} fetches ${fetched}`; + if (decoded > DECODE_BYTES_MAX) return `${pair[0].key}+${pair[1].key} decodes ${decoded}`; + } + return undefined; +} + +const ROOT = join(process.cwd(), 'public', 'ridge'); +const readJson = (p: string): unknown => JSON.parse(readFileSync(p, 'utf8')); +const index = parseIndex(readJson(join(ROOT, 'index.json'))); +const dirs = Object.entries(index.places); + +describe('the committed ridge assets', () => { + it('ship at least one place, and the index default is one of them', () => { + expect(dirs.length).toBeGreaterThan(0); + expect(index.places[index.default]).toBeDefined(); + }); + + dirs.forEach(([id, dir]) => { + describe(`${id} (${dir})`, () => { + const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest; + + it('parses, and its directory ends in its bake id', () => { + expect(() => parseManifest(raw, `${dir}/`)).not.toThrow(); + expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true); + }); + + it('has every plane file, at the length the manifest states', () => { + raw.frames.flatMap(planes).forEach((p) => { + expect(statSync(join(ROOT, dir, p.file)).size, p.file).toBe(p.bytes); + }); + }); + + it('keeps every adjacent pair of frames inside the fetch and decode budget', () => { + expect(sizeGate(raw)).toBeUndefined(); + }); + + it('records a finite luma for every frame', () => { + expect(raw.frames).toHaveLength(FRAME_KEYS.length); + raw.frames.forEach((f) => { + expect(Number.isFinite(f.luma.min) && Number.isFinite(f.luma.max), f.key).toBe(true); + expect(f.luma.min, f.key).toBeLessThanOrEqual(f.luma.max); + }); + }); + }); + }); + + it('holds no file a manifest does not name', () => { + const named = new Set(['index.json']); + dirs.forEach(([, dir]) => { + named.add(`${dir}/manifest.json`); + (readJson(join(ROOT, dir, 'manifest.json')) as WireManifest).frames + .flatMap(planes) + .forEach((p) => named.add(`${dir}/${p.file}`)); + }); + const onDisk = readdirSync(ROOT, { recursive: true, withFileTypes: true }) + .filter((e) => e.isFile()) + .map((e) => join(e.parentPath, e.name).slice(ROOT.length + 1)); + expect(onDisk.filter((f) => !named.has(f))).toEqual([]); + expect([...named].filter((f) => !existsSync(join(ROOT, f)))).toEqual([]); + }); +}); + +describe('sizeGate', () => { + const plane = (bytes: number): WirePlane => ({ file: 'x.webp', bytes, w: 1280, h: 600 }); + const frame = (key: string, bytes: number): WireFrame => ({ + key, + planes: { far: plane(bytes), mid: plane(bytes), near: plane(bytes) }, + luma: { min: 0, max: 1 }, + }); + const set = (bytes: number): WireManifest => ({ + bake_id: 'x', + frames: FRAME_KEYS.map((k) => frame(k, bytes)), + }); + + it('passes a pair at the budget and fails a 900 KB pair', () => { + expect(sizeGate(set(133_333))).toBeUndefined(); + expect(sizeGate(set(150_000))).toMatch(/fetches 900000/); + }); + + it('fails a pair that decodes past the budget', () => { + const m = set(1); + m.frames[2].planes.far = { file: 'x.webp', bytes: 1, w: 4096, h: 1000 }; + expect(sizeGate(m)).toMatch(/decodes/); + }); +});