strata-react 1.0.31 → 1.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/map.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"map.js","names":[],"sources":["../src/map/map-styles.ts","../src/map/route-map.tsx"],"sourcesContent":["import leafletCss from \"leaflet/dist/leaflet.css?inline\";\n\n// Leaflet draws with its own stylesheet (panes, tiles, controls positioned by class), which an app\n// would otherwise have to import beside strata-react's. That is an install step a component must\n// not need (CLAUDE.md, \"Imports decide the peers\"), so the map puts it in the page itself, once,\n// followed by the few rules that make Leaflet's own parts (zoom buttons, attribution, tooltips)\n// read as the app: its roles, its control height, its radius. The dark treatment is here too, in\n// one place: a map without dark tiles is turned to the dark scheme with a filter, which is a\n// fallback, not a design (an app with a dark tile set passes it as `tiles.dark`).\nconst strata = `\n.strata-map .leaflet-container { background: var(--surface-sunken); color: var(--foreground); font: inherit; }\n.strata-map .leaflet-container:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; }\n.strata-map .leaflet-bar { border: 1px solid var(--border); border-radius: var(--radius-control, 4px); box-shadow: none; overflow: hidden; }\n.strata-map .leaflet-bar a { background: var(--background); color: var(--foreground); border-bottom: 1px solid var(--border); width: var(--control-h, 2.5rem); height: var(--control-h, 2.5rem); line-height: var(--control-h, 2.5rem); }\n.strata-map .leaflet-control-zoom-in, .strata-map .leaflet-control-zoom-out { font: inherit; font-size: 1.25rem; font-weight: 600; }\n.strata-map .leaflet-bar a:last-child { border-bottom: 0; }\n.strata-map .leaflet-bar a:hover, .strata-map .leaflet-bar a:focus-visible { background: var(--muted); }\n.strata-map .leaflet-bar a.leaflet-disabled { color: var(--muted-foreground); background: var(--background); cursor: not-allowed; }\n.strata-map .leaflet-control-attribution { background: color-mix(in oklab, var(--background) 85%, transparent); color: var(--muted-foreground); font-size: 0.75rem; }\n.strata-map .leaflet-control-attribution a { color: inherit; text-decoration: underline; }\n.strata-map .leaflet-tooltip { background: var(--background); color: var(--foreground); border: 1px solid var(--border); border-radius: var(--radius-control, 4px); box-shadow: none; font: inherit; font-size: 0.8125rem; padding: 0.125rem 0.375rem; }\n.strata-map .leaflet-tooltip::before { display: none; }\n.strata-map[data-dark-treatment] .leaflet-tile-pane { filter: invert(1) hue-rotate(180deg) brightness(0.9) contrast(0.9); }\n.strata-map .strata-map-arrow { background: none; border: 0; }\n`;\n\nlet installed = false;\n\n/** Puts Leaflet's stylesheet and the token overrides in the document head, once. */\nexport function installMapStyles() {\n if (installed || typeof document === \"undefined\") return;\n installed = true;\n const el = document.createElement(\"style\");\n el.setAttribute(\"data-strata-map\", \"\");\n el.textContent = leafletCss + strata;\n document.head.appendChild(el);\n}\n","import * as React from \"react\";\nimport L from \"leaflet\";\nimport { useColorScheme } from \"../components/theme\";\nimport { cn } from \"../lib/utils\";\nimport { format } from \"../lib/format\";\nimport { geo, type LatLng } from \"../lib/geo\";\nimport { installMapStyles } from \"./map-styles\";\n\n// A themed map of routes with a position that moves along them (strata-react issue #80, from\n// strata-vid's MapPanel and jonathanburnhams.com's activity maps). It is behind its own entry,\n// `strata-react/map`, because Leaflet is heavy and an app that draws no maps should not install it:\n// Leaflet is an optional peer and nothing in the main entry imports it.\n//\n// Leaflet, without react-leaflet (Jonathan's choice, 2026-11-12). react-leaflet binds every layer to\n// a React element, so a position that moves sixty times a second re-renders the route elements\n// beside it; here the map is made once, the routes are one effect that runs only when the routes\n// change, and the position is another that calls `setLatLng` on one marker. A position update\n// touches nothing else: no route is redrawn, none is recreated.\n//\n// What the app supplies, and what the component decides:\n// - Tiles are the app's (`tiles.light`, `tiles.dark`, each with the attribution its provider\n// requires, shown on the map). A dark scheme uses `tiles.dark` when there is one, else the light\n// tiles under a filter (see map-styles.ts); the choice follows the colour scheme.\n// - Colours are roles. A route's colour is any CSS colour (`var(--chart-2)`, `var(--info)`), resolved\n// against the map's own element so SVG strokes, which Leaflet writes as attributes, get a real\n// colour that follows the scheme. Routes default to the chart palette in order.\n// - Colour by value (`values` on a route plus `colourScale`) follows LineChart's rules (§3.8): the\n// colour is a fact of the subject, steps are the app's, and a key names them (`colourScaleLabel`\n// and the step thresholds through `formatValue`) so colour is never the only cue. Runs of one\n// step are drawn as one line, so a long route is a few polylines, not thousands.\n// - One route is the common case: it gets direction chevrons and start and finish marks (a loop is\n// one mark) by default; with several routes those are off unless a route asks.\n// - Fit-to-content happens on first show and when the set of routes changes, not when a route's\n// points are replaced by the same ids, so a person who has zoomed is not thrown back.\n// - Overlay slots, `topEnd` and `bottomStart`, sit where Leaflet puts nothing (it uses the top\n// start for zoom and the bottom end for attribution), so an app's own control or figure never\n// covers a required notice.\n//\n// Keyboard and screen readers. Leaflet's container is a focus stop: arrows pan, + and − zoom. It is\n// named by `label` and described by a text alternative that says what is drawn (each route, its\n// length, whether it is a loop, and how far along the position is), written from the data or given\n// as `summary`. Hovering a route or a mark is a bonus; its facts are in that text. Choosing a route\n// is `onSelect`, and a screen that lets a person choose one lists its routes beside the map (a\n// pointer click on a line has no keyboard equivalent inside Leaflet's SVG, so the list is the path).\n//\n// No animation: zoom, fade and inertia are off, because a map is panned all the time and a tile\n// fade makes a screenshot depend on timing (character by frequency, and strata-visual).\n//\n// Checked: React Aria has no map or geographic part. Leaflet's own keyboard handler and focus are\n// kept as they are.\n\n/** A source of map tiles: a URL template the app's provider documents, and the attribution it requires. */\nexport type TileSource = {\n /** `https://tiles.example.com/{z}/{x}/{y}.png`; `{s}` and `{r}` work as in Leaflet. */\n url: string;\n /** What the provider requires shown (HTML allowed: \"© OpenStreetMap contributors\"). */\n attribution: string;\n subdomains?: string;\n minZoom?: number;\n maxZoom?: number;\n};\n\n/** One route on the map. */\nexport type MapRoute = {\n id: string;\n /** Its name, in the text alternative and on hover (\"Wednesday run\"). */\n label: string;\n points: readonly LatLng[];\n /** Any CSS colour, normally a role (`var(--chart-2)`). Default: the chart palette in order. */\n colour?: string;\n /** Line width in pixels. Default 4. */\n weight?: number;\n /** One value per point, coloured by `colourScale` (speed, elevation, heart rate). */\n values?: readonly number[];\n /** Direction chevrons along the line: true for five, or a count. Default on for a single route. */\n arrows?: boolean | number;\n /** Start and finish marks. Default on for a single route. */\n ends?: boolean;\n};\n\nexport type RouteMapProps = {\n /** Names the map (\"Route of Wednesday's run\"). */\n label: string;\n /** Keep this array stable between renders (state or `useMemo`): the routes are redrawn when it changes, which a moving position must not cause. */\n routes: readonly MapRoute[];\n tiles: { light: TileSource; dark?: TileSource };\n /** Where the moving thing is now. Moved without redrawing any route; null for none. */\n position?: LatLng | null;\n /** What the position is called in the text alternative. Default \"Current position\". */\n positionLabel?: string;\n /** Keep the position in view as it moves. */\n follow?: boolean;\n /** The route drawn heavier, with the others lighter. */\n selectedId?: string | null;\n /** A route line was pressed. Give the app's own list of routes the same action for the keyboard. */\n onSelect?: (id: string) => void;\n /** Step colours for routes that have `values`: a step starts at `at` and runs to the next. */\n colourScale?: readonly { at: number; colour: string }[];\n /** What the colours mean, written in the key (\"Speed\"). */\n colourScaleLabel?: string;\n /** Writes a value in the key and the text alternative (\"12 km/h\"). Default the plain number. */\n formatValue?: (value: number) => string;\n /** Replaces the generated text alternative. */\n summary?: string;\n /** Units for lengths in the generated text. Default metric. */\n units?: \"metric\" | \"imperial\";\n /** Wheel zoom. Off by default so the page still scrolls past the map. */\n scrollZoom?: boolean;\n /** An app control or figure in the top end corner (Leaflet leaves it free). */\n topEnd?: React.ReactNode;\n /** An app legend or figure in the bottom start corner, below the colour key when there is one. */\n bottomStart?: React.ReactNode;\n /** Layout only. The map is 16:9 and at least 16rem tall unless a height is given. */\n className?: string;\n};\n\n/** The smallest and largest value, without spreading the array (a long recording passes the engine's argument limit). */\nfunction extent(values: readonly number[]): [number, number] {\n let lo = Infinity;\n let hi = -Infinity;\n for (const v of values) {\n if (v < lo) lo = v;\n if (v > hi) hi = v;\n }\n return [lo, hi];\n}\n\nconst tuple = (p: LatLng): L.LatLngTuple => [p[0], p[1]];\nconst plain = (v: number) => String(v);\n\n/** `value`, sampled once a second (a throttle, not a debounce: a value that changes every frame still comes through): for text a screen reader may read, which must not change sixty times a second. */\nfunction useSlow<T>(value: T, ms = 1000): T {\n const [slow, setSlow] = React.useState(value);\n const latest = React.useRef(value);\n latest.current = value;\n React.useEffect(() => {\n const id = window.setInterval(() => setSlow(latest.current), ms);\n return () => window.clearInterval(id);\n }, [ms]);\n return slow;\n}\n\nconst PALETTE = [1, 2, 3, 4, 5].map((n) => `var(--chart-${n})`);\n\n/** The colour a CSS value (a `var()`, a role) resolves to on `el`, so an SVG attribute gets a real one. Falls back to the value itself. */\nfunction resolveColour(el: HTMLElement, value: string): string {\n const probe = document.createElement(\"span\");\n probe.style.color = value;\n el.appendChild(probe);\n const resolved = getComputedStyle(probe).color;\n probe.remove();\n return resolved || value;\n}\n\n/** Indices where a run of one step ends, so a coloured route is a few polylines. */\nfunction stepRuns(points: readonly LatLng[], values: readonly number[], stepOf: (v: number) => number) {\n const runs: { from: number; to: number; step: number }[] = [];\n for (let i = 1; i < points.length; i++) {\n const step = stepOf(((values[i - 1] ?? 0) + (values[i] ?? 0)) / 2);\n const last = runs[runs.length - 1];\n if (last && last.step === step) last.to = i;\n else runs.push({ from: i - 1, to: i, step });\n }\n return runs;\n}\n\nconst arrowHtml = (bearing: number, colour: string, halo: string) =>\n `<svg width=\"26\" height=\"26\" viewBox=\"0 0 26 26\" aria-hidden=\"true\" style=\"transform: rotate(${bearing.toFixed(0)}deg)\">` +\n `<path d=\"M6 17 L13 9 L20 17\" fill=\"none\" stroke=\"${halo}\" stroke-width=\"7\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>` +\n `<path d=\"M6 17 L13 9 L20 17\" fill=\"none\" stroke=\"${colour}\" stroke-width=\"3.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`;\n\n/** A map of one or more routes with a position that moves along them, on tiles the app supplies, themed from its roles. Leaflet, behind `strata-react/map`. */\nexport function RouteMap({\n label,\n routes,\n tiles,\n position = null,\n positionLabel = \"Current position\",\n follow = false,\n selectedId = null,\n onSelect,\n colourScale,\n colourScaleLabel,\n formatValue = plain,\n summary,\n units = \"metric\",\n scrollZoom = false,\n topEnd,\n bottomStart,\n className,\n}: RouteMapProps) {\n const { scheme } = useColorScheme();\n const host = React.useRef<HTMLDivElement>(null);\n const root = React.useRef<HTMLDivElement>(null);\n const [map, setMap] = React.useState<L.Map | null>(null);\n const summaryId = React.useId();\n const latest = React.useRef({ onSelect });\n latest.current = { onSelect };\n const selectable = Boolean(onSelect);\n const marker = React.useRef<L.CircleMarker | null>(null);\n const markerScheme = React.useRef<string | null>(null);\n\n const darkTiles = scheme === \"dark\" ? tiles.dark : undefined;\n const source = darkTiles ?? tiles.light;\n const treated = scheme === \"dark\" && !tiles.dark;\n const stops = React.useMemo(() => (colourScale ? [...colourScale].sort((a, b) => a.at - b.at) : []), [colourScale]);\n\n // The map, made once. Its container is Leaflet's; React owns only the wrapper around it.\n React.useEffect(() => {\n installMapStyles();\n const el = host.current;\n if (!el) return;\n const m = L.map(el, { scrollWheelZoom: scrollZoom, fadeAnimation: false, zoomAnimation: false, markerZoomAnimation: false, inertia: false, attributionControl: false, zoomSnap: 0.5 });\n L.control.attribution({ prefix: '<a href=\"https://leafletjs.com\">Leaflet</a>' }).addTo(m);\n el.setAttribute(\"aria-roledescription\", \"map\");\n // Leaflet follows the window, not its container; a pane that resizes (a Workspace split) needs the same.\n const ro = new ResizeObserver(() => m.invalidateSize({ animate: false }));\n ro.observe(el);\n setMap(m);\n return () => {\n ro.disconnect();\n marker.current = null;\n markerScheme.current = null;\n m.remove();\n setMap(null);\n };\n // The wheel setting is applied below, so the map is not rebuilt for it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n React.useEffect(() => {\n if (!map) return;\n if (scrollZoom) map.scrollWheelZoom.enable();\n else map.scrollWheelZoom.disable();\n }, [map, scrollZoom]);\n\n // The text alternative: written from the data unless the app gives one. The position is in it, but\n // it is not a live region: a position that moves many times a second must not be announced.\n const spoken = useSlow(position);\n const text = React.useMemo(() => {\n if (summary) return summary;\n if (!routes.length) return \"No routes to show.\";\n const parts = routes.map((r) => {\n const along = geo.cumulative(r.points);\n const total = along[along.length - 1] ?? 0;\n const ends = geo.ends(r.points);\n const shape = ends?.loop ? \", a loop\" : \"\";\n let here = \"\";\n if (spoken && r.points.length) {\n const i = geo.nearest(r.points, spoken);\n here = ` ${positionLabel}: ${format.distance(along[i] ?? 0, units)} along.`;\n }\n let range = \"\";\n if (stops.length && r.values?.length) range = ` ${colourScaleLabel ?? \"Value\"} from ${formatValue(extent(r.values)[0])} to ${formatValue(extent(r.values)[1])}.`;\n return `${r.label}: ${format.distance(total, units)}${shape}.${range}${here}`;\n });\n return `Map with ${routes.length === 1 ? \"one route\" : `${routes.length} routes`}. ${parts.join(\" \")}`;\n }, [summary, routes, spoken, positionLabel, units, stops.length, colourScaleLabel, formatValue]);\n\n React.useEffect(() => {\n if (!map) return;\n const c = map.getContainer();\n c.setAttribute(\"aria-label\", label);\n c.setAttribute(\"aria-describedby\", summaryId);\n }, [map, label, summaryId]);\n\n // Tiles: the light set, or the dark one in the dark scheme.\n React.useEffect(() => {\n if (!map) return;\n const layer = L.tileLayer(source.url, { attribution: source.attribution, subdomains: source.subdomains ?? \"abc\", minZoom: source.minZoom, maxZoom: source.maxZoom ?? 19, keepBuffer: 1 });\n layer.addTo(map);\n return () => void layer.remove();\n }, [map, source.url, source.attribution, source.subdomains, source.minZoom, source.maxZoom]);\n\n // The routes: redrawn when the routes, the scheme (colours resolve differently), the selection or\n // the scale change, and never for a position update.\n React.useEffect(() => {\n if (!map) return;\n const group = L.featureGroup().addTo(map);\n const el = map.getContainer();\n const halo = resolveColour(el, \"var(--background)\");\n const single = routes.length === 1;\n const stepOf = (v: number) => {\n let at = 0;\n stops.forEach((s, i) => {\n if (s.at <= v) at = i;\n });\n return at;\n };\n routes.forEach((route, index) => {\n if (route.points.length < 2) return;\n const base = resolveColour(el, route.colour ?? PALETTE[index % PALETTE.length]);\n const selected = route.id === selectedId;\n const dim = selectedId !== null && !selected;\n const weight = (route.weight ?? 4) + (selected ? 2 : 0);\n const style = { weight, opacity: dim ? 0.55 : 1, lineCap: \"round\" as const, lineJoin: \"round\" as const, interactive: selectable, bubblingMouseEvents: false };\n const lines: L.Polyline[] = [];\n if (stops.length && route.values?.length) {\n for (const run of stepRuns(route.points, route.values, stepOf)) {\n lines.push(L.polyline(route.points.slice(run.from, run.to + 1).map(tuple), { ...style, color: resolveColour(el, stops[run.step].colour) }));\n }\n } else {\n lines.push(L.polyline(route.points.map(tuple), { ...style, color: base }));\n }\n for (const line of lines) {\n line.bindTooltip(route.label, { sticky: true });\n line.on(\"click\", () => latest.current.onSelect?.(route.id));\n line.addTo(group);\n }\n const chevrons = route.arrows === undefined ? (single ? 5 : 0) : route.arrows === true ? 5 : route.arrows === false ? 0 : route.arrows;\n if (chevrons > 0) {\n for (const a of geo.arrows(route.points, chevrons)) {\n L.marker(tuple(a.position), {\n interactive: false,\n keyboard: false,\n icon: L.divIcon({ className: \"strata-map-arrow\", iconSize: [26, 26], iconAnchor: [13, 13], html: arrowHtml(a.bearing, base, halo) }),\n }).addTo(group);\n }\n }\n if (route.ends ?? single) {\n const ends = geo.ends(route.points);\n if (ends) {\n const success = resolveColour(el, \"var(--success)\");\n const danger = resolveColour(el, \"var(--danger)\");\n const mark = (at: LatLng, text: string, options: L.CircleMarkerOptions) => L.circleMarker(tuple(at), { radius: 7, interactive: true, bubblingMouseEvents: false, ...options }).bindTooltip(text).addTo(group);\n // Shapes carry the meaning as well as colour: a filled start, a ringed finish, one of each for a loop.\n if (ends.loop) mark(ends.start, `${route.label}: start and finish`, { color: danger, weight: 3, fillColor: success, fillOpacity: 1 });\n else {\n mark(ends.finish, `${route.label}: finish`, { color: danger, weight: 3, fillColor: halo, fillOpacity: 1 });\n mark(ends.start, `${route.label}: start`, { color: halo, weight: 2, fillColor: success, fillOpacity: 1 });\n }\n }\n }\n });\n return () => void group.remove();\n }, [map, routes, scheme, selectedId, stops, selectable]);\n\n // Fit to the routes when the map first has a size and whenever the set of routes changes.\n const routeKey = routes.map((r) => r.id).join(\"\\n\");\n const fitted = React.useRef<string | null>(null);\n React.useEffect(() => {\n if (!map) return;\n const fit = () => {\n const size = map.getSize();\n if (fitted.current === routeKey || size.x === 0 || size.y === 0) return;\n const box = geo.bounds(routes.flatMap((r) => r.points));\n if (!box) return;\n fitted.current = routeKey;\n map.fitBounds([tuple(box[0]), tuple(box[1])], { padding: [24, 24], animate: false, maxZoom: 17 });\n };\n fit();\n map.on(\"resize\", fit);\n return () => void map.off(\"resize\", fit);\n // `routes` is read when the key says the set changed; a new array of the same ids does not refit.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map, routeKey]);\n\n // The position: one marker, moved with `setLatLng`. Nothing else is touched.\n const [lat, lng] = position ?? [null, null];\n React.useEffect(() => {\n if (!map) return;\n if (lat === null || lng === null) {\n marker.current?.remove();\n marker.current = null;\n return;\n }\n const el = map.getContainer();\n if (!marker.current) {\n marker.current = L.circleMarker([lat, lng], { radius: 8, weight: 3, fillOpacity: 1, interactive: false }).addTo(map);\n markerScheme.current = null;\n } else marker.current.setLatLng([lat, lng]);\n if (markerScheme.current !== scheme) {\n markerScheme.current = scheme;\n marker.current.setStyle({ color: resolveColour(el, \"var(--background)\"), fillColor: resolveColour(el, \"var(--primary)\") });\n }\n if (follow && !map.getBounds().pad(-0.2).contains([lat, lng])) map.panTo([lat, lng], { animate: false });\n }, [map, lat, lng, follow, scheme]);\n\n return (\n <div ref={root} data-dark-treatment={treated ? \"\" : undefined} className={cn(\"strata-map relative isolate aspect-video min-h-64 overflow-hidden rounded-surface border border-border\", className)}>\n <div ref={host} className=\"size-full\" />\n <p id={summaryId} className=\"sr-only\">\n {text}\n </p>\n {topEnd && <div className=\"absolute top-2 right-2 z-1000\">{topEnd}</div>}\n {(stops.length > 0 || bottomStart) && (\n <div className=\"absolute bottom-6 left-2 z-1000 grid max-w-[60%] gap-2\">\n {stops.length > 0 && <ColourKey stops={stops} label={colourScaleLabel} formatValue={formatValue} />}\n {bottomStart}\n </div>\n )}\n </div>\n );\n}\n\n/** The key to a colour scale: its name, then each step with where it starts, so colour is never the only cue. */\nfunction ColourKey({ stops, label, formatValue }: { stops: readonly { at: number; colour: string }[]; label?: string; formatValue: (v: number) => string }) {\n return (\n <div className=\"rounded-control border border-border bg-background px-2 py-1.5 type-caption text-foreground\">\n {label && <p className=\"font-medium\">{label}</p>}\n <ul className=\"grid gap-0.5\">\n {stops.map((s) => (\n <li key={s.at} className=\"flex items-center gap-2 tabular-nums\">\n <svg width=\"20\" height=\"4\" aria-hidden>\n <line x1=\"0\" x2=\"20\" y1=\"2\" y2=\"2\" stroke={s.colour} strokeWidth={4} strokeLinecap=\"round\" />\n </svg>\n <span>{`From ${formatValue(s.at)}`}</span>\n </li>\n ))}\n </ul>\n </div>\n );\n}\n"],"mappings":";;;;;;;AASA,IAAM,SAAS;;;;;;;;;;;;;;;;AAiBf,IAAI,YAAY;;AAGhB,SAAgB,mBAAmB;CACjC,IAAI,aAAa,OAAO,aAAa,aAAa;CAClD,YAAY;CACZ,MAAM,KAAK,SAAS,cAAc,OAAO;CACzC,GAAG,aAAa,mBAAmB,EAAE;CACrC,GAAG,cAAc,aAAa;CAC9B,SAAS,KAAK,YAAY,EAAE;AAC9B;;;ACiFA,SAAS,OAAO,QAA6C;CAC3D,IAAI,KAAK;CACT,IAAI,KAAK;CACT,KAAK,MAAM,KAAK,QAAQ;EACtB,IAAI,IAAI,IAAI,KAAK;EACjB,IAAI,IAAI,IAAI,KAAK;CACnB;CACA,OAAO,CAAC,IAAI,EAAE;AAChB;AAEA,IAAM,SAAS,MAA6B,CAAC,EAAE,IAAI,EAAE,EAAE;AACvD,IAAM,SAAS,MAAc,OAAO,CAAC;;AAGrC,SAAS,QAAW,OAAU,KAAK,KAAS;CAC1C,MAAM,CAAC,MAAM,WAAW,MAAM,SAAS,KAAK;CAC5C,MAAM,SAAS,MA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WAAU;GAAe,UAAA;EAAS,CAAA,GAC/C,oBAAC,MAAD;GAAI,WAAU;GACX,UAAA,MAAM,KAAK,MACV,qBAAC,MAAD;IAAe,WAAU;IAAzB,UAAA,CACE,oBAAC,OAAD;KAAK,OAAM;KAAK,QAAO;KAAI,eAAA;KACzB,UAAA,oBAAC,QAAD;MAAM,IAAG;MAAI,IAAG;MAAK,IAAG;MAAI,IAAG;MAAI,QAAQ,EAAE;MAAQ,aAAa;MAAG,eAAc;KAAS,CAAA;IACzF,CAAA,GACL,oBAAC,QAAD,EAAA,UAAO,QAAQ,YAAY,EAAE,EAAE,IAAU,CAAA,CACvC;GALK,GAAA,EAAE,EAKP,CACL;EACC,CAAA,CACD;;AAET"}
1
+ {"version":3,"file":"map.js","names":["Tooltip","AriaButton","_Fragment"],"sources":["../src/map/map-styles.ts","../src/map/fan.ts","../src/map/markers.tsx","../src/map/route-map.tsx"],"sourcesContent":["import leafletCss from \"leaflet/dist/leaflet.css?inline\";\n\n// Leaflet draws with its own stylesheet (panes, tiles, controls positioned by class), which an app\n// would otherwise have to import beside strata-react's. That is an install step a component must\n// not need (CLAUDE.md, \"Imports decide the peers\"), so the map puts it in the page itself, once,\n// followed by the few rules that make Leaflet's own parts (zoom buttons, attribution, tooltips)\n// read as the app: its roles, its control height, its radius. The dark treatment is here too, in\n// one place: a map without dark tiles is turned to the dark scheme with a filter, which is a\n// fallback, not a design (an app with a dark tile set passes it as `tiles.dark`).\nconst strata = `\n.strata-map .leaflet-container { background: var(--surface-sunken); color: var(--foreground); font: inherit; }\n.strata-map .leaflet-container:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; }\n.strata-map .leaflet-bar { border: 1px solid var(--border); border-radius: var(--radius-control, 4px); box-shadow: none; overflow: hidden; }\n.strata-map .leaflet-bar a { background: var(--background); color: var(--foreground); border-bottom: 1px solid var(--border); width: var(--control-h, 2.5rem); height: var(--control-h, 2.5rem); line-height: var(--control-h, 2.5rem); }\n.strata-map .leaflet-control-zoom-in, .strata-map .leaflet-control-zoom-out { font: inherit; font-size: 1.25rem; font-weight: 600; }\n.strata-map .leaflet-bar a:last-child { border-bottom: 0; }\n.strata-map .leaflet-bar a:hover, .strata-map .leaflet-bar a:focus-visible { background: var(--muted); }\n.strata-map .leaflet-bar a.leaflet-disabled { color: var(--muted-foreground); background: var(--background); cursor: not-allowed; }\n.strata-map .leaflet-control-attribution { background: color-mix(in oklab, var(--background) 85%, transparent); color: var(--muted-foreground); font-size: 0.75rem; }\n.strata-map .leaflet-control-attribution a { color: inherit; text-decoration: underline; }\n.strata-map .leaflet-tooltip { background: var(--background); color: var(--foreground); border: 1px solid var(--border); border-radius: var(--radius-control, 4px); box-shadow: none; font: inherit; font-size: 0.8125rem; padding: 0.125rem 0.375rem; }\n.strata-map .leaflet-tooltip::before { display: none; }\n.strata-map[data-dark-treatment] .leaflet-tile-pane { filter: invert(1) hue-rotate(180deg) brightness(0.9) contrast(0.9); }\n.strata-map .strata-map-arrow { background: none; border: 0; }\n.strata-map .strata-map-marker, .strata-map .strata-map-crosshair { background: none; border: 0; display: grid; place-items: center; }\n.strata-map .strata-map-reset { display: grid; place-items: center; }\n.strata-map .strata-map-picking, .strata-map .strata-map-picking .leaflet-interactive { cursor: crosshair; }\n`;\n\nlet installed = false;\n\n/** Puts Leaflet's stylesheet and the token overrides in the document head, once. */\nexport function installMapStyles() {\n if (installed || typeof document === \"undefined\") return;\n installed = true;\n const el = document.createElement(\"style\");\n el.setAttribute(\"data-strata-map\", \"\");\n el.textContent = leafletCss + strata;\n document.head.appendChild(el);\n}\n","// Markers that would sit on top of each other are moved apart in a small fan (strata-react issue #181).\n// Pure maths on pixel positions, no map and no DOM, so the rule can be tested and so a frame is the\n// same everywhere. The positions are in the map's *world* pixels at the current zoom (not the screen's),\n// so panning never changes the result, only zooming does, and zooming in is what settles the fan.\n//\n// Rules: markers within `gap` pixels of each other, directly or through a chain of neighbours\n// (single linkage), form one group. A group of two to six goes on one circle just wide enough that\n// neighbours are `gap` apart; a larger group fills rings of radius gap, 2 gap, 3 gap… each holding as\n// many as fit, so forty markers on one spot make a tidy rosette, not one huge circle. The first marker\n// of a group (input order) goes straight up and the rest follow clockwise: the same input always gives the\n// same output. A lone marker does not move.\n\n/** A marker's true place in world pixels. */\nexport type FanInput = { id: string; x: number; y: number };\n/** Where it is drawn; `fanned` is true when that is not its true place (draw a leader line back). */\nexport type FanOutput = { id: string; x: number; y: number; fanned: boolean };\n\n/** Move apart markers closer than `gap` pixels. Output is in input order. */\nexport function fanOut(items: readonly FanInput[], gap = 26): FanOutput[] {\n const parent = items.map((_, i) => i);\n const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i])));\n // A grid of `gap`-sized cells, so each marker is compared with its neighbours and not with all 500.\n const cells = new Map<string, number[]>();\n const key = (cx: number, cy: number) => `${cx},${cy}`;\n items.forEach((p, i) => {\n const [cx, cy] = [Math.floor(p.x / gap), Math.floor(p.y / gap)];\n for (let dx = -1; dx <= 1; dx++)\n for (let dy = -1; dy <= 1; dy++)\n for (const j of cells.get(key(cx + dx, cy + dy)) ?? []) {\n if (Math.hypot(items[j].x - p.x, items[j].y - p.y) < gap) parent[find(i)] = find(j);\n }\n const own = cells.get(key(cx, cy));\n if (own) own.push(i);\n else cells.set(key(cx, cy), [i]);\n });\n const groups = new Map<number, number[]>();\n items.forEach((_, i) => {\n const r = find(i);\n const g = groups.get(r);\n if (g) g.push(i);\n else groups.set(r, [i]);\n });\n const out: FanOutput[] = items.map((p) => ({ id: p.id, x: p.x, y: p.y, fanned: false }));\n for (const members of groups.values()) {\n const n = members.length;\n if (n < 2) continue;\n const cx = members.reduce((s, i) => s + items[i].x, 0) / n;\n const cy = members.reduce((s, i) => s + items[i].y, 0) / n;\n const place = (i: number, radius: number, angle: number) => {\n out[i] = { id: items[i].id, x: cx + radius * Math.sin(angle), y: cy - radius * Math.cos(angle), fanned: true };\n };\n if (n <= 6) {\n const radius = gap / (2 * Math.sin(Math.PI / n));\n members.forEach((i, k) => place(i, radius, (2 * Math.PI * k) / n));\n } else {\n let k = 0;\n for (let ring = 1; k < n; ring++) {\n const radius = ring * gap;\n const fit = Math.max(1, Math.floor((2 * Math.PI * radius) / gap));\n const here = Math.min(fit, n - k);\n for (let m = 0; m < here; m++) place(members[k + m], radius, (2 * Math.PI * m) / here);\n k += here;\n }\n }\n }\n return out;\n}\n","import * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport L from \"leaflet\";\nimport { Button as AriaButton } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { geo, type LatLng } from \"../lib/geo\";\nimport { Tooltip } from \"../components/tooltip\";\nimport { fanOut } from \"./fan\";\n\n// Item markers on a map (strata-react issue #181, from strata-360's race map: a marker for every clip at\n// the middle of its stretch of track, the stretch drawn heavier, overlapping markers fanned apart, a card\n// on hover, a click that opens the clip). What is decided here and why:\n//\n// - **Each marker is a real control.** A React Aria `Button` portalled into the DOM node of a Leaflet\n// marker (a `divIcon` whose `html` is that node), so Leaflet keeps it where the map puts it while React\n// owns what it is: named by its label, pressed with a click, Enter or Space, a `Tooltip` on hover and\n// focus. Not Leaflet's popup, which is not a Strata surface and not reachable the same way.\n// - **One tab stop for all of them**, arrows (and Home and End) between them, in the order the app gave:\n// forty markers must not be forty tab stops. The map's own keyboard stays: the markers are a roving\n// group inside it, and the app's list of items beside the map is still the full keyboard path.\n// - **Only what is near the screen is drawn.** Each time the view settles the markers within the view\n// (plus a margin, so a fan is not cut at the edge) are laid out and the rest are not in the DOM, so 500\n// markers cost what the visible ones cost.\n// - **The fan is a pure function of the zoom** (`fanOut`, fan.ts): in world pixels, so panning never moves\n// it and zooming in settles it; a leader line joins each fanned marker to its true place.\n// - **States are shapes as well as colour**: a plain circle, a ringed larger one for selected, a diamond for\n// highlighted by the app (the newest draft's choice). The key names each one that is on the map.\n//\n// Checked: React Aria has no map part; `Button` and the Strata `Tooltip` are used as they are.\n\n/** The words the key uses for each marker state. */\nexport type MarkerKeyWords = { marker?: string; selected?: string; highlighted?: string };\n\n/** An item on the map: a place, or a stretch of a route (drawn heavier, the marker at its middle). */\nexport type MapMarker = {\n /** Stable between renders. */\n id: string;\n /** A place, or a stretch of a route between two distances along it (metres). */\n at: LatLng | { routeId: string; from: number; to: number };\n /** Its name: the button's accessible name and the card's default words. */\n label: string;\n selected?: boolean;\n /** Marked by the app (a diamond): the newest draft's choice, a flagged item. */\n highlighted?: boolean;\n /** Any CSS colour, normally a role; overrides the state's. */\n colour?: string;\n};\n\n/** A marker with where it really is and where it is drawn. */\nexport type Placed = { marker: MapMarker; at: LatLng; shown: LatLng; fanned: boolean };\n\nconst alongCache = new WeakMap<readonly LatLng[], number[]>();\n/** The running distance at each point of a route, kept per route array so a long route is walked once. */\nexport function alongOf(points: readonly LatLng[]): number[] {\n let a = alongCache.get(points);\n if (!a) {\n a = geo.cumulative(points);\n alongCache.set(points, a);\n }\n return a;\n}\n\n/** Where a marker really is: its place, or the middle of its stretch. Null when its route is not on the map. */\nexport function markerPlace(m: MapMarker, routes: readonly { id: string; points: readonly LatLng[] }[]): LatLng | null {\n if (Array.isArray(m.at)) return m.at as LatLng;\n const at = m.at as { routeId: string; from: number; to: number };\n const route = routes.find((r) => r.id === at.routeId);\n return route ? geo.pointAlong(route.points, (at.from + at.to) / 2, alongOf(route.points)) : null;\n}\n\n/** The markers near the view, with the overlapping ones fanned apart for this zoom. */\nexport function placeMarkers(map: L.Map, markers: readonly MapMarker[], routes: readonly { id: string; points: readonly LatLng[] }[]): Placed[] {\n const near = map.getBounds().pad(0.25);\n const zoom = map.getZoom();\n const here: { marker: MapMarker; at: LatLng }[] = [];\n for (const marker of markers) {\n const at = markerPlace(marker, routes);\n if (at && near.contains([at[0], at[1]])) here.push({ marker, at });\n }\n const fanned = fanOut(here.map((h) => ({ id: h.marker.id, ...map.project([h.at[0], h.at[1]], zoom) })));\n return here.map((h, i) => {\n const f = fanned[i];\n const shown = f.fanned ? map.unproject([f.x, f.y], zoom) : null;\n return { marker: h.marker, at: h.at, shown: shown ? ([shown.lat, shown.lng] as LatLng) : h.at, fanned: f.fanned };\n });\n}\n\nconst state = (m: MapMarker) => (m.highlighted ? \"highlighted\" : m.selected ? \"selected\" : \"marker\");\n\ntype PinProps = {\n map: L.Map;\n placed: Placed;\n active: boolean;\n onActivate: (id: string) => void;\n onMove: (id: string, to: \"next\" | \"previous\" | \"first\" | \"last\") => void;\n register: (id: string, el: HTMLElement | null) => void;\n onSelect?: (id: string) => void;\n card?: (m: MapMarker) => React.ReactNode;\n};\n\n/** One marker: a Leaflet marker holding a node that React fills with a labelled button. */\nfunction Pin({ map, placed, active, onActivate, onMove, register, onSelect, card }: PinProps) {\n const { marker, shown } = placed;\n const host = React.useMemo(() => {\n const el = document.createElement(\"div\");\n el.className = \"strata-map-pin\";\n return el;\n }, []);\n const layer = React.useRef<L.Marker | null>(null);\n React.useEffect(() => {\n const m = L.marker([shown[0], shown[1]], { icon: L.divIcon({ className: \"strata-map-marker\", html: host, iconSize: [28, 28], iconAnchor: [14, 14] }), interactive: false, keyboard: false }).addTo(map);\n layer.current = m;\n return () => {\n layer.current = null;\n m.remove();\n };\n // Made once per pin; where it is and how high it sits are updated below.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map, host]);\n React.useEffect(() => {\n layer.current?.setLatLng([shown[0], shown[1]]);\n }, [shown]);\n React.useEffect(() => {\n layer.current?.setZIndexOffset(marker.selected ? 1000 : marker.highlighted ? 500 : 0);\n }, [marker.selected, marker.highlighted]);\n const kind = state(marker);\n const swatch = marker.colour ?? (kind === \"highlighted\" ? \"var(--success)\" : kind === \"selected\" ? \"var(--foreground)\" : \"var(--primary)\");\n return createPortal(\n <Tooltip label={card ? card(marker) : marker.label} side=\"top\">\n <AriaButton\n ref={(el) => register(marker.id, el)}\n aria-label={marker.label}\n aria-pressed={marker.selected ?? false}\n excludeFromTabOrder={!active}\n onFocus={() => onActivate(marker.id)}\n onPress={() => onSelect?.(marker.id)}\n onKeyDown={(e) => {\n const to = e.key === \"ArrowRight\" || e.key === \"ArrowDown\" ? \"next\" : e.key === \"ArrowLeft\" || e.key === \"ArrowUp\" ? \"previous\" : e.key === \"Home\" ? \"first\" : e.key === \"End\" ? \"last\" : null;\n if (!to) return;\n e.preventDefault();\n e.stopPropagation();\n onMove(marker.id, to);\n }}\n className=\"pointer-events-auto grid size-7 cursor-pointer place-items-center rounded-pill outline-offset-1 focus-visible:outline-2 focus-visible:outline-ring\"\n >\n <Shape kind={kind} colour={swatch} />\n </AriaButton>\n </Tooltip>,\n host,\n );\n}\n\n/** The drawn shape of a marker state: a circle, a ringed larger circle, a diamond. Shapes carry the meaning as colour does. */\nfunction Shape({ kind, colour }: { kind: \"marker\" | \"selected\" | \"highlighted\"; colour: string }) {\n return (\n <span\n aria-hidden\n className={cn(\"block border-2 border-background\", kind === \"highlighted\" ? \"size-3.5 rotate-45 rounded-sm\" : \"rounded-pill\", kind === \"selected\" ? \"size-4 ring-2 ring-foreground\" : kind === \"marker\" ? \"size-3.5\" : \"\")}\n style={{ background: colour }}\n />\n );\n}\n\ntype LayerProps = {\n map: L.Map;\n placed: readonly Placed[];\n onSelect?: (id: string) => void;\n card?: (m: MapMarker) => React.ReactNode;\n};\n\n/** The pins for the markers near the view, as one roving group: one tab stop, arrows between them. */\nexport function MarkerLayer({ map, placed, onSelect, card }: LayerProps) {\n const [activeId, setActiveId] = React.useState<string | null>(null);\n const els = React.useRef(new Map<string, HTMLElement>());\n const ids = placed.map((p) => p.marker.id);\n const active = activeId !== null && ids.includes(activeId) ? activeId : (ids[0] ?? null);\n const register = React.useCallback((id: string, el: HTMLElement | null) => {\n if (el) els.current.set(id, el);\n else els.current.delete(id);\n }, []);\n const move = (id: string, to: \"next\" | \"previous\" | \"first\" | \"last\") => {\n const i = ids.indexOf(id);\n const next = to === \"first\" ? 0 : to === \"last\" ? ids.length - 1 : Math.min(ids.length - 1, Math.max(0, i + (to === \"next\" ? 1 : -1)));\n setActiveId(ids[next]);\n els.current.get(ids[next])?.focus();\n };\n return (\n <>\n {placed.map((p) => (\n <Pin key={p.marker.id} map={map} placed={p} active={p.marker.id === active} onActivate={setActiveId} onMove={move} register={register} onSelect={onSelect} card={card} />\n ))}\n </>\n );\n}\n\n/** The key to the marker states that are on the map, each with its shape and its words. */\nexport function MarkerKey({ markers, words }: { markers: readonly MapMarker[]; words?: MarkerKeyWords }) {\n const kinds = ([\"marker\", \"selected\", \"highlighted\"] as const).filter((k) => markers.some((m) => state(m) === k));\n const text = { marker: words?.marker ?? \"Item\", selected: words?.selected ?? \"Selected\", highlighted: words?.highlighted ?? \"Highlighted\" };\n if (!kinds.length) return null;\n return (\n <div className=\"rounded-control border border-border bg-background px-2 py-1.5 type-caption text-foreground\">\n <ul className=\"grid gap-0.5\">\n {kinds.map((k) => (\n <li key={k} className=\"flex items-center gap-2\">\n <span className=\"grid size-4 place-items-center\">\n <Shape kind={k} colour={k === \"highlighted\" ? \"var(--success)\" : k === \"selected\" ? \"var(--foreground)\" : \"var(--primary)\"} />\n </span>\n {text[k]}\n </li>\n ))}\n </ul>\n </div>\n );\n}\n","import * as React from \"react\";\nimport L from \"leaflet\";\nimport { useColorScheme } from \"../components/theme\";\nimport { cn } from \"../lib/utils\";\nimport { format } from \"../lib/format\";\nimport { geo, type LatLng } from \"../lib/geo\";\nimport { installMapStyles } from \"./map-styles\";\nimport { useSharedCursor } from \"../components/cursor\";\nimport { MarkerKey, MarkerLayer, alongOf, placeMarkers, type MapMarker, type MarkerKeyWords } from \"./markers\";\n\n// A themed map of routes with a position that moves along them (strata-react issue #80, from\n// strata-vid's MapPanel and jonathanburnhams.com's activity maps). It is behind its own entry,\n// `strata-react/map`, because Leaflet is heavy and an app that draws no maps should not install it:\n// Leaflet is an optional peer and nothing in the main entry imports it.\n//\n// Leaflet, without react-leaflet (Jonathan's choice, 2026-11-12). react-leaflet binds every layer to\n// a React element, so a position that moves sixty times a second re-renders the route elements\n// beside it; here the map is made once, the routes are one effect that runs only when the routes\n// change, and the position is another that calls `setLatLng` on one marker. A position update\n// touches nothing else: no route is redrawn, none is recreated.\n//\n// What the app supplies, and what the component decides:\n// - Tiles are the app's (`tiles.light`, `tiles.dark`, each with the attribution its provider\n// requires, shown on the map). A dark scheme uses `tiles.dark` when there is one, else the light\n// tiles under a filter (see map-styles.ts); the choice follows the colour scheme.\n// - Colours are roles. A route's colour is any CSS colour (`var(--chart-2)`, `var(--info)`), resolved\n// against the map's own element so SVG strokes, which Leaflet writes as attributes, get a real\n// colour that follows the scheme. Routes default to the chart palette in order.\n// - Colour by value (`values` on a route plus `colourScale`) follows LineChart's rules (§3.8): the\n// colour is a fact of the subject, steps are the app's, and a key names them (`colourScaleLabel`\n// and the step thresholds through `formatValue`) so colour is never the only cue. Runs of one\n// step are drawn as one line, so a long route is a few polylines, not thousands.\n// - One route is the common case: it gets direction chevrons and start and finish marks (a loop is\n// one mark) by default; with several routes those are off unless a route asks.\n// - Fit-to-content happens on first show and when the set of routes changes, not when a route's\n// points are replaced by the same ids, so a person who has zoomed is not thrown back.\n// - Overlay slots, `topEnd` and `bottomStart`, sit where Leaflet puts nothing (it uses the top\n// start for zoom and the bottom end for attribution), so an app's own control or figure never\n// covers a required notice.\n//\n// Keyboard and screen readers. Leaflet's container is a focus stop: arrows pan, + and − zoom. It is\n// named by `label` and described by a text alternative that says what is drawn (each route, its\n// length, whether it is a loop, and how far along the position is), written from the data or given\n// as `summary`. Hovering a route or a mark is a bonus; its facts are in that text. Choosing a route\n// is `onSelect`, and a screen that lets a person choose one lists its routes beside the map (a\n// pointer click on a line has no keyboard equivalent inside Leaflet's SVG, so the list is the path).\n//\n// Map as picture content (issue #161, from strata-vid, where a route inset is composed over footage and\n// must look the same on every frame as in an export drawn on a canvas). Three additions, none of which\n// changes a page map: `zoom` sets the zoom from outside (any number, so an animation is a prop that\n// changes every frame; unset keeps fit-to-routes), `follow=\"centre\"` holds the view on a position at that\n// zoom, and `positions` draws several moving positions, each tied to a route and drawn in its colour.\n// Centred follow pans to a whole-pixel view worked out from the position and zoom alone (`centre`), with\n// no animation: Leaflet's own centred pan truncates each step, so where the view ended up would depend\n// on the path it took; this depends only on the position and zoom, which is what makes frame N the same\n// picture however it was reached. A `reset` would give the same view but empties the tile layer on every\n// call, which flickers at one update per frame.\n// Fractional zoom needs `zoomSnap: 0`, which is set only while `zoom` is controlled, so a page map still\n// snaps to half steps. Each marker is one `L.CircleMarker` kept by id and moved with `setLatLng`.\n//\n// The map as an instrument, not only a picture (strata-react issues #181, #182, #184):\n// - `markers`: items on the route as controls with cards, fanned apart (markers.tsx).\n// - `onViewChange`: the visible bounds and zoom, once when movement settles (debounced `settle` ms), and\n// not for a move the app made through its own props (`zoom`, `view`, `follow`, the first fit), which it\n// already knows about: every move the component makes itself runs inside `silently`, and Leaflet's events\n// are synchronous with animation off, so the flag cannot leak. `reportAppMoves` turns that off.\n// - `view` restores a saved view; the person's own moves go out through `onViewChange`. A reset control\n// in Leaflet's own control group fits the routes again (or sets the zoom, when one is controlled).\n// - `picking` + `onPick`: choose a place. Pointer: a click. Keyboard: arrows move a crosshair (Shift for\n// bigger steps), Enter chooses, Escape asks to cancel; Leaflet's own arrow handling is switched off for\n// the time, since both would move. The result is announced with the nearest route, how far along it and\n// how far off (`geo.snap`). Route lines stop taking clicks while picking, or a pick near the route would\n// select the route instead. A click when not picking does nothing new.\n// - `cursor`: joins a `CursorScope` (cursor.tsx). The scope's unit here is metres along one route; a\n// pointer near the route (within 24 px of it) writes the distance of the nearest point on it, and\n// another member's distance is drawn as a ring on the route. Never drawn back at its own writer.\n//\n// No animation: zoom, fade and inertia are off, because a map is panned all the time and a tile\n// fade makes a screenshot depend on timing (character by frequency, and strata-visual).\n//\n// Checked: React Aria has no map or geographic part. Leaflet's own keyboard handler and focus are\n// kept as they are.\n\n/** A source of map tiles: a URL template the app's provider documents, and the attribution it requires. */\nexport type TileSource = {\n /** `https://tiles.example.com/{z}/{x}/{y}.png`; `{s}` and `{r}` work as in Leaflet. */\n url: string;\n /** What the provider requires shown (HTML allowed: \"© OpenStreetMap contributors\"). */\n attribution: string;\n subdomains?: string;\n minZoom?: number;\n maxZoom?: number;\n};\n\n/** One route on the map. */\nexport type MapRoute = {\n id: string;\n /** Its name, in the text alternative and on hover (\"Wednesday run\"). */\n label: string;\n points: readonly LatLng[];\n /** Any CSS colour, normally a role (`var(--chart-2)`). Default: the chart palette in order. */\n colour?: string;\n /** Line width in pixels. Default 4. */\n weight?: number;\n /** One value per point, coloured by `colourScale` (speed, elevation, heart rate). */\n values?: readonly number[];\n /** Direction chevrons along the line: true for five, or a count. Default on for a single route. */\n arrows?: boolean | number;\n /** Start and finish marks. Default on for a single route. */\n ends?: boolean;\n};\n\n/** One moving position, for a map with more than one (two runners on the same loop). */\nexport type MapPosition = {\n /** Stable between renders: the marker is kept by it and moved, never recreated. */\n id: string;\n /** Where it is now; null hides it. */\n at: LatLng | null;\n /** What it is called in the text alternative (\"Runner A\"). */\n label: string;\n /** The route it travels. Its marker takes that route's colour and the text alternative says how far along it is. */\n routeId?: string;\n /** Any CSS colour, normally a role. Overrides the route's. Default: the route's colour, else the theme's primary. */\n colour?: string;\n};\n\n/** The view the map settled on. */\nexport type MapView = { bounds: [LatLng, LatLng]; zoom: number; center: LatLng };\n\n/** The route nearest a picked place. */\nexport type PickNearest = {\n routeId: string;\n /** The leg of the route (its first point's index) the place is nearest. */\n index: number;\n /** How far the place is from the route, in metres. */\n distanceM: number;\n /** How far along the route the nearest point is, in metres. */\n alongM: number;\n /** The nearest point on the route. */\n position: LatLng;\n};\n\nexport type RouteMapProps = {\n /** Names the map (\"Route of Wednesday's run\"). */\n label: string;\n /** Keep this array stable between renders (state or `useMemo`): the routes are redrawn when it changes, which a moving position must not cause. */\n routes: readonly MapRoute[];\n tiles: { light: TileSource; dark?: TileSource };\n /** Where the moving thing is now. Moved without redrawing any route; null for none. */\n position?: LatLng | null;\n /** What the position is called in the text alternative. Default \"Current position\". */\n positionLabel?: string;\n /** More moving positions, each in its route's colour and named in the text alternative. Moved without redrawing any route; `position` may be used beside them. */\n positions?: readonly MapPosition[];\n /** Which position `follow` tracks: a `positions` id. Default `position`, else the first of `positions` that is shown. */\n followId?: string;\n /** `true` pans only when the position leaves the inner 80% of the view; `\"centre\"` keeps it exactly in the centre on every update, with no animation (a frame is deterministic), at `zoom` when that is set, else the zoom the map has. */\n follow?: boolean | \"centre\";\n /** The zoom level, any number (12, 14.5): it may change every frame without redrawing routes. Unset, the map fits its routes and the person zooms. */\n zoom?: number;\n /** Items on the map: places, or stretches of a route. Keep the array stable between renders. */\n markers?: readonly MapMarker[];\n /** A marker was pressed (click, Enter or Space). */\n onMarkerSelect?: (id: string) => void;\n /** The words shown beside a marker on hover and focus (as `Tooltip`; not interactive). Default its label. */\n renderMarkerCard?: (marker: MapMarker) => React.ReactNode;\n /** The words of the marker key; `false` leaves the key out. */\n markerKey?: MarkerKeyWords | false;\n /** Join the nearest `CursorScope`: a pointer near a route puts its distance along it in every member, and another member's distance shows as a ring on the route. `{ routeId }` picks the route (default the first). */\n cursor?: boolean | { routeId?: string };\n /** The view settled after the person moved or zoomed it: bounds, zoom and centre. Not called for moves the app caused through props. */\n onViewChange?: (view: MapView) => void;\n /** Milliseconds the view must be still before `onViewChange`. Default 250. */\n settle?: number;\n /** Also call `onViewChange` for moves the app caused through props (the first fit, `zoom`, `view`, `follow`). */\n reportAppMoves?: boolean;\n /** A view to show: centre and zoom, as a saved view or the app's own. The person can still move away from it; set it again to go back. Wins over fitting the routes. */\n view?: { center: LatLng; zoom: number };\n /** Choose a place on the map. While set, a click or Enter picks and route lines do not take clicks. */\n picking?: boolean;\n /** A place was chosen, with the nearest route to it when there is one. */\n onPick?: (at: LatLng, info: { nearest: PickNearest | null }) => void;\n /** Escape was pressed while picking: the app turns `picking` off. */\n onPickCancel?: () => void;\n /** The banner for pick mode (\"Click the map to set the point; Escape cancels\"), shown top centre. */\n pickBanner?: React.ReactNode;\n /** The route drawn heavier, with the others lighter. */\n selectedId?: string | null;\n /** A route line was pressed. Give the app's own list of routes the same action for the keyboard. */\n onSelect?: (id: string) => void;\n /** Step colours for routes that have `values`: a step starts at `at` and runs to the next. */\n colourScale?: readonly { at: number; colour: string }[];\n /** What the colours mean, written in the key (\"Speed\"). */\n colourScaleLabel?: string;\n /** Writes a value in the key and the text alternative (\"12 km/h\"). Default the plain number. */\n formatValue?: (value: number) => string;\n /** Replaces the generated text alternative. */\n summary?: string;\n /** Units for lengths in the generated text. Default metric. */\n units?: \"metric\" | \"imperial\";\n /** Wheel zoom. Off by default so the page still scrolls past the map. */\n scrollZoom?: boolean;\n /** An app control or figure in the top end corner (Leaflet leaves it free). */\n topEnd?: React.ReactNode;\n /** An app legend or figure in the bottom start corner, below the colour key when there is one. */\n bottomStart?: React.ReactNode;\n /** Layout only. The map is 16:9 and at least 16rem tall unless a height is given. */\n className?: string;\n};\n\n/** The smallest and largest value, without spreading the array (a long recording passes the engine's argument limit). */\nfunction extent(values: readonly number[]): [number, number] {\n let lo = Infinity;\n let hi = -Infinity;\n for (const v of values) {\n if (v < lo) lo = v;\n if (v > hi) hi = v;\n }\n return [lo, hi];\n}\n\nconst tuple = (p: LatLng): L.LatLngTuple => [p[0], p[1]];\nconst plain = (v: number) => String(v);\n\n/** `value`, sampled once a second (a throttle, not a debounce: a value that changes every frame still comes through): for text a screen reader may read, which must not change sixty times a second. */\nfunction useSlow<T>(value: T, ms = 1000): T {\n const [slow, setSlow] = React.useState(value);\n const latest = React.useRef(value);\n latest.current = value;\n React.useEffect(() => {\n const id = window.setInterval(() => setSlow(latest.current), ms);\n return () => window.clearInterval(id);\n }, [ms]);\n return slow;\n}\n\n/** How many moves of the map the component itself is making right now (see `onViewChange`). */\nconst quiet = new WeakMap<L.Map, number>();\n/** Run a move the component makes itself, so `onViewChange` does not report it. Leaflet's events are synchronous with animation off. */\nfunction silently<T>(map: L.Map, fn: () => T): T {\n quiet.set(map, (quiet.get(map) ?? 0) + 1);\n try {\n return fn();\n } finally {\n quiet.set(map, (quiet.get(map) ?? 1) - 1);\n }\n}\n\n/** The route nearest a place, by distance from it to the route (not to a vertex). */\nfunction nearestRoute(routes: readonly MapRoute[], at: LatLng): PickNearest | null {\n let best: PickNearest | null = null;\n for (const r of routes) {\n const s = geo.snap(r.points, at, alongOf(r.points));\n if (s && (!best || s.offset < best.distanceM)) best = { routeId: r.id, index: s.index, distanceM: s.offset, alongM: s.metres, position: s.position };\n }\n return best;\n}\n\nconst RESET_ICON = '<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.75\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M2 6V2h4M10 2h4v4M14 10v4h-4M6 14H2v-4\"/></svg>';\nconst CROSS_ICON = '<svg width=\"32\" height=\"32\" viewBox=\"0 0 32 32\" aria-hidden=\"true\" fill=\"none\" stroke-linecap=\"round\"><path d=\"M16 4v24M4 16h24\" stroke=\"var(--background)\" stroke-width=\"5\"/><path d=\"M16 4v24M4 16h24\" stroke=\"var(--foreground)\" stroke-width=\"2\"/></svg>';\n\n/** Leaflet's control group gets a reset: fit the routes again. A link with a button role, as Leaflet's own zoom buttons are. */\nfunction resetControl(onReset: () => void): L.Control {\n const control = new L.Control({ position: \"topleft\" });\n control.onAdd = () => {\n const bar = L.DomUtil.create(\"div\", \"leaflet-bar leaflet-control\");\n const a = L.DomUtil.create(\"a\", \"strata-map-reset\", bar);\n a.href = \"#\";\n a.setAttribute(\"role\", \"button\");\n a.setAttribute(\"aria-label\", \"Reset view\");\n a.title = \"Reset view\";\n a.innerHTML = RESET_ICON;\n L.DomEvent.disableClickPropagation(bar);\n L.DomEvent.on(a, \"click\", (e) => {\n L.DomEvent.preventDefault(e);\n onReset();\n });\n L.DomEvent.on(a, \"keydown\", (e) => {\n if ((e as KeyboardEvent).key === \" \") {\n L.DomEvent.preventDefault(e);\n onReset();\n }\n });\n return bar;\n };\n return control;\n}\n\n/** Put the routes in view (or, with a zoom set, centre the routes at it). */\nfunction showRoutes(map: L.Map, routes: readonly MapRoute[], zoom: number | undefined) {\n const box = geo.bounds(routes.flatMap((r) => r.points));\n if (!box) return false;\n if (zoom !== undefined) map.setView([(box[0][0] + box[1][0]) / 2, (box[0][1] + box[1][1]) / 2], zoom, { animate: false });\n else map.fitBounds([tuple(box[0]), tuple(box[1])], { padding: [24, 24], animate: false, maxZoom: 17 });\n return true;\n}\n\nconst SINGLE = \"\\u0000position\";\nconst PALETTE = [1, 2, 3, 4, 5].map((n) => `var(--chart-${n})`);\n\n/**\n * Put `target` in the exact middle of the view at zoom `z`, with no animation and without throwing the\n * loaded tiles away. A zoom change goes through `setView` (Leaflet redraws its tiles then anyway). The\n * position is then set by panning to a whole-pixel top-left worked out from the target and the zoom\n * alone, so where the view ends up does not depend on the path taken (Leaflet's own centred pan\n * truncates each step and drifts); a `reset` would be exact too but empties the tile layer on every\n * call, which flickers when the position changes every frame.\n */\nfunction centre(map: L.Map, target: LatLng, z: number) {\n silently(map, () => {\n if (map.getZoom() !== z) map.setView(tuple(target), z, { animate: false });\n const want = map.project(tuple(target), z).subtract(map.getSize().divideBy(2)).round();\n const have = map.getPixelBounds().min!.round();\n const move = want.subtract(have);\n if (move.x || move.y) map.panBy(move, { animate: false, noMoveStart: true });\n });\n}\n\n/** The colour a CSS value (a `var()`, a role) resolves to on `el`, so an SVG attribute gets a real one. Falls back to the value itself. */\nfunction resolveColour(el: HTMLElement, value: string): string {\n const probe = document.createElement(\"span\");\n probe.style.color = value;\n el.appendChild(probe);\n const resolved = getComputedStyle(probe).color;\n probe.remove();\n return resolved || value;\n}\n\n/** Indices where a run of one step ends, so a coloured route is a few polylines. */\nfunction stepRuns(points: readonly LatLng[], values: readonly number[], stepOf: (v: number) => number) {\n const runs: { from: number; to: number; step: number }[] = [];\n for (let i = 1; i < points.length; i++) {\n const step = stepOf(((values[i - 1] ?? 0) + (values[i] ?? 0)) / 2);\n const last = runs[runs.length - 1];\n if (last && last.step === step) last.to = i;\n else runs.push({ from: i - 1, to: i, step });\n }\n return runs;\n}\n\nconst arrowHtml = (bearing: number, colour: string, halo: string) =>\n `<svg width=\"26\" height=\"26\" viewBox=\"0 0 26 26\" aria-hidden=\"true\" style=\"transform: rotate(${bearing.toFixed(0)}deg)\">` +\n `<path d=\"M6 17 L13 9 L20 17\" fill=\"none\" stroke=\"${halo}\" stroke-width=\"7\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>` +\n `<path d=\"M6 17 L13 9 L20 17\" fill=\"none\" stroke=\"${colour}\" stroke-width=\"3.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`;\n\n/** A map of one or more routes with a position that moves along them, on tiles the app supplies, themed from its roles. Leaflet, behind `strata-react/map`. */\nexport function RouteMap({\n label,\n routes,\n tiles,\n position = null,\n positionLabel = \"Current position\",\n positions,\n followId,\n follow = false,\n zoom,\n markers,\n onMarkerSelect,\n renderMarkerCard,\n markerKey,\n cursor: cursorProp,\n onViewChange,\n settle = 250,\n reportAppMoves = false,\n view,\n picking = false,\n onPick,\n onPickCancel,\n pickBanner,\n selectedId = null,\n onSelect,\n colourScale,\n colourScaleLabel,\n formatValue = plain,\n summary,\n units = \"metric\",\n scrollZoom = false,\n topEnd,\n bottomStart,\n className,\n}: RouteMapProps) {\n const { scheme } = useColorScheme();\n const host = React.useRef<HTMLDivElement>(null);\n const root = React.useRef<HTMLDivElement>(null);\n const [map, setMap] = React.useState<L.Map | null>(null);\n const summaryId = React.useId();\n const latest = React.useRef({ onSelect, onViewChange, reportAppMoves, settle, picking, onPick, onPickCancel, routes, units, view, zoom });\n latest.current = { onSelect, onViewChange, reportAppMoves, settle, picking, onPick, onPickCancel, routes, units, view, zoom };\n const [announced, setAnnounced] = React.useState(\"\");\n // True once the map has a view (the first fit has happened): before that Leaflet cannot say what is near.\n const [ready, setReady] = React.useState(false);\n const selectable = Boolean(onSelect);\n // One marker per position, by id, with the style last applied so a moving marker is not restyled every frame.\n const posMarkers = React.useRef(new Map<string, { marker: L.CircleMarker; style: string }>());\n\n const darkTiles = scheme === \"dark\" ? tiles.dark : undefined;\n const source = darkTiles ?? tiles.light;\n const treated = scheme === \"dark\" && !tiles.dark;\n const stops = React.useMemo(() => (colourScale ? [...colourScale].sort((a, b) => a.at - b.at) : []), [colourScale]);\n\n // The map, made once. Its container is Leaflet's; React owns only the wrapper around it.\n React.useEffect(() => {\n installMapStyles();\n const el = host.current;\n if (!el) return;\n const m = L.map(el, { scrollWheelZoom: scrollZoom, fadeAnimation: false, zoomAnimation: false, markerZoomAnimation: false, inertia: false, attributionControl: false, zoomSnap: 0.5 });\n L.control.attribution({ prefix: '<a href=\"https://leafletjs.com\">Leaflet</a>' }).addTo(m);\n el.setAttribute(\"aria-roledescription\", \"map\");\n // Leaflet follows the window, not its container; a pane that resizes (a Workspace split) needs the same.\n const ro = new ResizeObserver(() => m.invalidateSize({ animate: false }));\n ro.observe(el);\n setMap(m);\n return () => {\n ro.disconnect();\n posMarkers.current.clear();\n m.remove();\n setMap(null);\n setReady(false);\n };\n // The wheel setting is applied below, so the map is not rebuilt for it.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n React.useEffect(() => {\n if (!map) return;\n if (scrollZoom) map.scrollWheelZoom.enable();\n else map.scrollWheelZoom.disable();\n }, [map, scrollZoom]);\n\n // A zoom set from outside is any number; Leaflet snaps to `zoomSnap`, so it is 0 while zoom is controlled.\n const zoomed = zoom !== undefined;\n React.useEffect(() => {\n if (map) map.options.zoomSnap = zoomed ? 0 : 0.5;\n }, [map, zoomed]);\n\n // Every position on the map, the single `position` first: what is spoken, drawn and followed.\n const all = React.useMemo<MapPosition[]>(() => [...(position ? [{ id: SINGLE, at: position, label: positionLabel }] : []), ...(positions ?? [])], [position, positionLabel, positions]);\n\n // The text alternative: written from the data unless the app gives one. The position is in it, but\n // it is not a live region: a position that moves many times a second must not be announced.\n const spoken = useSlow(all);\n const text = React.useMemo(() => {\n if (summary) return summary;\n if (!routes.length) return \"No routes to show.\";\n const parts = routes.map((r) => {\n const along = geo.cumulative(r.points);\n const total = along[along.length - 1] ?? 0;\n const ends = geo.ends(r.points);\n const shape = ends?.loop ? \", a loop\" : \"\";\n let here = \"\";\n // A position tied to another route is not on this one; one tied to no route is described along each.\n for (const p of spoken) {\n if (!p.at || !r.points.length || (p.routeId !== undefined && p.routeId !== r.id && routes.some((o) => o.id === p.routeId))) continue;\n here += ` ${p.label}: ${format.distance(along[geo.nearest(r.points, p.at)] ?? 0, units)} along.`;\n }\n let range = \"\";\n if (stops.length && r.values?.length) range = ` ${colourScaleLabel ?? \"Value\"} from ${formatValue(extent(r.values)[0])} to ${formatValue(extent(r.values)[1])}.`;\n return `${r.label}: ${format.distance(total, units)}${shape}.${range}${here}`;\n });\n const items = markers?.length ? ` ${markers.length === 1 ? \"One marker\" : `${markers.length} markers`}${markers.some((m) => m.selected) ? `, selected: ${markers.filter((m) => m.selected).map((m) => m.label).join(\", \")}` : \"\"}.` : \"\";\n return `Map with ${routes.length === 1 ? \"one route\" : `${routes.length} routes`}. ${parts.join(\" \")}${items}`;\n }, [summary, routes, spoken, units, stops.length, colourScaleLabel, formatValue, markers]);\n\n React.useEffect(() => {\n if (!map) return;\n const c = map.getContainer();\n c.setAttribute(\"aria-label\", label);\n c.setAttribute(\"aria-describedby\", summaryId);\n }, [map, label, summaryId]);\n\n // Tiles: the light set, or the dark one in the dark scheme.\n React.useEffect(() => {\n if (!map) return;\n const layer = L.tileLayer(source.url, { attribution: source.attribution, subdomains: source.subdomains ?? \"abc\", minZoom: source.minZoom, maxZoom: source.maxZoom ?? 19, keepBuffer: 1 });\n layer.addTo(map);\n return () => void layer.remove();\n }, [map, source.url, source.attribution, source.subdomains, source.minZoom, source.maxZoom]);\n\n // The routes: redrawn when the routes, the scheme (colours resolve differently), the selection or\n // the scale change, and never for a position update.\n React.useEffect(() => {\n if (!map) return;\n const group = L.featureGroup().addTo(map);\n const el = map.getContainer();\n const halo = resolveColour(el, \"var(--background)\");\n const single = routes.length === 1;\n const stepOf = (v: number) => {\n let at = 0;\n stops.forEach((s, i) => {\n if (s.at <= v) at = i;\n });\n return at;\n };\n routes.forEach((route, index) => {\n if (route.points.length < 2) return;\n const base = resolveColour(el, route.colour ?? PALETTE[index % PALETTE.length]);\n const selected = route.id === selectedId;\n const dim = selectedId !== null && !selected;\n const weight = (route.weight ?? 4) + (selected ? 2 : 0);\n const style = { weight, opacity: dim ? 0.55 : 1, lineCap: \"round\" as const, lineJoin: \"round\" as const, interactive: selectable && !picking, bubblingMouseEvents: false };\n const lines: L.Polyline[] = [];\n if (stops.length && route.values?.length) {\n for (const run of stepRuns(route.points, route.values, stepOf)) {\n lines.push(L.polyline(route.points.slice(run.from, run.to + 1).map(tuple), { ...style, color: resolveColour(el, stops[run.step].colour) }));\n }\n } else {\n lines.push(L.polyline(route.points.map(tuple), { ...style, color: base }));\n }\n for (const line of lines) {\n line.bindTooltip(route.label, { sticky: true });\n line.on(\"click\", () => latest.current.onSelect?.(route.id));\n line.addTo(group);\n }\n const chevrons = route.arrows === undefined ? (single ? 5 : 0) : route.arrows === true ? 5 : route.arrows === false ? 0 : route.arrows;\n if (chevrons > 0) {\n for (const a of geo.arrows(route.points, chevrons)) {\n L.marker(tuple(a.position), {\n interactive: false,\n keyboard: false,\n icon: L.divIcon({ className: \"strata-map-arrow\", iconSize: [26, 26], iconAnchor: [13, 13], html: arrowHtml(a.bearing, base, halo) }),\n }).addTo(group);\n }\n }\n if (route.ends ?? single) {\n const ends = geo.ends(route.points);\n if (ends) {\n const success = resolveColour(el, \"var(--success)\");\n const danger = resolveColour(el, \"var(--danger)\");\n const mark = (at: LatLng, text: string, options: L.CircleMarkerOptions) => L.circleMarker(tuple(at), { radius: 7, interactive: true, bubblingMouseEvents: false, ...options }).bindTooltip(text).addTo(group);\n // Shapes carry the meaning as well as colour: a filled start, a ringed finish, one of each for a loop.\n if (ends.loop) mark(ends.start, `${route.label}: start and finish`, { color: danger, weight: 3, fillColor: success, fillOpacity: 1 });\n else {\n mark(ends.finish, `${route.label}: finish`, { color: danger, weight: 3, fillColor: halo, fillOpacity: 1 });\n mark(ends.start, `${route.label}: start`, { color: halo, weight: 2, fillColor: success, fillOpacity: 1 });\n }\n }\n }\n });\n // Redrawn routes are new layers: keep the positions above them.\n for (const { marker } of posMarkers.current.values()) marker.bringToFront();\n return () => void group.remove();\n }, [map, routes, scheme, selectedId, stops, selectable, picking]);\n\n // The position a followed view is held on: read by the fit (a map shown for the first time starts\n // centred on it) and by the position effect.\n const target = React.useMemo(() => {\n if (!follow) return null;\n const shown = all.filter((p) => p.at);\n return (followId ? shown.find((p) => p.id === followId) : shown[0])?.at ?? null;\n }, [all, follow, followId]);\n const latestView = React.useRef({ target, zoom, centred: follow === \"centre\" });\n latestView.current = { target, zoom, centred: follow === \"centre\" };\n\n // Fit to the routes when the map first has a size and whenever the set of routes changes. With a\n // zoom set there is nothing to fit: the view is placed at that zoom, on the followed position when\n // the map is centred on one, else on the middle of the routes.\n const routeKey = routes.map((r) => r.id).join(\"\\n\");\n const fitted = React.useRef<string | null>(null);\n React.useEffect(() => {\n if (!map) return;\n const fit = () => {\n const size = map.getSize();\n if (fitted.current === routeKey || size.x === 0 || size.y === 0) return;\n if (!geo.bounds(routes.flatMap((r) => r.points)) && !latest.current.view) return;\n fitted.current = routeKey;\n const v = latestView.current;\n setReady(true);\n // A given view wins, then a set zoom (on the followed position, or the routes' middle), then the routes.\n silently(map, () => {\n if (latest.current.view) map.setView(tuple(latest.current.view.center), latest.current.view.zoom, { animate: false });\n else if (v.zoom !== undefined && v.centred && v.target) map.setView(tuple(v.target), v.zoom, { animate: false });\n else showRoutes(map, latest.current.routes, v.zoom);\n });\n };\n fit();\n map.on(\"resize\", fit);\n return () => void map.off(\"resize\", fit);\n // `routes` is read when the key says the set changed; a new array of the same ids does not refit.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map, routeKey]);\n\n // A zoom that changes after the first view (an animation) moves the zoom about the view's centre.\n React.useEffect(() => {\n if (map && zoom !== undefined && fitted.current !== null && map.getZoom() !== zoom) silently(map, () => map.setZoom(zoom, { animate: false }));\n }, [map, zoom]);\n\n // The positions: one marker each, kept by id and moved with `setLatLng`. No route is touched.\n React.useEffect(() => {\n if (!map) return;\n const el = map.getContainer();\n const live = posMarkers.current;\n const seen = new Set<string>();\n for (const p of all) {\n if (!p.at) continue;\n seen.add(p.id);\n let entry = live.get(p.id);\n if (!entry) {\n entry = { marker: L.circleMarker(tuple(p.at), { radius: 8, weight: 3, fillOpacity: 1, interactive: false }).addTo(map), style: \"\" };\n live.set(p.id, entry);\n } else entry.marker.setLatLng(tuple(p.at));\n const index = routes.findIndex((r) => r.id === p.routeId);\n const spec = p.colour ?? (index >= 0 ? (routes[index].colour ?? PALETTE[index % PALETTE.length]) : \"var(--primary)\");\n const style = `${scheme}|${spec}`;\n if (entry.style !== style) {\n entry.style = style;\n entry.marker.setStyle({ color: resolveColour(el, \"var(--background)\"), fillColor: resolveColour(el, spec) });\n }\n }\n for (const [id, entry] of live) {\n if (seen.has(id)) continue;\n entry.marker.remove();\n live.delete(id);\n }\n if (!target) return;\n if (follow === \"centre\") {\n // Before the first fit with no zoom set there is no zoom to hold; the fit places the view.\n const z = zoom ?? (fitted.current === null ? undefined : map.getZoom());\n if (z !== undefined) centre(map, target, z);\n } else if (!map.getBounds().pad(-0.2).contains(tuple(target))) silently(map, () => map.panTo(tuple(target), { animate: false }));\n }, [map, all, routes, scheme, follow, target, zoom]);\n\n // The reset control: fit the routes again, as the person's own move (so it is reported).\n React.useEffect(() => {\n if (!map) return;\n const control = resetControl(() => {\n const view = latest.current.view;\n if (view) map.setView(tuple(view.center), view.zoom, { animate: false });\n else showRoutes(map, latest.current.routes, latest.current.zoom);\n });\n control.addTo(map);\n return () => void control.remove();\n }, [map]);\n\n // The view, reported once it settles: the person's moves, not the app's own (unless asked).\n React.useEffect(() => {\n if (!map) return;\n let timer: number | undefined;\n const send = () => {\n timer = undefined;\n const b = map.getBounds();\n const c = map.getCenter();\n latest.current.onViewChange?.({ bounds: [[b.getSouth(), b.getWest()], [b.getNorth(), b.getEast()]], zoom: map.getZoom(), center: [c.lat, c.lng] });\n };\n const moved = () => {\n if (!latest.current.onViewChange) return;\n if (!latest.current.reportAppMoves && (quiet.get(map) ?? 0) > 0) return;\n window.clearTimeout(timer);\n timer = window.setTimeout(send, latest.current.settle);\n };\n map.on(\"moveend zoomend\", moved);\n // The first fit ran before this listener was there: with `reportAppMoves`, it is reported too.\n if (fitted.current !== null && latest.current.reportAppMoves) moved();\n return () => {\n map.off(\"moveend zoomend\", moved);\n window.clearTimeout(timer);\n };\n }, [map]);\n\n // A view the app sets (a saved one): the map goes there when it changes, silently.\n const [viewLat, viewLng, viewZoom] = view ? [view.center[0], view.center[1], view.zoom] : [null, null, null];\n React.useEffect(() => {\n if (!map || viewLat === null || viewLng === null || viewZoom === null || fitted.current === null) return;\n const c = map.getCenter();\n if (map.getZoom() === viewZoom && Math.abs(c.lat - viewLat) < 1e-7 && Math.abs(c.lng - viewLng) < 1e-7) return;\n silently(map, () => map.setView([viewLat, viewLng], viewZoom, { animate: false }));\n }, [map, viewLat, viewLng, viewZoom]);\n\n // The shared cursor: metres along one route.\n const shared = useSharedCursor();\n const cursorOn = Boolean(cursorProp) && shared !== null;\n const cursorRouteId = typeof cursorProp === \"object\" && cursorProp.routeId ? cursorProp.routeId : routes[0]?.id;\n const cursorRoute = routes.find((r) => r.id === cursorRouteId) ?? null;\n const setPointer = shared?.setPointer;\n React.useEffect(() => {\n if (!map || !cursorOn || !cursorRoute || !setPointer) return;\n const along = alongOf(cursorRoute.points);\n const onMove = (e: L.LeafletMouseEvent) => {\n if (latest.current.picking) return;\n const snap = geo.snap(cursorRoute.points, [e.latlng.lat, e.latlng.lng], along);\n if (!snap) return;\n const apart = map.latLngToContainerPoint(e.latlng).distanceTo(map.latLngToContainerPoint(tuple(snap.position)));\n setPointer(apart <= 24 ? snap.metres : null);\n };\n const onOut = () => setPointer(null);\n map.on(\"mousemove\", onMove);\n map.on(\"mouseout\", onOut);\n return () => {\n map.off(\"mousemove\", onMove);\n map.off(\"mouseout\", onOut);\n setPointer(null);\n };\n }, [map, cursorOn, cursorRoute, setPointer]);\n const otherAlong = cursorOn ? (shared?.other ?? null) : null;\n const ring = React.useRef<L.CircleMarker | null>(null);\n React.useEffect(() => {\n if (!map) return;\n const at = otherAlong !== null && cursorRoute ? geo.pointAlong(cursorRoute.points, otherAlong, alongOf(cursorRoute.points)) : null;\n if (!at) {\n ring.current?.remove();\n ring.current = null;\n return;\n }\n if (!ring.current) {\n const el = map.getContainer();\n ring.current = L.circleMarker(tuple(at), { radius: 9, weight: 3, fillOpacity: 0, interactive: false, color: resolveColour(el, \"var(--foreground)\") }).addTo(map);\n } else ring.current.setLatLng(tuple(at));\n }, [map, otherAlong, cursorRoute]);\n React.useEffect(() => () => void (ring.current = null), [map]);\n\n // Item markers: those near the view, laid out again each time it settles.\n const [tick, setTick] = React.useState(0);\n React.useEffect(() => {\n if (!map || !markers?.length) return;\n const again = () => setTick((t) => t + 1);\n map.on(\"moveend zoomend resize\", again);\n return () => void map.off(\"moveend zoomend resize\", again);\n }, [map, markers?.length]);\n const placed = React.useMemo(() => (map && ready && markers?.length ? placeMarkers(map, markers, routes) : []), [map, ready, markers, routes, tick]);\n // A stretch is its route's part drawn heavier, and a fanned marker has a leader line back to its true place.\n React.useEffect(() => {\n if (!map || !markers?.length) return;\n const group = L.featureGroup().addTo(map);\n const el = map.getContainer();\n for (const m of markers) {\n if (Array.isArray(m.at)) continue;\n const at = m.at as { routeId: string; from: number; to: number };\n const index = routes.findIndex((r) => r.id === at.routeId);\n if (index < 0) continue;\n const route = routes[index];\n const part = geo.slice(route.points, at.from, at.to, alongOf(route.points));\n if (part.length < 2) continue;\n const colour = m.colour ?? (m.highlighted ? \"var(--success)\" : m.selected ? \"var(--foreground)\" : (route.colour ?? PALETTE[index % PALETTE.length]));\n L.polyline(part.map(tuple), { color: resolveColour(el, colour), weight: (route.weight ?? 4) + (m.selected ? 5 : 3), opacity: m.selected ? 1 : 0.8, lineCap: \"round\", interactive: false }).addTo(group);\n }\n for (const p of placed) if (p.fanned) L.polyline([tuple(p.at), tuple(p.shown)], { color: resolveColour(el, \"var(--muted-foreground)\"), weight: 1, dashArray: \"2 3\", interactive: false }).addTo(group);\n for (const { marker } of posMarkers.current.values()) marker.bringToFront();\n return () => void group.remove();\n }, [map, markers, routes, placed, scheme]);\n\n // Choosing a place.\n React.useEffect(() => {\n if (!map || !picking) return;\n const el = map.getContainer();\n el.classList.add(\"strata-map-picking\");\n map.keyboard.disable();\n setAnnounced(\"Choose a place on the map. Arrow keys move the crosshair, Shift for bigger steps, Enter chooses, Escape cancels.\");\n let cross: L.Marker | null = null;\n const showCross = (at: L.LatLng) => {\n if (!cross) cross = L.marker(at, { interactive: false, keyboard: false, icon: L.divIcon({ className: \"strata-map-crosshair\", html: CROSS_ICON, iconSize: [32, 32], iconAnchor: [16, 16] }) }).addTo(map);\n else cross.setLatLng(at);\n };\n const choose = (ll: L.LatLng) => {\n const at: LatLng = [ll.lat, ll.lng];\n const nearest = nearestRoute(latest.current.routes, at);\n const route = nearest ? latest.current.routes.find((r) => r.id === nearest.routeId) : undefined;\n setAnnounced(`Picked ${at[0].toFixed(5)}, ${at[1].toFixed(5)}.${nearest && route ? ` Nearest: ${route.label}, ${format.distance(nearest.alongM, latest.current.units)} along, ${format.distance(nearest.distanceM, latest.current.units)} from the route.` : \"\"}`);\n latest.current.onPick?.(at, { nearest });\n };\n const onClick = (e: L.LeafletMouseEvent) => {\n cross?.remove();\n cross = null;\n choose(e.latlng);\n };\n const onKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n e.preventDefault();\n e.stopPropagation();\n latest.current.onPickCancel?.();\n return;\n }\n if (e.key === \"Enter\") {\n e.preventDefault();\n e.stopPropagation();\n choose(cross ? cross.getLatLng() : map.getCenter());\n return;\n }\n const step = e.shiftKey ? 50 : 10;\n const d = ({ ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] } as Record<string, [number, number]>)[e.key];\n if (!d) return;\n e.preventDefault();\n e.stopPropagation();\n const from = map.latLngToContainerPoint(cross ? cross.getLatLng() : map.getCenter());\n let to = from.add(d);\n const size = map.getSize();\n // Past the edge, the map moves and the crosshair stays at the edge.\n const inside = L.point(Math.min(Math.max(to.x, 16), size.x - 16), Math.min(Math.max(to.y, 16), size.y - 16));\n if (!inside.equals(to)) {\n map.panBy(to.subtract(inside), { animate: false });\n to = inside;\n }\n showCross(map.containerPointToLatLng(to));\n };\n map.on(\"click\", onClick);\n el.addEventListener(\"keydown\", onKey);\n return () => {\n map.off(\"click\", onClick);\n el.removeEventListener(\"keydown\", onKey);\n cross?.remove();\n el.classList.remove(\"strata-map-picking\");\n map.keyboard.enable();\n };\n }, [map, picking]);\n\n return (\n <div ref={root} data-dark-treatment={treated ? \"\" : undefined} className={cn(\"strata-map relative isolate aspect-video min-h-64 overflow-hidden rounded-surface border border-border\", className)}>\n <div ref={host} className=\"size-full\" />\n <p id={summaryId} className=\"sr-only\">\n {text}\n </p>\n <p role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {announced}\n </p>\n {map && placed.length > 0 && <MarkerLayer map={map} placed={placed} onSelect={onMarkerSelect} card={renderMarkerCard} />}\n {topEnd && <div className=\"absolute top-2 right-2 z-1000\">{topEnd}</div>}\n {picking && pickBanner && <div className=\"absolute top-2 left-1/2 z-1000 max-w-[60%] -translate-x-1/2\">{pickBanner}</div>}\n {(stops.length > 0 || bottomStart || (markers?.length && markerKey !== false)) && (\n <div className=\"absolute bottom-6 left-2 z-1000 grid max-w-[60%] gap-2\">\n {stops.length > 0 && <ColourKey stops={stops} label={colourScaleLabel} formatValue={formatValue} />}\n {markers && markers.length > 0 && markerKey !== false && <MarkerKey markers={markers} words={markerKey} />}\n {bottomStart}\n </div>\n )}\n </div>\n );\n}\n\n/** The key to a colour scale: its name, then each step with where it starts, so colour is never the only cue. */\nfunction ColourKey({ stops, label, formatValue }: { stops: readonly { at: number; colour: string }[]; label?: string; formatValue: (v: number) => string }) {\n return (\n <div className=\"rounded-control border border-border bg-background px-2 py-1.5 type-caption text-foreground\">\n {label && <p className=\"font-medium\">{label}</p>}\n <ul className=\"grid gap-0.5\">\n {stops.map((s) => (\n <li key={s.at} className=\"flex items-center gap-2 tabular-nums\">\n <svg width=\"20\" height=\"4\" aria-hidden>\n <line x1=\"0\" x2=\"20\" y1=\"2\" y2=\"2\" stroke={s.colour} strokeWidth={4} strokeLinecap=\"round\" />\n </svg>\n <span>{`From ${formatValue(s.at)}`}</span>\n </li>\n ))}\n </ul>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;AASA,IAAM,SAAS;;;;;;;;;;;;;;;;;;;AAoBf,IAAI,YAAY;;AAGhB,SAAgB,mBAAmB;CACjC,IAAI,aAAa,OAAO,aAAa,aAAa;CAClD,YAAY;CACZ,MAAM,KAAK,SAAS,cAAc,OAAO;CACzC,GAAG,aAAa,mBAAmB,EAAE;CACrC,GAAG,cAAc,aAAa;CAC9B,SAAS,KAAK,YAAY,EAAE;AAC9B;;;ACrBA,SAAgB,OAAO,OAA4B,MAAM,IAAiB;CACxE,MAAM,SAAS,MAAM,KAAK,GAAG,MAAM,CAAC;CACpC,MAAM,QAAQ,MAAuB,OAAO,OAAO,IAAI,IAAK,OAAO,KAAK,KAAK,OAAO,EAAE;CAEtF,MAAM,wBAAQ,IAAI,IAAsB;CACxC,MAAM,OAAO,IAAY,OAAe,GAAG,GAAG,GAAG;CACjD,MAAM,SAAS,GAAG,MAAM;EACtB,MAAM,CAAC,IAAI,MAAM,CAAC,KAAK,MAAM,EAAE,IAAI,GAAG,GAAG,KAAK,MAAM,EAAE,IAAI,GAAG,CAAC;EAC9D,KAAK,IAAI,KAAK,IAAI,MAAM,GAAG,MACzB,KAAK,IAAI,KAAK,IAAI,MAAM,GAAG,MACzB,KAAK,MAAM,KAAK,MAAM,IAAI,IAAI,KAAK,IAAI,KAAK,EAAE,C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vC;GALK,GAAA,EAAE,EAKP,CACL;EACC,CAAA,CACD;;AAET"}
@@ -134,6 +134,15 @@ async function capture(browser, shot, options) {
134
134
  async function settle(page) {
135
135
  await page.waitForLoadState("networkidle", { timeout: 3e3 }).catch(() => void 0);
136
136
  await page.evaluate(() => document.fonts.ready.then(() => void 0));
137
+ await page.waitForFunction(() => [...document.querySelectorAll("video")].every((v) => v.readyState >= 2 || v.error !== null), void 0, { timeout: 5e3 }).catch(() => void 0);
138
+ await page.evaluate(() => Promise.all([...document.querySelectorAll("video")].filter((v) => v.readyState >= 2 && !v.error && "requestVideoFrameCallback" in v).map((v) => new Promise((done) => {
139
+ const stop = window.setTimeout(done, 2e3);
140
+ v.requestVideoFrameCallback(() => {
141
+ window.clearTimeout(stop);
142
+ done();
143
+ });
144
+ v.currentTime = v.currentTime;
145
+ })))).catch(() => void 0);
137
146
  await page.waitForTimeout(250);
138
147
  }
139
148
  async function platformFonts(page) {
@@ -749,4 +758,4 @@ function formatReport(report) {
749
758
  }
750
759
  export { capture as _, defaultThemes as a, viewports as c, MAX_DIFF_PIXELS as d, THRESHOLD as f, encode as g, decode as h, runVisual as i, serveStatic as l, compare as m, formatReport as n, routeShots as o, boxBlur as p, pinWarnings as r, storybookShots as s, defineVisualConfig as t, BLUR as u, resolveShotUrl as v, toFetchRequest as y };
751
760
 
752
- //# sourceMappingURL=run-CKlcLpdN.js.map
761
+ //# sourceMappingURL=run-BqZGKhW9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-BqZGKhW9.js","names":[],"sources":["../src/visual/capture.ts","../src/visual/compare.ts","../src/visual/serve.ts","../src/visual/types.ts","../src/visual/targets.ts","../src/visual/run.ts"],"sourcesContent":["// Taking one shot. Everything here is about determinism: a fresh browser context per shot so\n// shots cannot affect each other, reduced motion and frozen animations so the settled state is\n// what is captured, fonts awaited, the theme set both as the colour scheme and as the class the\n// app reads, the clock optionally frozen, and, for routes, every request the page makes answered\n// by MSW handlers in Node, so the screenshot depends on nothing outside the suite.\nimport type { Browser, BrowserContext, Page, Request as PlaywrightRequest, Route as PlaywrightRoute } from \"playwright\";\nimport type { RequestHandler } from \"msw\";\nimport type { Shot, VisualConfig } from \"./types\";\n\n// Where ThemeProvider and colorSchemeScript() keep the preference (COLOR_SCHEME_STORAGE_KEY in components/theme.tsx; copied, not imported, so the runner loads no React).\nconst COLOR_SCHEME_STORAGE_KEY = \"strata-color-scheme\";\n\n// Animations and transitions off, caret hidden: a screenshot is of the settled state.\nconst freeze = `*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }`;\n\n/** Options shared by every shot of a run. */\nexport interface CaptureOptions {\n /** Where `shot.path` resolves, ending in `/`. */\n baseUrl: string;\n time?: string | number | Date;\n timezone?: string;\n locale?: string;\n /** Block service workers (an app's own MSW worker or PWA cache would bypass the handlers). */\n blockServiceWorkers?: boolean;\n onUnhandledRequest?: \"error\" | \"bypass\";\n /** Look up which faces drew the page's text and return the ones that are not web fonts. Default true. */\n checkFonts?: boolean;\n}\n\n/** What one shot produced. */\nexport interface Capture {\n png: Buffer;\n /** Page errors, console errors and unanswered requests. */\n problems: string[];\n /**\n * Text drawn in a font installed on this machine rather than one the page loaded, one line per\n * face with an example element, e.g. `\"DejaVu Sans\" in <kbd> \"⌘K\"`. Such text renders\n * differently on every machine, so the runner fails the shot (see {@link VisualConfig.systemFonts}).\n */\n systemFonts: string[];\n}\n\n/** Resolves a shot's path under the base URL, keeping the base's own path (`/app/` + `/review`). */\nexport function resolveShotUrl(path: string, baseUrl: string): string {\n if (/^[a-z][a-z0-9+.-]*:/i.test(path)) return path;\n return new URL(path.replace(/^\\/+/, \"\"), baseUrl).href;\n}\n\n/** Converts a request the page made into a Fetch `Request` MSW can match. */\nexport function toFetchRequest(request: Pick<PlaywrightRequest, \"url\" | \"method\" | \"headers\" | \"postDataBuffer\">): Request {\n const method = request.method();\n const body = method === \"GET\" || method === \"HEAD\" ? undefined : (request.postDataBuffer() ?? undefined);\n return new Request(request.url(), { method, headers: request.headers(), body: body ? new Uint8Array(body) : undefined });\n}\n\nasync function answerWithHandlers(\n context: BrowserContext,\n handlers: readonly RequestHandler[],\n baseUrl: string,\n unhandled: \"error\" | \"bypass\",\n problems: string[],\n) {\n const msw = await import(\"msw\").catch(() => {\n throw new Error(\"route shots with handlers need msw: npm install -D msw\");\n });\n const origin = new URL(baseUrl).origin;\n await context.route(\"**/*\", async (route: PlaywrightRoute) => {\n const request = route.request();\n const response = await msw.getResponse([...handlers], toFetchRequest(request), { baseUrl: origin, quiet: true });\n if (response && response.headers.get(\"x-msw-intention\") !== \"passthrough\") {\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => (headers[key] = value));\n await route.fulfill({ status: response.status, headers, body: Buffer.from(await response.arrayBuffer()) });\n return;\n }\n if (!response && unhandled === \"error\" && [\"fetch\", \"xhr\", \"eventsource\", \"websocket\"].includes(request.resourceType())) {\n const url = new URL(request.url());\n problems.push(`no handler for ${request.method()} ${url.origin === origin ? \"\" : url.origin}${url.pathname}${url.search}`);\n }\n await route.continue();\n });\n}\n\n/** Takes one shot and returns its PNG, or throws with what went wrong. Page and console errors are returned as problems. */\nexport async function capture(browser: Browser, shot: Shot, options: CaptureOptions): Promise<Capture> {\n const context = await browser.newContext({\n viewport: shot.viewport,\n deviceScaleFactor: 1,\n reducedMotion: \"reduce\",\n colorScheme: shot.theme,\n timezoneId: options.timezone ?? \"UTC\",\n locale: options.locale ?? \"en-US\",\n serviceWorkers: options.blockServiceWorkers ? \"block\" : \"allow\",\n });\n const problems: string[] = [];\n try {\n if (options.time !== undefined) await context.clock.setFixedTime(options.time);\n // The theme the app's ThemeProvider reads before React runs (what `colorSchemeScript()` reads), so a shot's\n // theme reaches an app whose default preference is not \"system\" (issue #136). Failing storage is the app's no-op.\n await context.addInitScript(\n ({ key, theme }) => {\n try {\n localStorage.setItem(key, theme);\n } catch {}\n },\n { key: COLOR_SCHEME_STORAGE_KEY, theme: shot.theme },\n );\n if (shot.darkClass) {\n await context.addInitScript(\n ({ cls, dark }) => {\n const apply = () => document.documentElement?.classList.toggle(cls, dark);\n apply();\n document.addEventListener(\"DOMContentLoaded\", apply);\n },\n { cls: shot.darkClass, dark: shot.theme === \"dark\" },\n );\n }\n if (shot.handlers?.length || options.onUnhandledRequest === \"error\") {\n await answerWithHandlers(context, shot.handlers ?? [], options.baseUrl, options.onUnhandledRequest ?? \"bypass\", problems);\n }\n const page = await context.newPage();\n page.on(\"pageerror\", (e) => problems.push(e.message));\n // Error responses a state serves on purpose (4xx/5xx) are logged by Chromium; not a fault.\n page.on(\"console\", (m) => {\n if (m.type() === \"error\" && !m.text().startsWith(\"Failed to load resource\")) problems.push(m.text());\n });\n await page.goto(resolveShotUrl(shot.path, options.baseUrl), { waitUntil: \"load\" });\n await page.addStyleTag({ content: freeze });\n await page.waitForFunction((root) => (document.querySelector(root)?.childElementCount ?? 0) > 0, shot.root, { timeout: 15_000 }).catch(() => {\n throw new Error(`${shot.root} stayed empty for 15s`);\n });\n if (shot.waitFor) await page.locator(shot.waitFor).first().waitFor({ state: \"visible\", timeout: 15_000 });\n await settle(page);\n if (shot.setup) {\n await shot.setup(page, shot);\n await settle(page);\n }\n let png: Buffer;\n if (shot.clip === \"page\") {\n png = await page.screenshot({ fullPage: true, animations: \"disabled\" });\n } else {\n const clip = await page.evaluate(paintedBox, { root: shot.root, margin: 8 });\n if (!clip) throw new Error(\"rendered nothing visible\");\n png = await page.screenshot({ fullPage: true, clip, animations: \"disabled\" });\n }\n const systemFonts = options.checkFonts === false ? [] : await platformFonts(page);\n return { png, problems, systemFonts };\n } finally {\n await context.close();\n }\n}\n\nasync function settle(page: Page) {\n // A state that is meant to stay loading keeps a request open, so networkidle may not come.\n await page.waitForLoadState(\"networkidle\", { timeout: 3_000 }).catch(() => undefined);\n await page.evaluate(() => document.fonts.ready.then(() => undefined));\n // A paused video shows its first frame once decoded; without this a shot is taken before or after, depending on the machine.\n await page\n .waitForFunction(() => [...document.querySelectorAll(\"video\")].every((v) => v.readyState >= 2 || v.error !== null), undefined, { timeout: 5_000 })\n .catch(() => undefined);\n // Decoded is not painted: on a loaded runner Chromium can hold a decoded first frame back from the\n // compositor, and a shot then shows an empty cell for good (it stays empty for seconds; this was the\n // flaky CompareVideoGrid shots). A seek to the time a video is already at presents a fresh frame, and\n // its callback says when it was handed to the compositor, so each shot waits for that, per video.\n await page\n .evaluate(() =>\n Promise.all(\n [...document.querySelectorAll(\"video\")]\n .filter((v) => v.readyState >= 2 && !v.error && \"requestVideoFrameCallback\" in v)\n .map(\n (v) =>\n new Promise<void>((done) => {\n const stop = window.setTimeout(done, 2_000);\n v.requestVideoFrameCallback(() => {\n window.clearTimeout(stop);\n done();\n });\n v.currentTime = v.currentTime;\n }),\n ),\n ),\n )\n .catch(() => undefined);\n await page.waitForTimeout(250);\n}\n\n// Which faces drew the text. Chromium's DevTools protocol reports, per element, the font files\n// that actually painted its glyphs and whether each came from the page (@font-face) or from the\n// machine. A system face is the largest source of machine-to-machine difference left once the\n// browser is pinned: the same `ui-sans-serif` is Cantarell on one Linux, DejaVu on another and\n// San Francisco on a Mac, and a glyph missing from a web font (an arrow, ⌘) falls back to\n// whatever the machine has. So the shot reports it rather than tolerating it in the comparison.\nasync function platformFonts(page: Page): Promise<string[]> {\n const cdp = await page.context().newCDPSession(page);\n try {\n await cdp.send(\"DOM.enable\");\n await cdp.send(\"CSS.enable\");\n const { root } = await cdp.send(\"DOM.getDocument\", { depth: -1, pierce: true });\n type DomNode = {\n nodeId: number;\n nodeType: number;\n nodeName: string;\n nodeValue: string;\n pseudoType?: string;\n children?: DomNode[];\n shadowRoots?: DomNode[];\n pseudoElements?: DomNode[];\n contentDocument?: DomNode;\n };\n const texts: { id: number; name: string; text: string }[] = [];\n const walk = (n: DomNode) => {\n if (n.nodeName === \"SCRIPT\" || n.nodeName === \"STYLE\" || n.nodeName === \"HEAD\") return;\n const own = n.children?.filter((c) => c.nodeType === 3 && c.nodeValue.trim()) ?? [];\n if (n.nodeType === 1 && own.length) texts.push({ id: n.nodeId, name: n.nodeName.toLowerCase(), text: own.map((c) => c.nodeValue.trim()).join(\" \") });\n // Generated content (`::before { content: \"⌘\" }`) draws text too; it has no text child.\n for (const p of n.pseudoElements ?? []) texts.push({ id: p.nodeId, name: `${n.nodeName.toLowerCase()}::${p.pseudoType ?? \"pseudo\"}`, text: \"\" });\n for (const c of [...(n.children ?? []), ...(n.shadowRoots ?? []), ...(n.contentDocument ? [n.contentDocument] : [])]) walk(c);\n };\n walk(root as DomNode);\n const found = new Map<string, string>();\n for (const t of texts) {\n // A node that is not rendered (display: none) has no fonts and is skipped by Chromium.\n const { fonts } = await cdp.send(\"CSS.getPlatformFontsForNode\", { nodeId: t.id }).catch(() => ({ fonts: [] }));\n for (const f of fonts) {\n if (f.isCustomFont || found.has(f.familyName)) continue;\n const text = t.text.length > 30 ? `${t.text.slice(0, 29)}…` : t.text;\n // The CSS stack that fell through to the machine, so a `--font-mono` that names a face the app did not import is\n // recognisable as such (issue #136): the glyph or the whole stack was missing from the bundled faces.\n const { computedStyle } = await cdp.send(\"CSS.getComputedStyleForNode\", { nodeId: t.id }).catch(() => ({ computedStyle: [] }));\n const stack = computedStyle.find((p) => p.name === \"font-family\")?.value;\n found.set(f.familyName, `\"${f.familyName}\" in <${t.name}>${text ? ` \"${text}\"` : \"\"}${stack ? ` (font-family: ${stack})` : \"\"}`);\n }\n }\n return [...found.values()];\n } finally {\n await cdp.detach().catch(() => undefined);\n }\n}\n\n// Runs in the page. The box around what the root actually paints: text, replaced and form\n// elements, SVGs, and any box with a background, border or shadow, each cut to the scroll\n// containers it sits in. So a row of buttons is cropped to the buttons, not the full-width div\n// holding them, and fixed elements (an undo bar) count wherever they are. Portalled overlays\n// (children of the body outside the root) count too, so an open dialog or popover is in its shot. The screenshot is\n// fullPage, so the box may extend past the viewport and a large component is captured whole.\nfunction paintedBox({ root: selector, margin }: { root: string; margin: number }) {\n const root = document.querySelector(selector);\n if (!root) return null;\n const replaced = new Set([\"IMG\", \"INPUT\", \"SELECT\", \"TEXTAREA\", \"CANVAS\", \"VIDEO\", \"svg\", \"HR\"]);\n const transparent = (c: string) => c === \"transparent\" || /rgba\\(.*,\\s*0\\)$/.test(c) || /\\/\\s*0\\)$/.test(c);\n const paints = (el: Element) => {\n const cs = getComputedStyle(el);\n if (replaced.has(el.tagName)) return true;\n if (!transparent(cs.backgroundColor) || cs.backgroundImage !== \"none\" || cs.boxShadow !== \"none\") return true;\n return ([\"Top\", \"Right\", \"Bottom\", \"Left\"] as const).some(\n (s) => parseFloat(cs[`border${s}Width`]) > 0 && cs[`border${s}Style`] !== \"none\",\n );\n };\n const clipTo = (r: DOMRect, el: Node) => {\n let { left, top, right, bottom } = r;\n for (let a = el.parentElement; a && a !== document.body; a = a.parentElement) {\n const cs = getComputedStyle(a);\n if (cs.overflowX !== \"visible\" || cs.overflowY !== \"visible\" || cs.clipPath !== \"none\" || cs.clip !== \"auto\") {\n const b = a.getBoundingClientRect();\n left = Math.max(left, b.left);\n top = Math.max(top, b.top);\n right = Math.min(right, b.right);\n bottom = Math.min(bottom, b.bottom);\n }\n if (cs.position === \"fixed\") break;\n }\n return right - left > 1 && bottom - top > 1 ? { left, top, right, bottom } : null;\n };\n const rects: { left: number; top: number; right: number; bottom: number }[] = [];\n // Overlays (dialogs, popovers, tooltips, menus) are portalled to the body, outside the root, so\n // the walk covers the root and every other element the body holds besides scripts and styles.\n const roots: Element[] = [root, ...[...document.body.children].filter((c) => !c.contains(root) && ![\"SCRIPT\", \"STYLE\", \"LINK\", \"TEMPLATE\"].includes(c.tagName))];\n const nodes: Node[] = [];\n for (const r of roots) {\n const walker = document.createTreeWalker(r, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);\n for (let n = walker.nextNode(); n; n = walker.nextNode()) nodes.push(n);\n }\n for (const n of nodes) {\n if (n.nodeType === Node.TEXT_NODE) {\n if (!n.textContent?.trim() || !n.parentElement) continue;\n const range = document.createRange();\n range.selectNodeContents(n);\n for (const r of range.getClientRects()) {\n // From the text node itself, so its own element's clip counts too (an sr-only span is a\n // 1px clipped box, and its text paints nothing).\n const c = clipTo(r, n);\n if (c) rects.push(c);\n }\n continue;\n }\n const el = n as Element;\n if (el.closest(\"svg\") && el.tagName !== \"svg\") continue;\n if (getComputedStyle(el).visibility === \"hidden\" || !paints(el)) continue;\n const c = clipTo(el.getBoundingClientRect(), el);\n if (c) rects.push(c);\n }\n if (!rects.length) return null;\n const x0 = Math.max(0, Math.floor(Math.min(...rects.map((r) => r.left)) + scrollX - margin));\n const y0 = Math.max(0, Math.floor(Math.min(...rects.map((r) => r.top)) + scrollY - margin));\n const x1 = Math.min(document.documentElement.scrollWidth, Math.ceil(Math.max(...rects.map((r) => r.right)) + scrollX + margin));\n const y1 = Math.min(document.documentElement.scrollHeight, Math.ceil(Math.max(...rects.map((r) => r.bottom)) + scrollY + margin));\n return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };\n}\n","// PNG decode and pixelmatch comparison, kept apart from the browser so it is unit tested without\n// one. The defaults are the ones every Strata suite uses, so a baseline means the same thing in\n// the library and in an app; a config can change them (`VisualConfig.compare`).\n//\n// Why blur first. Two machines running the same Chromium still rasterise edges a little\n// differently (GPU or CPU raster, SIMD paths, a newer Skia): the coverage of an edge pixel moves\n// to its neighbour, so plain pixelmatch sees a scatter of differing pixels along every edge and\n// glyph. Experiments on Strata's 218 shots (CHANGELOG, 2026-11-07) found that noise reached 159\n// pixels at threshold 0.1 under GPU raster, more than one changed letter makes (10 to 50 pixels),\n// so no pixel allowance could tell the two apart. Averaging each pixel with its 3×3 neighbours\n// before comparing keeps the ink an edge or glyph lays down and drops where exactly it fell: the\n// same noise then came to at most 1 pixel, while a changed letter, a weight step, a 1px shift or a\n// colour change still differed by tens to thousands. A size change is always a change (the layout\n// moved).\nimport pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\n/** Per-pixel colour distance pixelmatch treats as equal (0–1), measured after the blur. */\nexport const THRESHOLD = 0.1;\n/** Radius in pixels of the box blur applied to both images before comparing (1 is 3×3; 0 turns it off). */\nexport const BLUR = 1;\n/** Differing pixels (after the blur) tolerated before a screenshot counts as changed. */\nexport const MAX_DIFF_PIXELS = 4;\n\n/** How two screenshots are compared. Every field has the default above. */\nexport interface CompareOptions {\n /** Per-pixel colour distance treated as equal, 0–1 (pixelmatch's `threshold`). Default {@link THRESHOLD}. */\n threshold?: number;\n /** Box blur radius in whole pixels applied to both images first, absorbing anti-aliasing differences (0 turns it off). Default {@link BLUR}. */\n blur?: number;\n /** Differing pixels tolerated. Default {@link MAX_DIFF_PIXELS}. */\n maxDiffPixels?: number;\n /** Count pixels pixelmatch judges to be anti-aliasing as differences too. Default false. */\n includeAA?: boolean;\n}\n\n/** A decoded RGBA image. */\nexport interface Image {\n width: number;\n height: number;\n data: Uint8Array;\n}\n\n/** The result of comparing a screenshot with its baseline. */\nexport interface CompareResult {\n /** Within tolerance: the screenshot matches. */\n same: boolean;\n /** Every pixel is identical, before any blur or threshold. */\n identical: boolean;\n /** Pixels that differ beyond the threshold after the blur (Infinity when the size changed). */\n diffPixels: number;\n /** The same count without the blur: how much anti-aliasing the blur absorbed. */\n unblurredDiffPixels: number;\n /** One line for a report: what changed. */\n reason: string;\n /** A PNG highlighting the differing pixels in red over the faded baseline, when the images differ in content. */\n diff?: Buffer;\n}\n\n/** Decodes a PNG file's bytes. */\nexport function decode(buffer: Buffer | Uint8Array): Image {\n return PNG.sync.read(Buffer.from(buffer));\n}\n\n/** Encodes an RGBA image as PNG bytes. */\nexport function encode({ width, height, data }: Image): Buffer {\n const png = new PNG({ width, height });\n png.data = Buffer.from(data);\n return PNG.sync.write(png);\n}\n\n/** Box-blurs an RGBA image with the given radius (separable, edges averaged over what exists). */\nexport function boxBlur({ width: w, height: h, data }: Image, radius: number): Uint8Array {\n if (!Number.isInteger(radius) || radius < 0) throw new Error(`blur must be a whole number of pixels, 0 or more (got ${radius})`);\n if (radius === 0) return data;\n const pass = (src: ArrayLike<number>, horizontal: boolean) => {\n const out = new Float32Array(src.length);\n const [outer, inner] = horizontal ? [h, w] : [w, h];\n for (let o = 0; o < outer; o++) {\n for (let c = 0; c < 4; c++) {\n const at = (i: number) => ((horizontal ? o * w + i : i * w + o) << 2) + c;\n // Running sum over the window, so the cost does not grow with the radius.\n let sum = 0;\n for (let i = 0; i <= Math.min(radius, inner - 1); i++) sum += src[at(i)];\n for (let i = 0; i < inner; i++) {\n const lo = Math.max(0, i - radius);\n const hi = Math.min(inner - 1, i + radius);\n out[at(i)] = sum / (hi - lo + 1);\n if (i + radius + 1 < inner) sum += src[at(i + radius + 1)];\n if (i - radius >= 0) sum -= src[at(i - radius)];\n }\n }\n }\n return out;\n };\n const blurred = pass(pass(data, true), false);\n const out = new Uint8Array(blurred.length);\n for (let i = 0; i < blurred.length; i++) out[i] = Math.round(blurred[i]);\n return out;\n}\n\nfunction sameBytes(a: Uint8Array, b: Uint8Array) {\n return a.length === b.length && Buffer.compare(Buffer.from(a.buffer, a.byteOffset, a.byteLength), Buffer.from(b.buffer, b.byteOffset, b.byteLength)) === 0;\n}\n\n/** Compares two decoded PNGs with pixelmatch after a small blur. A size change is always a change. */\nexport function compare(expected: Image, actual: Image, options: CompareOptions = {}): CompareResult {\n const { threshold = THRESHOLD, blur = BLUR, maxDiffPixels = MAX_DIFF_PIXELS, includeAA = false } = options;\n if (expected.width !== actual.width || expected.height !== actual.height) {\n return {\n same: false,\n identical: false,\n diffPixels: Number.POSITIVE_INFINITY,\n unblurredDiffPixels: Number.POSITIVE_INFINITY,\n reason: `size ${expected.width}×${expected.height} → ${actual.width}×${actual.height}`,\n };\n }\n const { width, height } = expected;\n if (sameBytes(expected.data, actual.data)) return { same: true, identical: true, diffPixels: 0, unblurredDiffPixels: 0, reason: \"identical\" };\n const mask = new Uint8Array(width * height * 4);\n const diffPixels = pixelmatch(boxBlur(expected, blur), boxBlur(actual, blur), mask, width, height, {\n threshold,\n includeAA,\n diffMask: true,\n });\n const unblurredDiffPixels = blur > 0 ? pixelmatch(expected.data, actual.data, null, width, height, { threshold, includeAA }) : diffPixels;\n const same = diffPixels <= maxDiffPixels;\n return {\n same,\n identical: false,\n diffPixels,\n unblurredDiffPixels,\n reason: `${diffPixels} pixels differ (${((diffPixels / (width * height)) * 100).toFixed(3)}%)${blur > 0 ? `, ${unblurredDiffPixels} without the blur` : \"\"}`,\n diff: same ? undefined : diffImage(expected, mask),\n };\n}\n\n// The baseline faded to grey, with the pixels that differ (pixelmatch's red mask) on top: the\n// mask was computed on blurred images, so it is drawn over the sharp baseline to stay readable.\nfunction diffImage(expected: Image, mask: Uint8Array): Buffer {\n const png = new PNG({ width: expected.width, height: expected.height });\n const d = expected.data;\n for (let i = 0; i < d.length; i += 4) {\n if (mask[i + 3] > 0 && mask[i] === 255 && mask[i + 1] === 0) {\n png.data[i] = 255;\n png.data[i + 1] = 0;\n png.data[i + 2] = 0;\n } else {\n const grey = 255 + ((0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2] - 255) * 0.1 * d[i + 3]) / 255;\n png.data[i] = png.data[i + 1] = png.data[i + 2] = grey;\n }\n png.data[i + 3] = 255;\n }\n return PNG.sync.write(png);\n}\n","// A static file server for a build folder, on a free local port. Storybook needs nothing more;\n// an app's build also needs history fallback (a request for /review that asks for HTML gets\n// index.html, as a host like Pages or Netlify would serve it) and its Vite `base`. Requests that\n// do not ask for HTML are never given index.html, so a missed API route fails loudly as a 404\n// instead of a JSON parse error.\nimport { createServer } from \"node:http\";\nimport { createReadStream, existsSync, statSync } from \"node:fs\";\nimport { extname, join, normalize, resolve, sep } from \"node:path\";\n\nconst types: Record<string, string> = {\n \".html\": \"text/html\",\n \".js\": \"text/javascript\",\n \".mjs\": \"text/javascript\",\n \".css\": \"text/css\",\n \".json\": \"application/json\",\n \".map\": \"application/json\",\n \".webmanifest\": \"application/manifest+json\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n \".gif\": \"image/gif\",\n \".ico\": \"image/x-icon\",\n \".woff2\": \"font/woff2\",\n \".woff\": \"font/woff\",\n \".ttf\": \"font/ttf\",\n \".txt\": \"text/plain\",\n \".wasm\": \"application/wasm\",\n};\n\n/** A running server: its origin plus base, and how to stop it. */\nexport interface StaticServer {\n /** e.g. `http://127.0.0.1:53121/app/` (always ends in `/`). */\n url: string;\n close(): Promise<void>;\n}\n\n/** Serves `dir` on 127.0.0.1 under `base`, with history fallback to `index.html` when `spa` is set. */\nexport async function serveStatic(dir: string, { spa = false, base = \"/\" }: { spa?: boolean; base?: string } = {}): Promise<StaticServer> {\n const root = resolve(dir);\n const prefix = `/${base.replace(/^\\/+|\\/+$/g, \"\")}/`.replace(/^\\/\\/$/, \"/\");\n const server = createServer((req, res) => {\n const pathname = decodeURIComponent(new URL(req.url ?? \"/\", \"http://x\").pathname);\n if (!pathname.startsWith(prefix) && `${pathname}/` !== prefix) {\n res.writeHead(404).end();\n return;\n }\n const rel = normalize(pathname.slice(prefix.length)).replace(/^([/\\\\])+/, \"\");\n let file = join(root, rel || \"index.html\");\n if (file !== root && !file.startsWith(root + sep)) {\n res.writeHead(404).end();\n return;\n }\n if (existsSync(file) && statSync(file).isDirectory()) file = join(file, \"index.html\");\n if (!existsSync(file)) {\n const wantsHtml = (req.headers.accept ?? \"\").includes(\"text/html\");\n if (!spa || !wantsHtml || !existsSync(join(root, \"index.html\"))) {\n res.writeHead(404).end();\n return;\n }\n file = join(root, \"index.html\");\n }\n res.writeHead(200, { \"Content-Type\": types[extname(file)] ?? \"application/octet-stream\", \"Service-Worker-Allowed\": \"/\" });\n createReadStream(file).pipe(res);\n });\n await new Promise<void>((r) => server.listen(0, \"127.0.0.1\", r));\n const address = server.address();\n const port = typeof address === \"object\" && address ? address.port : 0;\n return {\n url: `http://127.0.0.1:${port}${prefix}`,\n close: () => new Promise((r) => server.close(() => r())),\n };\n}\n","// The shapes a visual suite is written in. One Shot is one PNG: a URL, a theme, a viewport, how to\n// tell it has rendered, and what to cut out. Storybook stories and app routes are both turned into\n// shots, so capture, comparison and baselines are the same code for a component library and for\n// an app's screens (strata-react issue #13).\nimport type { Page } from \"playwright\";\nimport type { RequestHandler } from \"msw\";\nimport type { CompareOptions } from \"./compare\";\n\n/** The two colour schemes every shot is taken in. */\nexport type Theme = \"light\" | \"dark\";\n\n/** A viewport in CSS pixels. Screenshots are taken at a device scale factor of 1. */\nexport interface Viewport {\n width: number;\n height: number;\n}\n\n/** A named viewport (see {@link viewports}) or an explicit size. */\nexport type ViewportChoice = keyof typeof viewports | Viewport;\n\n/**\n * Named viewports. `wide` and `phone` are what the Storybook tags `visual-wide` and\n * `visual-phone` select; `default` is a laptop-sized screen for routes. (Untagged stories render\n * 1024 wide and 200 tall and grow with the component, see {@link storybookShots}.)\n */\nexport const viewports = {\n default: { width: 1024, height: 768 },\n wide: { width: 1440, height: 900 },\n phone: { width: 390, height: 844 },\n} as const satisfies Record<string, Viewport>;\n\n/**\n * What a screenshot covers. `paint` is the union of what the root element paints (text,\n * controls, SVGs, and boxes with a background, border or shadow) plus 8px, so a component's\n * baseline shows the component and not the empty canvas. `page` is the whole page, for screens.\n */\nexport type Clip = \"paint\" | \"page\";\n\n/** A step run after a shot has rendered and before it is captured: open a menu, focus a field. */\nexport type Setup = (page: Page, shot: Shot) => Promise<void> | void;\n\n/** One screenshot: everything the runner needs to take it and to name its baseline. */\nexport interface Shot {\n /** The baseline's file name without `.png`, e.g. `review--empty--wide--dark`. */\n name: string;\n /** Path and query under the served base (`/review?tab=queue`), or an absolute URL. */\n path: string;\n theme: Theme;\n viewport: Viewport;\n /** Selector of the element the app renders into; the shot waits until it has children. */\n root: string;\n clip: Clip;\n /** A Playwright selector that must be visible before the shot is taken (see {@link RouteState.waitFor}). */\n waitFor?: string;\n /** MSW handlers answering the page's requests, first match wins. Route shots only. */\n handlers?: readonly RequestHandler[];\n /** Class put on `<html>` in the dark theme (Strata's `dark:` variant reads `.dark`). */\n darkClass?: string | false;\n setup?: Setup;\n}\n\n/** An app's built Storybook. */\nexport interface StorybookTarget {\n /** The `storybook build` output folder. Default `storybook-static`. */\n dir?: string;\n /** The Storybook global the preview reads the theme from. Default `theme`, as Strata's preview. */\n themeGlobal?: string;\n}\n\n/** One state of a route: the MSW handlers that put the server into it, and optional steps. */\nexport interface RouteState {\n /** Handlers tried before the target's base handlers (like `server.use(...)` in a test). */\n handlers?: readonly RequestHandler[];\n /** A different path for this state, e.g. the same screen with `?tab=sync`. */\n path?: string;\n /**\n * A Playwright selector that must be visible before the shot is taken, such as `role=alert` or\n * `text=Try again`. Needed when a state takes longer than the network to show: an error after\n * the query client's retry, a toast after a timer.\n */\n waitFor?: string;\n setup?: Setup;\n}\n\n/** A screen of the app, screenshotted in each of its states. */\nexport interface Route {\n /** Names the baselines: lower-case letters, digits and dashes. */\n name: string;\n /** Path and query under the app's base, e.g. `/review` or `/library?sort=-added`. */\n path: string;\n /**\n * The server states to capture, by name. A list of handlers is shorthand for `{ handlers }`.\n * Default: one state, `default`, served by the base handlers alone.\n */\n states?: Record<string, readonly RequestHandler[] | RouteState>;\n viewports?: readonly ViewportChoice[];\n clip?: Clip;\n root?: string;\n waitFor?: string;\n setup?: Setup;\n}\n\n/** An app served from its production build (or a running server), screenshotted route by route. */\nexport interface AppTarget {\n /** The build folder to serve, e.g. `dist`. Unknown paths that ask for HTML get `index.html`. */\n dir?: string;\n /** Or a server that is already running, e.g. `http://localhost:4173`. */\n url?: string;\n /** The app's base path (Vite's `base`). Default `/`. */\n base?: string;\n /** MSW handlers for every route: the healthy server, usually the app's `handlers.ts`. */\n handlers?: readonly RequestHandler[];\n /** Default `#root`. */\n root?: string;\n /** Default `[\"wide\"]`. Every route is taken at each. */\n viewports?: readonly ViewportChoice[];\n /** Default `page`. */\n clip?: Clip;\n /** Default `dark`; `false` to rely on `prefers-color-scheme` alone. */\n darkClass?: string | false;\n /**\n * A `fetch` or XHR request no handler answers: `error` (default) fails the shot, because a\n * screenshot that depends on a real server is not a baseline; `bypass` lets it through.\n */\n onUnhandledRequest?: \"error\" | \"bypass\";\n routes: readonly Route[];\n}\n\n/** A visual suite: where baselines live and what to screenshot. Paths are relative to the config file. */\nexport interface VisualConfig {\n /** Committed baselines. Default `tests/visual/baselines`. */\n baselines?: string;\n /** Actual, expected and diff PNGs of changed shots (uploaded by CI). Default `tests/visual/output`. */\n output?: string;\n /** Default `[\"light\", \"dark\"]`. */\n themes?: readonly Theme[];\n /** Freeze the page's clock at this time, so \"3 minutes ago\" and today's date stay put. */\n time?: string | number | Date;\n /** The page's time zone. Default `UTC`, so a date renders the same on every machine. */\n timezone?: string;\n /** The page's locale (`navigator.language`, `Intl` defaults). Default `en-US`. */\n locale?: string;\n /**\n * What to do with text drawn in a font installed on the machine rather than one the page\n * loaded (a theme whose `--font-*` falls through to `ui-sans-serif`, or a glyph the web font\n * lacks). `error` (default) fails the shot, because no comparison threshold makes Cantarell\n * match San Francisco; `warn` reports it; `allow` skips the check. Bundle every face with\n * `@fontsource` (or your own `@font-face`) and name it first in the theme's `--font-*`.\n */\n systemFonts?: \"error\" | \"warn\" | \"allow\";\n /**\n * How a screenshot is compared with its baseline. The defaults (a 3×3 blur, then pixelmatch at\n * threshold 0.1 with 4 differing pixels allowed) absorb anti-aliasing differences between\n * machines and still fail on a changed letter; change them only with evidence from your own\n * screens.\n */\n compare?: CompareOptions;\n /** Pages captured at once. Default 4. */\n concurrency?: number;\n storybook?: StorybookTarget | string;\n app?: AppTarget;\n}\n\n/** What a run found. */\nexport interface VisualReport {\n /** Shots taken. */\n total: number;\n same: number;\n /** `name.png: reason` for each shot that matched without being pixel-identical (anti-aliasing absorbed). */\n tolerated: string[];\n /** `name.png: reason` for each shot that differs from its baseline. */\n changed: string[];\n /** Shots with no baseline yet (written, and copied to the output folder). */\n added: string[];\n /** Baselines no shot produced (removed when updating). */\n obsolete: string[];\n /** Shots that failed: page errors, console errors, unhandled requests, nothing rendered. */\n errors: string[];\n /** Things that make baselines less trustworthy, such as an unpinned Playwright. */\n warnings: string[];\n updated: boolean;\n /** Whether the run should fail (in CI a missing baseline fails too). */\n failed: boolean;\n}\n","// Turning what an app has into shots. A component library has stories; an app may have only\n// screens (strata-listory has Review, Library and Settings and no stories), so routes are a\n// first-class target: each route is taken in each server state, viewport and theme, with the\n// state set by MSW handlers, the same handlers its unit tests use. Names are stable and readable\n// (`review--empty--phone--dark.png`) because a person reviews baselines by file name in a diff.\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { viewports, type AppTarget, type Route, type RouteState, type Shot, type StorybookTarget, type Theme, type Viewport, type ViewportChoice } from \"./types\";\n\n/** The light and dark themes, the default for every target. */\nexport const defaultThemes: readonly Theme[] = [\"light\", \"dark\"];\n\n// Untagged stories lay out in a 1024-wide, 200-tall frame and the clip grows with the component,\n// so a short component's fixed elements (the undo bar) sit near it rather than 768px down.\nconst storyViewport: Viewport = { width: 1024, height: 200 };\n\ninterface IndexEntry {\n id: string;\n type: string;\n title?: string;\n name?: string;\n tags?: string[];\n}\n\n/**\n * Shots for every story in a built Storybook (its `index.json`), in each theme. Tags pick the\n * viewport: `visual-phone` 390×844, `visual-wide` 1440×900, otherwise 1024 wide; `no-visual`\n * skips the story. A story's own tag beats its file's, since Storybook merges both.\n */\nexport function storybookShots(target: StorybookTarget & { dir: string }, themes: readonly Theme[] = defaultThemes): Shot[] {\n const index = JSON.parse(readFileSync(join(target.dir, \"index.json\"), \"utf8\")) as { entries: Record<string, IndexEntry> };\n const global = target.themeGlobal ?? \"theme\";\n return Object.values(index.entries)\n .filter((e) => e.type === \"story\" && !e.tags?.includes(\"no-visual\"))\n .flatMap((story) => {\n const tag = [\"visual-phone\", \"visual-wide\"].find((t) => story.tags?.includes(t));\n const viewport = tag === \"visual-phone\" ? viewports.phone : tag === \"visual-wide\" ? viewports.wide : storyViewport;\n return themes.map((theme) => ({\n name: `${story.id}--${theme}`,\n path: `iframe.html?id=${story.id}&viewMode=story&globals=${global}:${theme}`,\n theme,\n viewport: { ...viewport },\n root: \"#storybook-root\",\n clip: \"paint\" as const,\n darkClass: false as const,\n }));\n });\n}\n\nconst slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\nfunction viewportName(v: ViewportChoice): string {\n return typeof v === \"string\" ? v : `${v.width}x${v.height}`;\n}\n\nfunction viewportSize(v: ViewportChoice): Viewport {\n if (typeof v !== \"string\") return { width: v.width, height: v.height };\n const size = viewports[v];\n if (!size) throw new Error(`unknown viewport \"${String(v)}\": use ${Object.keys(viewports).join(\", \")} or { width, height }`);\n return { ...size };\n}\n\nfunction stateOf(value: readonly unknown[] | RouteState): RouteState {\n return Array.isArray(value) ? { handlers: value as RouteState[\"handlers\"] } : (value as RouteState);\n}\n\n/**\n * Shots for every route of an app in each state, viewport and theme, named\n * `route--state--viewport--theme`. A state's handlers come before the target's base handlers, as\n * `server.use(...)` would put them.\n */\nexport function routeShots(app: AppTarget, themes: readonly Theme[] = defaultThemes): Shot[] {\n const shots: Shot[] = [];\n for (const route of app.routes as readonly Route[]) {\n if (!slug.test(route.name)) throw new Error(`route name \"${route.name}\" must be lower-case letters, digits and dashes`);\n const states = Object.entries(route.states ?? { default: [] });\n if (!states.length) throw new Error(`route \"${route.name}\" has an empty states object: leave it out for one default state`);\n const chosen = route.viewports ?? app.viewports ?? [\"wide\"];\n for (const [stateName, value] of states) {\n if (!slug.test(stateName)) throw new Error(`state \"${stateName}\" of route \"${route.name}\" must be lower-case letters, digits and dashes`);\n const state = stateOf(value);\n const setups = [route.setup, state.setup].filter((s) => s !== undefined);\n for (const v of chosen) {\n for (const theme of themes) {\n shots.push({\n name: `${route.name}--${stateName}--${viewportName(v)}--${theme}`,\n path: state.path ?? route.path,\n theme,\n viewport: viewportSize(v),\n root: route.root ?? app.root ?? \"#root\",\n clip: route.clip ?? app.clip ?? \"page\",\n waitFor: state.waitFor ?? route.waitFor,\n handlers: [...(state.handlers ?? []), ...(app.handlers ?? [])],\n darkClass: app.darkClass ?? \"dark\",\n setup: setups.length ? async (page, shot) => { for (const s of setups) await s(page, shot); } : undefined,\n });\n }\n }\n }\n }\n return shots;\n}\n","// Running a suite: serve each target, take its shots a few at a time in one Chromium, compare\n// each with its committed baseline, and report. The rules are the library's own, so an app's\n// suite fails for the same reasons Strata's does: a changed screenshot, a page or console\n// error, an unanswered request, and in CI a shot with no baseline (it was added without one).\n//\n// Baselines are only comparable when written by the same Chromium on the same platform, which\n// is why Playwright is pinned to an exact version. A run records both next to the baselines\n// (`.strata-visual.json`) when it writes them, and says so when a later run differs.\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { Browser } from \"playwright\";\nimport { capture } from \"./capture\";\nimport { compare, decode } from \"./compare\";\nimport { serveStatic, type StaticServer } from \"./serve\";\nimport { defaultThemes, routeShots, storybookShots } from \"./targets\";\nimport type { Shot, VisualConfig, VisualReport } from \"./types\";\n\n/** Returns the config unchanged; it exists so a config file is type-checked. */\nexport function defineVisualConfig(config: VisualConfig): VisualConfig {\n return config;\n}\n\n/** Options for one run, usually from the command line. */\nexport interface RunOptions {\n /** Folder the config's paths are relative to. Default `process.cwd()`. */\n cwd?: string;\n /** Write the screenshots as the baselines and remove obsolete ones, instead of comparing. */\n update?: boolean;\n /** Only shots whose name contains this text (obsolete baselines are then not reported). */\n filter?: string;\n /** Fail when a shot has no baseline. Default: when the `CI` environment variable is set. */\n ci?: boolean;\n /** Progress lines; default none. */\n log?: (line: string) => void;\n}\n\nconst metaFile = \".strata-visual.json\";\ninterface Meta {\n chromium: string;\n platform: string;\n}\n\ninterface Batch {\n shots: Shot[];\n server?: StaticServer;\n baseUrl: string;\n blockServiceWorkers: boolean;\n onUnhandledRequest?: \"error\" | \"bypass\";\n}\n\n/** Screenshots every shot the config describes, compares with the baselines, and reports. */\nexport async function runVisual(config: VisualConfig, options: RunOptions = {}): Promise<VisualReport> {\n const cwd = resolve(options.cwd ?? process.cwd());\n const baselineDir = resolve(cwd, config.baselines ?? \"tests/visual/baselines\");\n const outputDir = resolve(cwd, config.output ?? \"tests/visual/output\");\n const themes = config.themes ?? defaultThemes;\n const update = options.update ?? false;\n const ci = options.ci ?? Boolean(process.env.CI);\n const log = options.log ?? (() => undefined);\n const concurrency = config.concurrency ?? 4;\n // A worker count that is not a positive integer would start no workers and report an empty,\n // passing run, so it is refused up front.\n if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(`concurrency must be a whole number of pages, 1 or more (got ${String(config.concurrency)})`);\n const report: VisualReport = { total: 0, same: 0, tolerated: [], changed: [], added: [], obsolete: [], errors: [], warnings: pinWarnings(cwd), updated: update, failed: false };\n\n const batches: Batch[] = [];\n try {\n if (config.storybook !== undefined) {\n const target = typeof config.storybook === \"string\" ? { dir: config.storybook } : config.storybook;\n const dir = resolve(cwd, target.dir ?? \"storybook-static\");\n if (!existsSync(join(dir, \"index.json\"))) throw new Error(`${join(dir, \"index.json\")} not found: build Storybook first (storybook build)`);\n // Shots first: if building them throws, no server is left running to hold the process open.\n const shots = storybookShots({ ...target, dir }, themes);\n const batch: Batch = { shots, baseUrl: \"\", blockServiceWorkers: false };\n batches.push(batch);\n batch.server = await serveStatic(dir);\n batch.baseUrl = batch.server.url;\n }\n if (config.app !== undefined) {\n const app = config.app;\n if (!app.dir === !app.url) throw new Error(\"app needs exactly one of dir (a build to serve) or url (a running server)\");\n const shots = routeShots(app, themes);\n const batch: Batch = { shots, baseUrl: \"\", blockServiceWorkers: true, onUnhandledRequest: app.onUnhandledRequest ?? \"error\" };\n batches.push(batch);\n if (app.dir) {\n const dir = resolve(cwd, app.dir);\n if (!existsSync(join(dir, \"index.html\"))) throw new Error(`${join(dir, \"index.html\")} not found: build the app first`);\n batch.server = await serveStatic(dir, { spa: true, base: app.base });\n batch.baseUrl = batch.server.url;\n } else {\n batch.baseUrl = new URL(`${(app.base ?? \"/\").replace(/^\\/*/, \"/\").replace(/\\/*$/, \"/\")}`, app.url).href;\n }\n }\n if (!batches.length) throw new Error(\"nothing to screenshot: the config needs storybook or app\");\n\n const all = batches.flatMap((b) => b.shots);\n const names = new Set<string>();\n for (const s of all) {\n if (names.has(s.name)) throw new Error(`two shots are named ${s.name}: give routes and states distinct names`);\n names.add(s.name);\n }\n for (const b of batches) b.shots = b.shots.filter((s) => !options.filter || s.name.includes(options.filter));\n report.total = batches.reduce((n, b) => n + b.shots.length, 0);\n\n mkdirSync(baselineDir, { recursive: true });\n rmSync(outputDir, { recursive: true, force: true });\n mkdirSync(outputDir, { recursive: true });\n\n const { chromium } = await import(\"playwright\").catch(() => {\n throw new Error(\"strata-visual needs Playwright: npm install -D -E playwright, then npx playwright install chromium\");\n });\n // Font hinting and LCD anti-aliasing off and an sRGB profile: the same pixels on every machine.\n // STRATA_VISUAL_CHROMIUM_ARGS adds flags, for experiments such as checking that the\n // comparison absorbs another rasteriser (the visual-portability workflow).\n const extraArgs = (process.env.STRATA_VISUAL_CHROMIUM_ARGS ?? \"\").split(/\\s+/).filter(Boolean);\n const browser = await chromium.launch({ args: [\"--font-render-hinting=none\", \"--disable-lcd-text\", \"--force-color-profile=srgb\", ...extraArgs] });\n const meta: Meta = { chromium: browser.version(), platform: `${process.platform}-${process.arch}` };\n try {\n for (const batch of batches) await runBatch(browser, batch, { config, baselineDir, outputDir, update, report, log });\n } finally {\n await browser.close();\n }\n\n const pngs = readdirSync(baselineDir).filter((f) => f.endsWith(\".png\"));\n report.obsolete = options.filter ? [] : pngs.filter((f) => !names.has(f.slice(0, -4)));\n if (update) {\n for (const f of report.obsolete) rmSync(join(baselineDir, f));\n if (!options.filter) writeFileSync(join(baselineDir, metaFile), `${JSON.stringify(meta, null, 2)}\\n`);\n } else if (report.changed.length) {\n const written = readMeta(baselineDir);\n if (written && (written.chromium !== meta.chromium || written.platform !== meta.platform)) {\n report.warnings.push(\n `the baselines were written by Chromium ${written.chromium} on ${written.platform}; this run used Chromium ${meta.chromium} on ${meta.platform}, so some differences may be the browser, not the app`,\n );\n }\n }\n } finally {\n for (const b of batches) await b.server?.close();\n }\n report.failed = Boolean(report.errors.length || report.changed.length || (ci && !update && report.added.length));\n return report;\n}\n\nasync function runBatch(\n browser: Browser,\n batch: Batch,\n ctx: { config: VisualConfig; baselineDir: string; outputDir: string; update: boolean; report: VisualReport; log: (l: string) => void },\n) {\n const { baselineDir, outputDir, update, report } = ctx;\n const shoot = async (shot: Shot) => {\n const file = `${shot.name}.png`;\n try {\n const fonts = ctx.config.systemFonts ?? \"error\";\n const { png, problems, systemFonts } = await capture(browser, shot, {\n baseUrl: batch.baseUrl,\n time: ctx.config.time,\n timezone: ctx.config.timezone,\n locale: ctx.config.locale,\n blockServiceWorkers: batch.blockServiceWorkers,\n onUnhandledRequest: batch.onUnhandledRequest,\n checkFonts: fonts !== \"allow\",\n });\n if (systemFonts.length) {\n const line = `${file}: text in a system font, which differs by machine (bundle the face with @fontsource and name it in the theme's --font-*): ${systemFonts.join(\", \")}`;\n if (fonts === \"error\") problems.push(line.slice(file.length + 2));\n else report.warnings.push(line);\n }\n if (problems.length) report.errors.push(`${file}: ${problems.join(\" | \")}`);\n const baselinePath = join(baselineDir, file);\n if (update || !existsSync(baselinePath)) {\n if (!update) report.added.push(file);\n writeFileSync(baselinePath, png);\n if (!update) writeFileSync(join(outputDir, file), png);\n return;\n }\n const expected = readFileSync(baselinePath);\n const result = compare(decode(expected), decode(png), ctx.config.compare);\n if (result.same) {\n report.same++;\n if (!result.identical) report.tolerated.push(`${file}: ${result.reason}`);\n return;\n }\n report.changed.push(`${file}: ${result.reason}`);\n writeFileSync(join(outputDir, `${shot.name}.actual.png`), png);\n writeFileSync(join(outputDir, `${shot.name}.expected.png`), expected);\n if (result.diff) writeFileSync(join(outputDir, `${shot.name}.diff.png`), result.diff);\n } catch (e) {\n report.errors.push(`${file}: ${(e instanceof Error ? e.message : String(e)).split(\"\\n\")[0]}`);\n } finally {\n ctx.log(file);\n }\n };\n // A few pages at once: each shot has its own context, so they cannot affect each other.\n const queue = [...batch.shots];\n await Promise.all(\n Array.from({ length: ctx.config.concurrency ?? 4 }, async () => {\n for (let shot = queue.shift(); shot; shot = queue.shift()) await shoot(shot);\n }),\n );\n}\n\nfunction readMeta(dir: string): Meta | undefined {\n try {\n return JSON.parse(readFileSync(join(dir, metaFile), \"utf8\")) as Meta;\n } catch {\n return undefined;\n }\n}\n\n/** A warning when the app's package.json lets Playwright float, since each version brings its own Chromium. */\nexport function pinWarnings(cwd: string): string[] {\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n try {\n pkg = JSON.parse(readFileSync(join(cwd, \"package.json\"), \"utf8\"));\n } catch {\n return [];\n }\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n return [\"playwright\", \"@playwright/test\"]\n .filter((name) => deps[name] !== undefined && !/^\\d+\\.\\d+\\.\\d+$/.test(deps[name]))\n .map(\n (name) =>\n `${name} is \"${deps[name]}\" in package.json: pin an exact version (npm install -D -E ${name}) so CI and the machine that wrote the baselines render with the same Chromium`,\n );\n}\n\n// Sorts by the blurred count, then by the count without the blur.\nconst pixels = (line: string) => {\n const m = /: (\\d+) pixels differ[^,]*(?:, (\\d+) without)?/.exec(line);\n return Number(m?.[1] ?? 0) * 1e9 + Number(m?.[2] ?? 0);\n};\n\n/** The report as the lines the command prints. */\nexport function formatReport(report: VisualReport): string {\n const lines = [\n report.updated\n ? `Wrote ${report.total} baselines${report.obsolete.length ? `, removed ${report.obsolete.length} obsolete` : \"\"}.`\n : `${report.same} of ${report.total} screenshots match their baselines${report.tolerated.length ? ` (${report.same - report.tolerated.length} identical, ${report.tolerated.length} within tolerance)` : \"\"}.`,\n ...report.changed.map((l) => `changed ${l}`),\n // The most-differing few: enough to see how close to the allowance a machine runs.\n ...[...report.tolerated]\n .sort((a, b) => pixels(b) - pixels(a))\n .slice(0, 5)\n .map((l) => `within ${l}`),\n ...(report.tolerated.length > 5 ? [`within … and ${report.tolerated.length - 5} more`] : []),\n ...report.added.map((l) => `new ${l} (baseline written; commit it)`),\n ...report.obsolete.map((l) => `obsolete ${l}${report.updated ? \" (removed)\" : \" (run with --update to remove)\"}`),\n ...report.errors.map((l) => `error ${l}`),\n ...report.warnings.map((l) => `warning ${l}`),\n ];\n if (report.failed) {\n lines.push(\"\", \"Diffs are in the output folder (tests/visual/output by default). Look at them; if the change is intended, run with --update and commit the baselines.\");\n }\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;AAUA,IAAM,2BAA2B;AAGjC,IAAM,SAAS;;AA8Bf,SAAgB,eAAe,MAAc,SAAyB;CACpE,IAAI,uBAAuB,KAAK,IAAI,GAAG,OAAO;CAC9C,OAAO,IAAI,IAAI,KAAK,QAAQ,QAAQ,EAAE,GAAG,OAAO,CAAC,CAAC;AACpD;;AAGA,SAAgB,eAAe,SAA4F;CACzH,MAAM,SAAS,QAAQ,OAAO;CAC9B,MAAM,OAAO,WAAW,SAAS,WAAW,SAAS,KAAA,IAAa,QAAQ,eAAe,KAAK,KAAA;CAC9F,OAAO,IAAI,QAAQ,QAAQ,IAAI,GAAG;EAAE;EAAQ,SAAS,QAAQ,QAAQ;EAAG,MAAM,OAAO,IAAI,WAAW,IAAI,IAAI,KAAA;CAAU,CAAC;AACzH;AAEA,eAAe,mBACb,SACA,UACA,SACA,WACA,UACA;CACA,MAAM,MAAM,MAAM,OAAO,MAAM,CAAC,YAAY;EAC1C,MAAM,IAAI,MAAM,wDAAwD;CAC1E,CAAC;CACD,MAAM,SAAS,IAAI,IAAI,OAAO,CAAC,CAAC;CAChC,MAAM,QAAQ,MAAM,QAAQ,OAAO,UAA2B;EAC5D,MAAM,UAAU,MAAM,QAAQ;EAC9B,MAAM,WAAW,MAAM,IAAI,YAAY,CAAC,GAAG,QAAQ,GAAG,eAAe,OAAO,GAAG;GAAE,SAAS;GAAQ,OAAO;EAAK,CAAC;EAC/G,IAAI,YAAY,SAAS,QAAQ,IAAI,iBAAiB,MAAM,eAAe;GACzE,MAAM,UAAkC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AAS,KAAK,MAAM,YAAY,GAAG;CAC/C;CACA,IAAI,OAAO,QACT,MAAM,KAAK,IAAI,uJAAuJ;CAExK,OAAO,MAAM,KAAK,IAAI;AACxB"}
@@ -1,4 +1,4 @@
1
- import { i as runVisual, n as formatReport } from "./run-CKlcLpdN.js";
1
+ import { i as runVisual, n as formatReport } from "./run-BqZGKhW9.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
package/dist/visual.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as capture, a as defaultThemes, c as viewports, d as MAX_DIFF_PIXELS, f as THRESHOLD, g as encode, h as decode, i as runVisual, l as serveStatic, m as compare, n as formatReport, o as routeShots, p as boxBlur, r as pinWarnings, s as storybookShots, t as defineVisualConfig, u as BLUR, v as resolveShotUrl, y as toFetchRequest } from "./run-CKlcLpdN.js";
1
+ import { _ as capture, a as defaultThemes, c as viewports, d as MAX_DIFF_PIXELS, f as THRESHOLD, g as encode, h as decode, i as runVisual, l as serveStatic, m as compare, n as formatReport, o as routeShots, p as boxBlur, r as pinWarnings, s as storybookShots, t as defineVisualConfig, u as BLUR, v as resolveShotUrl, y as toFetchRequest } from "./run-BqZGKhW9.js";
2
2
  // src/visual/drop.ts
3
3
  /** What `dropFiles` uses when a file gives no `lastModified`. */
4
4
  var DROPPED_FILE_MODIFIED = Date.UTC(2026, 0, 1);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "strata-react",
3
- "version": "1.0.31",
3
+ "version": "1.0.33",
4
4
  "description": "React + Tailwind v4 components that ship structure, behaviour, states and a token contract, and no look: each product brings a theme generated from its own subject.",
5
5
  "repository": {
6
6
  "type": "git",