strata-react 1.3.16 → 1.3.17

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.
@@ -1 +1 @@
1
- {"version":3,"file":"panorama.js","names":[],"sources":["../src/panorama/gl.ts","../src/panorama/projection.ts","../src/panorama/panorama-viewer.tsx"],"sourcesContent":["import type { PanoramaView } from \"./projection\";\n\n// The WebGL2 side of `PanoramaViewer` (strata-react issue #178): one full-screen triangle, and a\n// fragment shader that does for every pixel what `project`/`unproject` do for one (projection.ts holds\n// the same formulas, and tests hold the two to each other): build the ray through the pixel from the\n// view's yaw, pitch and field of view, turn it into longitude and latitude, and read the equirectangular\n// texture there. The texture repeats across the seam (longitude) and clamps at the poles. No mipmaps:\n// the longitude wraps with an `atan`, whose jump at the seam would make a mipmapped lookup draw a line\n// one pixel wide down it; plain linear filtering draws none.\n//\n// Cost, as documented for apps: one texture upload per *drawn video frame* (`texImage2D` of the\n// `<video>`), none for a still picture (uploaded once), and a draw only when the view, the size or the\n// picture changed, never on a timer.\n\nconst VERTEX = `#version 300 es\nin vec2 aPos;\nout vec2 vNdc;\nvoid main() { vNdc = aPos; gl_Position = vec4(aPos, 0.0, 1.0); }`;\n\nconst FRAGMENT = `#version 300 es\nprecision highp float;\nin vec2 vNdc;\nout vec4 outColor;\nuniform sampler2D uPicture;\nuniform float uYaw;\nuniform float uPitch;\nuniform float uTanHalf;\nuniform float uAspect;\nconst float PI = 3.14159265358979;\nvoid main() {\n vec3 forward = vec3(cos(uPitch) * sin(uYaw), sin(uPitch), cos(uPitch) * cos(uYaw));\n vec3 right = vec3(cos(uYaw), 0.0, -sin(uYaw));\n vec3 up = vec3(-sin(uPitch) * sin(uYaw), cos(uPitch), -sin(uPitch) * cos(uYaw));\n vec3 ray = normalize(forward + vNdc.x * uTanHalf * right + vNdc.y * (uTanHalf / uAspect) * up);\n float lon = atan(ray.x, ray.z);\n float lat = asin(clamp(ray.y, -1.0, 1.0));\n outColor = texture(uPicture, vec2(lon / (2.0 * PI) + 0.5, 0.5 - lat / PI));\n}`;\n\n/** Anything WebGL can take as a texture: a decoded image or a playing video. */\nexport type PanoramaPicture = HTMLImageElement | HTMLVideoElement | ImageBitmap | HTMLCanvasElement;\n\n/** What draws the window. */\nexport type PanoramaRenderer = {\n /** Sends the picture to the GPU. Call when the picture is a new one (an image) or a new frame (a video). */\n upload: (picture: PanoramaPicture) => void;\n /** Draws the view into a canvas of `width` by `height` device pixels. */\n draw: (view: PanoramaView, width: number, height: number) => void;\n /** How many times `upload` has sent a picture (a video frame, an image), for the documented cost and for tests. */\n uploads: () => number;\n /** Frees the GPU objects. */\n dispose: () => void;\n};\n\n/** Makes a renderer on `canvas`, or null where WebGL2 is not available (the viewer then shows the flat picture). */\nexport function createRenderer(canvas: HTMLCanvasElement): PanoramaRenderer | null {\n const gl = canvas.getContext(\"webgl2\", { antialias: false, preserveDrawingBuffer: false, alpha: false }) as WebGL2RenderingContext | null;\n if (!gl) return null;\n const compile = (type: number, source: string) => {\n const shader = gl.createShader(type)!;\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const log = gl.getShaderInfoLog(shader);\n gl.deleteShader(shader);\n throw new Error(`Panorama shader: ${log}`);\n }\n return shader;\n };\n let program: WebGLProgram;\n try {\n program = gl.createProgram()!;\n gl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX));\n gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAGMENT));\n gl.linkProgram(program);\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(`Panorama program: ${gl.getProgramInfoLog(program)}`);\n } catch {\n return null;\n }\n gl.useProgram(program);\n const buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n // One triangle that covers the screen.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n const position = gl.getAttribLocation(program, \"aPos\");\n gl.enableVertexAttribArray(position);\n gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n const uniforms = {\n yaw: gl.getUniformLocation(program, \"uYaw\"),\n pitch: gl.getUniformLocation(program, \"uPitch\"),\n tanHalf: gl.getUniformLocation(program, \"uTanHalf\"),\n aspect: gl.getUniformLocation(program, \"uAspect\"),\n picture: gl.getUniformLocation(program, \"uPicture\"),\n };\n gl.uniform1i(uniforms.picture, 0);\n let uploaded = 0;\n let has = false;\n\n return {\n upload(picture) {\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, picture);\n uploaded++;\n has = true;\n },\n draw(view, width, height) {\n if (canvas.width !== width || canvas.height !== height) {\n canvas.width = width;\n canvas.height = height;\n }\n gl.viewport(0, 0, width, height);\n if (!has) {\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n return;\n }\n const rad = Math.PI / 180;\n gl.uniform1f(uniforms.yaw, view.yaw * rad);\n gl.uniform1f(uniforms.pitch, view.pitch * rad);\n gl.uniform1f(uniforms.tanHalf, Math.tan((view.fov * rad) / 2));\n gl.uniform1f(uniforms.aspect, width / height);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n uploads: () => uploaded,\n dispose() {\n gl.deleteTexture(texture);\n gl.deleteBuffer(buffer);\n gl.deleteProgram(program);\n },\n };\n}\n","// The geometry of `PanoramaViewer` (strata-react issue #178), with no DOM and no GL so every case\n// is tested on its own and the GL shader is held to the same numbers. A 360 picture is\n// *equirectangular*: longitude across, latitude down. The viewer shows a *rectilinear* window into the\n// sphere, as a camera does: straight lines stay straight, and the width of what is seen is the\n// horizontal field of view `fov`.\n//\n// Angles are degrees, because that is what an app and a person talk in. `yaw` is the heading: 0 is the\n// middle of the picture, positive to the right, wrapped to (-180, 180]. `pitch` is the elevation:\n// 0 is the horizon, positive up, limited to +-90 (the apps' own `maxPitch` is kept below that). A\n// direction in the world is a unit vector `(cos p sin y, sin p, cos p cos y)`; the camera's forward,\n// right and up are built from the view's yaw and pitch (no roll: upright footage). A point is drawn\n// where its direction crosses the image plane, `fpx = (width / 2) / tan(fov / 2)` pixels from the camera.\n\n/** Where the window looks and how wide it sees, degrees. */\nexport type PanoramaView = { yaw: number; pitch: number; fov: number };\n\n/** The size of the picture box in CSS pixels. */\nexport type PanoramaSize = { width: number; height: number };\n\n/** A place in the box. `inside` says it is within the box; a point behind the camera has none (`project` returns null). */\nexport type PanoramaPoint = { x: number; y: number; inside: boolean };\n\nconst RAD = Math.PI / 180;\nconst DEG = 180 / Math.PI;\n\n/** Wraps a heading to (-180, 180]. */\nexport function wrapYaw(yaw: number): number {\n const w = ((((yaw + 180) % 360) + 360) % 360) - 180;\n return w === -180 ? 180 : w;\n}\n\n/** The smallest signed turn from heading `from` to heading `to`, in (-180, 180]. Use it for a difference of headings, never `to - from`. */\nexport const yawDelta = (from: number, to: number) => wrapYaw(to - from);\n\n/** Keeps a view inside its limits: heading wrapped, pitch within +-`maxPitch`, field of view within `minFov` to `maxFov`. */\nexport function clampView(view: PanoramaView, { maxPitch = 85, minFov = 20, maxFov = 120 }: { maxPitch?: number; minFov?: number; maxFov?: number } = {}): PanoramaView {\n return { yaw: wrapYaw(view.yaw), pitch: Math.min(Math.max(view.pitch, -maxPitch), maxPitch), fov: Math.min(Math.max(view.fov, minFov), maxFov) };\n}\n\nconst focal = (view: PanoramaView, size: PanoramaSize) => size.width / 2 / Math.tan((view.fov * RAD) / 2);\n\nfunction basis(view: PanoramaView) {\n const y = view.yaw * RAD;\n const p = view.pitch * RAD;\n const forward = [Math.cos(p) * Math.sin(y), Math.sin(p), Math.cos(p) * Math.cos(y)] as const;\n const right = [Math.cos(y), 0, -Math.sin(y)] as const;\n const up = [-Math.sin(p) * Math.sin(y), Math.cos(p), -Math.sin(p) * Math.cos(y)] as const;\n return { forward, right, up };\n}\nconst dot = (a: readonly number[], b: readonly number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n\n/** Where the direction (`yaw`, `pitch`) is drawn in the box for `view`, or null when it is behind the camera. */\nexport function project(view: PanoramaView, size: PanoramaSize, yaw: number, pitch: number): PanoramaPoint | null {\n const { forward, right, up } = basis(view);\n const p = pitch * RAD;\n const y = yaw * RAD;\n const d = [Math.cos(p) * Math.sin(y), Math.sin(p), Math.cos(p) * Math.cos(y)] as const;\n const z = dot(d, forward);\n if (z <= 1e-9) return null;\n const f = focal(view, size);\n const x = size.width / 2 + (f * dot(d, right)) / z;\n const yy = size.height / 2 - (f * dot(d, up)) / z;\n return { x, y: yy, inside: x >= 0 && x <= size.width && yy >= 0 && yy <= size.height };\n}\n\n/** The direction under a point of the box for `view`: the inverse of `project`. */\nexport function unproject(view: PanoramaView, size: PanoramaSize, x: number, y: number): { yaw: number; pitch: number } {\n const { forward, right, up } = basis(view);\n const f = focal(view, size);\n const a = (x - size.width / 2) / f;\n const b = -(y - size.height / 2) / f;\n const v = [forward[0] + a * right[0] + b * up[0], forward[1] + a * right[1] + b * up[1], forward[2] + a * right[2] + b * up[2]] as const;\n const length = Math.hypot(v[0], v[1], v[2]);\n return { yaw: wrapYaw(Math.atan2(v[0], v[2]) * DEG), pitch: Math.asin(Math.min(Math.max(v[1] / length, -1), 1)) * DEG };\n}\n\n/** Pixels to degrees at the middle of the box: how far a drag of `px` turns the view. */\nexport const degreesPerPixel = (view: PanoramaView, size: PanoramaSize) => (Math.atan(1 / focal(view, size)) * DEG);\n\n/** The flat picture's own mapping, for the fallback with no WebGL: longitude and latitude are straight across and down, the visible rectangle is `fov` wide and as tall as the box's shape makes it. */\nexport function projectFlat(view: PanoramaView, size: PanoramaSize, yaw: number, pitch: number): PanoramaPoint {\n const perPixel = view.fov / size.width;\n const x = size.width / 2 + yawDelta(view.yaw, yaw) / perPixel;\n const y = size.height / 2 - (pitch - view.pitch) / perPixel;\n return { x, y, inside: x >= 0 && x <= size.width && y >= 0 && y <= size.height };\n}\n\n/** The inverse of `projectFlat`. */\nexport function unprojectFlat(view: PanoramaView, size: PanoramaSize, x: number, y: number): { yaw: number; pitch: number } {\n const perPixel = view.fov / size.width;\n return { yaw: wrapYaw(view.yaw + (x - size.width / 2) * perPixel), pitch: Math.min(Math.max(view.pitch - (y - size.height / 2) * perPixel, -90), 90) };\n}\n\n/** The direction in words: \"Looking 40° right, 5° up\", \"Looking straight ahead\". Whole degrees; nothing is said for less than half a degree. */\nexport function describeView(view: Pick<PanoramaView, \"yaw\" | \"pitch\">): string {\n const yaw = Math.round(wrapYaw(view.yaw));\n const pitch = Math.round(view.pitch);\n const side = yaw === 0 ? \"\" : yaw === 180 ? \"directly behind\" : `${Math.abs(yaw)}° ${yaw > 0 ? \"right\" : \"left\"}`;\n const tilt = pitch === 0 ? \"\" : `${Math.abs(pitch)}° ${pitch > 0 ? \"up\" : \"down\"}`;\n const parts = [side, tilt].filter(Boolean);\n return parts.length === 0 ? \"Looking straight ahead\" : `Looking ${parts.join(\", \")}`;\n}\n","import * as React from \"react\";\nimport { VisuallyHidden } from \"react-aria\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\nimport { Slider } from \"../components/value-controls\";\nimport { createRenderer, type PanoramaPicture, type PanoramaRenderer } from \"./gl\";\nimport { clampView, degreesPerPixel, describeView, project, projectFlat, unproject, unprojectFlat, type PanoramaPoint, type PanoramaSize, type PanoramaView } from \"./projection\";\n\n// A 360 picture or video as a window you pan and zoom (strata-react issue #178, from strata-360, which\n// drew equirectangular footage with a hand-written WebGL2 shader and its own pointer, transport and\n// frame stepping). This is its own entry (`strata-react/panorama`) so an app that never shows 360 ships\n// no GL code. Nothing else in the package is as far from React Aria's world, so the choices:\n//\n// - **The picture is a canvas, the controls are keys and pointers on a group.** React Aria has no 360\n// view, so the viewer is ours; what it can give, it gives: the field-of-view slider is Strata's\n// `Slider` (React Aria's), and the pointer handling is plain pointer events (React Aria's `usePress`\n// is for a press, not a drag that turns a sphere; checked in its props: it reports a press and its\n// start and end, with no movement).\n// - **It does not own the video.** `video` is a ref to an element the app owns (`useMediaElement`,\n// `Transport`, `SeekBar` and `transportShortcuts` drive it as they drive any video, frame stepping\n// included). The viewer reads each new frame (`requestVideoFrameCallback`, else the element's events\n// and a frame loop while it plays) and uploads it: one texture upload per drawn frame, none for a\n// still picture, and no drawing at all while the viewer is off screen.\n// - **The view is controlled from outside** (`view`/`onViewChange`: yaw, pitch and field of view, in\n// degrees; `defaultView` to let it hold its own). It never animates: a view set from outside is\n// drawn at once, so an app's aim modes (follow a heading, a person, a point) are the app's own\n// function of time, and its pan on top is just another view.\n// - **From the keyboard and by touch, as well as the mouse**: arrow keys pan (Shift for more), `+` and\n// `-` zoom, `0` goes home; a drag pans (the picture follows the pointer), a wheel and a pinch zoom,\n// and a click that did not drag is `onPick` with the direction under it. A field-of-view slider is\n// an option. `maxPitch` stops the view short of the poles, where \"up\" stops meaning anything.\n// - **An overlay in the picture's coordinates**: `overlay` gets `project(yaw, pitch)` (the place in the\n// box, or null behind the camera), `unproject(x, y)` (the direction under a place) and the view, so\n// an app draws markers, aim dots and frame outlines in DOM, where they are text and buttons and take\n// focus. The same maths (projection.ts, with no GL) drives the shader.\n// - **Said in words.** The canvas is an image named by `label` and where it looks (\"Looking 40° right,\n// 5° up\"), always current; a polite status says it once the view has been still for a moment, never\n// per frame.\n// - **No WebGL2, no blank box**: the flat picture is drawn instead, cropped to the same window with the\n// same controls, and a line says so. `project` and `unproject` follow the flat drawing there, so\n// overlay markers still sit on what they mark.\n//\n// A GL context that is lost (a GPU reset, a tab in the background on a phone) is restored without the\n// app doing anything: the picture is sent again and the view redrawn.\n\nexport type PanoramaPictureSource = { image: string; video?: never } | { video: React.RefObject<HTMLVideoElement | null>; image?: never };\n\n/** What an overlay is given. */\nexport type PanoramaOverlayApi = {\n view: PanoramaView;\n size: PanoramaSize;\n /** Where the direction is in the box, or null behind the camera. */\n project: (yaw: number, pitch: number) => PanoramaPoint | null;\n /** The direction under a place in the box. */\n unproject: (x: number, y: number) => { yaw: number; pitch: number };\n /** The flat picture is being drawn (no WebGL2). */\n flat: boolean;\n};\n\nexport type PanoramaViewerProps = PanoramaPictureSource & {\n /** Names the viewer: \"360 view of the kitchen\". Required; the current direction is added to it. */\n label: string;\n /** The view, when the app holds it. */\n view?: PanoramaView;\n /** The view the viewer starts with, when it holds its own. Default straight ahead at 90°. */\n defaultView?: PanoramaView;\n /** The view changed (a drag, a key, a wheel, the slider). Not called for a view the app set. */\n onViewChange?: (view: PanoramaView) => void;\n /** A click that did not drag: the direction under it. */\n onPick?: (direction: { yaw: number; pitch: number }) => void;\n /** Highest and lowest look, degrees from the horizon. Default 85. */\n maxPitch?: number;\n /** Narrowest and widest field of view, degrees. Default 20 and 120. */\n minFov?: number;\n maxFov?: number;\n /** Zoom with the wheel. Default true. */\n wheelZoom?: boolean;\n /** Show a field-of-view slider under the picture. */\n fovSlider?: boolean;\n /** Markers and outlines drawn over the picture in its own coordinates. */\n overlay?: (api: PanoramaOverlayApi) => React.ReactNode;\n /** `\"flat\"` draws the flat picture even where WebGL2 is available (a low-power mode, or to see what a browser without it shows). Default `\"auto\"`. */\n mode?: \"auto\" | \"flat\";\n /** The shape of the box. Default 16/9. */\n aspect?: number | `${number}/${number}`;\n className?: string;\n};\n\nconst HOME: PanoramaView = { yaw: 0, pitch: 0, fov: 90 };\nconst STILL_MS = 600;\n\n/** A 360 picture or video as a window you pan and zoom, controlled from outside, with an overlay in the picture's coordinates. */\nexport function PanoramaViewer({ label, image, video, view: controlled, defaultView = HOME, onViewChange, onPick, maxPitch = 85, minFov = 20, maxFov = 120, wheelZoom = true, fovSlider = false, overlay, mode = \"auto\", aspect = \"16/9\", className }: PanoramaViewerProps) {\n const limits = React.useMemo(() => ({ maxPitch, minFov, maxFov }), [maxPitch, minFov, maxFov]);\n const [own, setOwn] = React.useState(() => clampView(defaultView, limits));\n const view = React.useMemo(() => clampView(controlled ?? own, limits), [controlled, own, limits]);\n const live = React.useRef({ view, controlled: controlled !== undefined, onViewChange, onPick, limits });\n live.current = { view, controlled: controlled !== undefined, onViewChange, onPick, limits };\n const change = React.useCallback((next: PanoramaView) => {\n const l = live.current;\n const clamped = clampView(next, l.limits);\n if (!l.controlled) setOwn(clamped);\n l.onViewChange?.(clamped);\n }, []);\n\n // The box, and the canvas in it.\n const box = React.useRef<HTMLDivElement>(null);\n const canvas = React.useRef<HTMLCanvasElement>(null);\n const [size, setSize] = React.useState<PanoramaSize>({ width: 0, height: 0 });\n React.useLayoutEffect(() => {\n const el = box.current;\n if (!el) return;\n const read = () => {\n const r = el.getBoundingClientRect();\n setSize((s) => (s.width === r.width && s.height === r.height ? s : { width: r.width, height: r.height }));\n };\n read();\n if (typeof ResizeObserver === \"undefined\") return;\n const ro = new ResizeObserver(read);\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n // The picture: a still is loaded once; a video is the app's element.\n const [still, setStill] = React.useState<HTMLImageElement | null>(null);\n React.useEffect(() => {\n if (image === undefined) {\n setStill(null);\n return;\n }\n const img = new Image();\n img.crossOrigin = \"anonymous\";\n let cancelled = false;\n img.onload = () => !cancelled && setStill(img);\n img.src = image;\n return () => {\n cancelled = true;\n img.onload = null;\n };\n }, [image]);\n\n // Drawing: only when something changed, and only while on screen.\n const { ref: visibleRef, inView } = useInView({ unsupported: true });\n // One stable callback: an inline one is called with null and the element on every render, and `useInView` would watch it come and go.\n const boxRef = React.useCallback(\n (el: HTMLDivElement | null) => {\n box.current = el;\n visibleRef(el);\n },\n [visibleRef],\n );\n const renderer = React.useRef<PanoramaRenderer | null>(null);\n const [flat, setFlat] = React.useState(false);\n const frame = React.useRef(0);\n const dirtyPicture = React.useRef(true);\n const current = React.useRef({ size, inView, flat });\n current.current = { size, inView, flat };\n\n const pictureNow = React.useCallback((): PanoramaPicture | null => {\n const v = video?.current;\n if (v) return v.readyState >= 2 && v.videoWidth > 0 ? v : null;\n return still;\n }, [video, still]);\n\n const paint = React.useCallback(() => {\n frame.current = 0;\n const c = canvas.current;\n const { size: s, inView: visible } = current.current;\n if (!c || !visible || s.width === 0 || s.height === 0) return;\n const picture = pictureNow();\n const dpr = Math.min(typeof devicePixelRatio === \"number\" ? devicePixelRatio : 1, 2);\n const w = Math.max(1, Math.round(s.width * dpr));\n const h = Math.max(1, Math.round(s.height * dpr));\n if (current.current.flat) {\n const ctx = c.getContext(\"2d\");\n if (!ctx) return;\n if (c.width !== w || c.height !== h) {\n c.width = w;\n c.height = h;\n }\n ctx.fillStyle = \"#000\";\n ctx.fillRect(0, 0, w, h);\n if (!picture) return;\n const sw = (picture as HTMLImageElement).naturalWidth || (picture as HTMLVideoElement).videoWidth || c.width;\n const sh = (picture as HTMLImageElement).naturalHeight || (picture as HTMLVideoElement).videoHeight || c.height;\n const v = live.current.view;\n const wide = (v.fov / 360) * sw;\n const tall = ((v.fov * (s.height / s.width)) / 180) * sh;\n const left = ((v.yaw - v.fov / 2 + 180) / 360) * sw;\n const top = ((90 - v.pitch) / 180) * sh - tall / 2;\n // Across the seam the window is two pieces of the picture side by side.\n for (const shift of [-sw, 0, sw]) {\n const a = Math.max(left + shift, 0);\n const b = Math.min(left + shift + wide, sw);\n if (b > a) ctx.drawImage(picture as CanvasImageSource, a, Math.max(top, 0), b - a, Math.min(tall, sh), ((a - (left + shift)) / wide) * w, 0, ((b - a) / wide) * w, h);\n }\n return;\n }\n const r = renderer.current;\n if (!r) return;\n if (picture && dirtyPicture.current) {\n r.upload(picture);\n dirtyPicture.current = false;\n }\n r.draw(live.current.view, w, h);\n }, [pictureNow]);\n const schedule = React.useCallback(() => {\n if (frame.current === 0) frame.current = requestAnimationFrame(paint);\n }, [paint]);\n\n // The renderer: made once, restored if the context is lost, and the flat picture if there is none.\n React.useEffect(() => {\n const c = canvas.current;\n if (!c) return;\n const make = () => {\n renderer.current?.dispose();\n renderer.current = mode === \"flat\" ? null : createRenderer(c);\n setFlat(renderer.current === null);\n dirtyPicture.current = true;\n schedule();\n };\n make();\n const lost = (e: Event) => {\n e.preventDefault();\n renderer.current = null;\n };\n c.addEventListener(\"webglcontextlost\", lost);\n c.addEventListener(\"webglcontextrestored\", make);\n return () => {\n c.removeEventListener(\"webglcontextlost\", lost);\n c.removeEventListener(\"webglcontextrestored\", make);\n renderer.current?.dispose();\n renderer.current = null;\n if (frame.current) cancelAnimationFrame(frame.current);\n frame.current = 0;\n };\n }, [schedule, mode]);\n\n // A new still, a new size, a new view, or coming into view: draw.\n React.useEffect(() => {\n dirtyPicture.current = true;\n }, [still]);\n React.useEffect(() => {\n schedule();\n }, [schedule, view.yaw, view.pitch, view.fov, size.width, size.height, still, inView, flat]);\n\n // A video: each new frame is one upload and one draw.\n React.useEffect(() => {\n const v = video?.current;\n if (!v || !inView) return;\n let stopped = false;\n let handle = 0;\n const onFrame = () => {\n if (stopped) return;\n dirtyPicture.current = true;\n schedule();\n handle = v.requestVideoFrameCallback(onFrame);\n };\n if (typeof v.requestVideoFrameCallback === \"function\") {\n handle = v.requestVideoFrameCallback(onFrame);\n return () => {\n stopped = true;\n v.cancelVideoFrameCallback?.(handle);\n };\n }\n // No frame callback: the element's own events, and a frame loop while it plays.\n const touch = () => {\n dirtyPicture.current = true;\n schedule();\n };\n const events = [\"loadeddata\", \"seeked\", \"timeupdate\", \"play\", \"pause\"] as const;\n for (const e of events) v.addEventListener(e, touch);\n let loop = 0;\n const tick = () => {\n if (!v.paused) touch();\n loop = requestAnimationFrame(tick);\n };\n loop = requestAnimationFrame(tick);\n return () => {\n for (const e of events) v.removeEventListener(e, touch);\n cancelAnimationFrame(loop);\n };\n }, [video, inView, schedule]);\n\n // Pointer: drag turns the view with the pointer, two pointers pinch, a click that did not drag picks.\n const pointers = React.useRef(new Map<number, { x: number; y: number }>());\n const gesture = React.useRef<{ moved: boolean; pinch: number | null; start: { x: number; y: number } } | null>(null);\n const hostRect = () => box.current!.getBoundingClientRect();\n const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n if (e.button !== 0 && e.pointerType === \"mouse\") return;\n pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });\n e.currentTarget.setPointerCapture?.(e.pointerId);\n const [first, second] = [...pointers.current.values()];\n const distance = second ? Math.hypot(first.x - second.x, first.y - second.y) : null;\n gesture.current = { moved: false, pinch: distance, start: { x: e.clientX, y: e.clientY } };\n e.currentTarget.focus({ preventScroll: true });\n };\n const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n const last = pointers.current.get(e.pointerId);\n if (!last || !gesture.current) return;\n const now = { x: e.clientX, y: e.clientY };\n pointers.current.set(e.pointerId, now);\n const v = live.current.view;\n const s = { width: hostRect().width, height: hostRect().height };\n if (pointers.current.size === 2) {\n const [a, b] = [...pointers.current.values()];\n const d = Math.hypot(a.x - b.x, a.y - b.y);\n if (gesture.current.pinch && d > 0) change({ ...v, fov: v.fov * (gesture.current.pinch / d) });\n gesture.current.pinch = d;\n gesture.current.moved = true;\n return;\n }\n if (Math.hypot(now.x - gesture.current.start.x, now.y - gesture.current.start.y) > 4) gesture.current.moved = true;\n if (!gesture.current.moved) return;\n // The picture follows the pointer: dragging right turns the view left.\n const per = degreesPerPixel(v, s);\n change({ ...v, yaw: v.yaw - (now.x - last.x) * per, pitch: v.pitch + (now.y - last.y) * per });\n };\n const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {\n const g = gesture.current;\n pointers.current.delete(e.pointerId);\n if (pointers.current.size === 0) {\n gesture.current = null;\n if (g && !g.moved && live.current.onPick) {\n const r = hostRect();\n const s = { width: r.width, height: r.height };\n const x = e.clientX - r.left;\n const y = e.clientY - r.top;\n live.current.onPick(current.current.flat ? unprojectFlat(live.current.view, s, x, y) : unproject(live.current.view, s, x, y));\n }\n } else if (g) g.pinch = null;\n };\n\n // The wheel zooms; native, because React's wheel listener is passive and the page must not scroll too.\n React.useEffect(() => {\n const el = box.current;\n if (!el || !wheelZoom) return;\n const onWheel = (e: WheelEvent) => {\n e.preventDefault();\n const v = live.current.view;\n change({ ...v, fov: v.fov * Math.exp(e.deltaY * 0.0015) });\n };\n el.addEventListener(\"wheel\", onWheel, { passive: false });\n return () => el.removeEventListener(\"wheel\", onWheel);\n }, [wheelZoom, change]);\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n const v = live.current.view;\n const turn = (v.fov / 12) * (e.shiftKey ? 3 : 1);\n if (e.key === \"ArrowLeft\") change({ ...v, yaw: v.yaw - turn });\n else if (e.key === \"ArrowRight\") change({ ...v, yaw: v.yaw + turn });\n else if (e.key === \"ArrowUp\") change({ ...v, pitch: v.pitch + turn });\n else if (e.key === \"ArrowDown\") change({ ...v, pitch: v.pitch - turn });\n else if (e.key === \"+\" || e.key === \"=\") change({ ...v, fov: v.fov * 0.8 });\n else if (e.key === \"-\" || e.key === \"_\") change({ ...v, fov: v.fov * 1.25 });\n else if (e.key === \"0\") change(defaultView);\n else return;\n e.preventDefault();\n };\n\n // Said in words: always on the picture; politely once the view has been still for a moment.\n const direction = describeView(view);\n const [said, setSaid] = React.useState(\"\");\n const first = React.useRef(true);\n React.useEffect(() => {\n if (first.current) {\n first.current = false;\n return;\n }\n const t = setTimeout(() => setSaid(`${direction}, field of view ${Math.round(view.fov)}°`), STILL_MS);\n return () => clearTimeout(t);\n }, [direction, view.fov]);\n\n const api: PanoramaOverlayApi = {\n view,\n size,\n flat,\n project: (yaw, pitch) => (flat ? projectFlat(view, size, yaw, pitch) : project(view, size, yaw, pitch)),\n unproject: (x, y) => (flat ? unprojectFlat(view, size, x, y) : unproject(view, size, x, y)),\n };\n const slider = fovSlider ? <Slider aria-label=\"Field of view\" value={Math.round(view.fov)} onChange={(fov) => change({ ...view, fov })} min={minFov} max={maxFov} step={1} unit=\"degree\" /> : null;\n\n return (\n <div className={cn(\"grid min-w-0 gap-2\", className)}>\n <div\n ref={boxRef}\n role=\"group\"\n aria-label={label}\n aria-describedby={undefined}\n tabIndex={0}\n onKeyDown={onKeyDown}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onPointerCancel={onPointerUp}\n className=\"relative w-full cursor-grab touch-none overflow-hidden rounded-surface bg-surface-sunken select-none active:cursor-grabbing\"\n style={{ aspectRatio: aspect }}\n >\n <canvas key={mode === \"flat\" ? \"2d\" : \"gl\"} ref={canvas} role=\"img\" aria-label={`${label}. ${direction}, field of view ${Math.round(view.fov)}°`} className=\"absolute inset-0 size-full\" />\n {overlay && size.width > 0 && <div className=\"pointer-events-none absolute inset-0\">{overlay(api)}</div>}\n </div>\n {flat && <p className=\"type-body-sm text-muted-foreground\">This browser cannot draw the 360 view, so the flat picture is shown. The controls work the same.</p>}\n {slider}\n <VisuallyHidden>\n <span role=\"status\">{said}</span>\n </VisuallyHidden>\n </div>\n );\n}\n"],"mappings":";;;;;;AAcA,IAAM,SAAS;;;;AAKf,IAAM,WAAW;;;;;;;;;;;;;;;;;;;;AAoCjB,SAAgB,eAAe,QAAoD;CACjF,MAAM,KAAK,OAAO,WAAW,UAAU;EAAE,WAAW;EAAO,uBAAuB;EAAO,OAAO;CAAM,CAAC;CACvG,IAAI,CAAC,IAAI,OAAO;CAChB,MAAM,WAAW,MAAc,WAAmB;EAChD,MAAM,SAAS,GAAG,aAAa,IAAI;EACnC,GAAG,aAAa,QAAQ,MAAM;EAC9B,GAAG,cAAc,MAAM;EACvB,IAAI,CAAC,GAAG,mBAAmB,QAAQ,GAAG,cAAc,GAAG;GACrD,MAAM,MAAM,GAAG,iBAAiB,MAAM;GACtC,GAAG,aAAa,MAAM;GACtB,MAAM,I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8B,GAA7K,SAAS,SAAS,OAAO,IAAoJ,GACzL,WAAW,KAAK,QAAQ,KAAK,oBAAC,OAAD;KAAK,WAAU;KAAwC,UAAA,QAAQ,GAAG;IAAO,CAAA,CACpG;;GACJ,QAAQ,oBAAC,KAAD;IAAG,WAAU;IAAqC,UAAA;GAAmG,CAAA;GAC7J;GACD,oBAAC,gBAAD,EAAA,UACE,oBAAC,QAAD;IAAM,MAAK;IAAU,UAAA;GAAW,CAAA,EAClB,CAAA;EACb;;AAET"}
1
+ {"version":3,"file":"panorama.js","names":[],"sources":["../src/panorama/gl.ts","../src/panorama/projection.ts","../src/panorama/panorama-viewer.tsx"],"sourcesContent":["import type { PanoramaView } from \"./projection\";\n\n// The WebGL2 side of `PanoramaViewer` (strata-react issue #178): one full-screen triangle, and a\n// fragment shader that does for every pixel what `project`/`unproject` do for one (projection.ts holds\n// the same formulas, and tests hold the two to each other): build the ray through the pixel from the\n// view's yaw, pitch and field of view, turn it into longitude and latitude, and read the equirectangular\n// texture there. The texture repeats across the seam (longitude) and clamps at the poles. No mipmaps:\n// the longitude wraps with an `atan`, whose jump at the seam would make a mipmapped lookup draw a line\n// one pixel wide down it; plain linear filtering draws none.\n//\n// Cost, as documented for apps: one texture upload per *drawn video frame* (`texImage2D` of the\n// `<video>`), none for a still picture (uploaded once), and a draw only when the view, the size or the\n// picture changed, never on a timer.\n\nconst VERTEX = `#version 300 es\nin vec2 aPos;\nout vec2 vNdc;\nvoid main() { vNdc = aPos; gl_Position = vec4(aPos, 0.0, 1.0); }`;\n\nconst FRAGMENT = `#version 300 es\nprecision highp float;\nin vec2 vNdc;\nout vec4 outColor;\nuniform sampler2D uPicture;\nuniform float uYaw;\nuniform float uPitch;\nuniform float uTanHalf;\nuniform float uAspect;\nconst float PI = 3.14159265358979;\nvoid main() {\n vec3 forward = vec3(cos(uPitch) * sin(uYaw), sin(uPitch), cos(uPitch) * cos(uYaw));\n vec3 right = vec3(cos(uYaw), 0.0, -sin(uYaw));\n vec3 up = vec3(-sin(uPitch) * sin(uYaw), cos(uPitch), -sin(uPitch) * cos(uYaw));\n vec3 ray = normalize(forward + vNdc.x * uTanHalf * right + vNdc.y * (uTanHalf / uAspect) * up);\n float lon = atan(ray.x, ray.z);\n float lat = asin(clamp(ray.y, -1.0, 1.0));\n outColor = texture(uPicture, vec2(lon / (2.0 * PI) + 0.5, 0.5 - lat / PI));\n}`;\n\n/** Anything WebGL can take as a texture: a decoded image or a playing video. */\nexport type PanoramaPicture = HTMLImageElement | HTMLVideoElement | ImageBitmap | HTMLCanvasElement;\n\n/** What draws the window. */\nexport type PanoramaRenderer = {\n /** Sends the picture to the GPU. Call when the picture is a new one (an image) or a new frame (a video). */\n upload: (picture: PanoramaPicture) => void;\n /** Draws the view into a canvas of `width` by `height` device pixels. */\n draw: (view: PanoramaView, width: number, height: number) => void;\n /** How many times `upload` has sent a picture (a video frame, an image), for the documented cost and for tests. */\n uploads: () => number;\n /** Frees the GPU objects. */\n dispose: () => void;\n};\n\n/** Makes a renderer on `canvas`, or null where WebGL2 is not available (the viewer then shows the flat picture). */\nexport function createRenderer(canvas: HTMLCanvasElement): PanoramaRenderer | null {\n const gl = canvas.getContext(\"webgl2\", { antialias: false, preserveDrawingBuffer: false, alpha: false }) as WebGL2RenderingContext | null;\n if (!gl) return null;\n const compile = (type: number, source: string) => {\n const shader = gl.createShader(type)!;\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const log = gl.getShaderInfoLog(shader);\n gl.deleteShader(shader);\n throw new Error(`Panorama shader: ${log}`);\n }\n return shader;\n };\n let program: WebGLProgram;\n try {\n program = gl.createProgram()!;\n gl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX));\n gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAGMENT));\n gl.linkProgram(program);\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(`Panorama program: ${gl.getProgramInfoLog(program)}`);\n } catch {\n return null;\n }\n gl.useProgram(program);\n const buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n // One triangle that covers the screen.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n const position = gl.getAttribLocation(program, \"aPos\");\n gl.enableVertexAttribArray(position);\n gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n const uniforms = {\n yaw: gl.getUniformLocation(program, \"uYaw\"),\n pitch: gl.getUniformLocation(program, \"uPitch\"),\n tanHalf: gl.getUniformLocation(program, \"uTanHalf\"),\n aspect: gl.getUniformLocation(program, \"uAspect\"),\n picture: gl.getUniformLocation(program, \"uPicture\"),\n };\n gl.uniform1i(uniforms.picture, 0);\n let uploaded = 0;\n let has = false;\n\n return {\n upload(picture) {\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, picture);\n uploaded++;\n has = true;\n },\n draw(view, width, height) {\n if (canvas.width !== width || canvas.height !== height) {\n canvas.width = width;\n canvas.height = height;\n }\n gl.viewport(0, 0, width, height);\n if (!has) {\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n return;\n }\n const rad = Math.PI / 180;\n gl.uniform1f(uniforms.yaw, view.yaw * rad);\n gl.uniform1f(uniforms.pitch, view.pitch * rad);\n gl.uniform1f(uniforms.tanHalf, Math.tan((view.fov * rad) / 2));\n gl.uniform1f(uniforms.aspect, width / height);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n },\n uploads: () => uploaded,\n dispose() {\n gl.deleteTexture(texture);\n gl.deleteBuffer(buffer);\n gl.deleteProgram(program);\n },\n };\n}\n","// The geometry of `PanoramaViewer` (strata-react issue #178), with no DOM and no GL so every case\n// is tested on its own and the GL shader is held to the same numbers. A 360 picture is\n// *equirectangular*: longitude across, latitude down. The viewer shows a *rectilinear* window into the\n// sphere, as a camera does: straight lines stay straight, and the width of what is seen is the\n// horizontal field of view `fov`.\n//\n// Angles are degrees, because that is what an app and a person talk in. `yaw` is the heading: 0 is the\n// middle of the picture, positive to the right, wrapped to (-180, 180]. `pitch` is the elevation:\n// 0 is the horizon, positive up, limited to +-90 (the apps' own `maxPitch` is kept below that). A\n// direction in the world is a unit vector `(cos p sin y, sin p, cos p cos y)`; the camera's forward,\n// right and up are built from the view's yaw and pitch (no roll: upright footage). A point is drawn\n// where its direction crosses the image plane, `fpx = (width / 2) / tan(fov / 2)` pixels from the camera.\n\n/** Where the window looks and how wide it sees, degrees. */\nexport type PanoramaView = { yaw: number; pitch: number; fov: number };\n\n/** The size of the picture box in CSS pixels. */\nexport type PanoramaSize = { width: number; height: number };\n\n/** A place in the box. `inside` says it is within the box; a point behind the camera has none (`project` returns null). */\nexport type PanoramaPoint = { x: number; y: number; inside: boolean };\n\nconst RAD = Math.PI / 180;\nconst DEG = 180 / Math.PI;\n\n/** Wraps a heading to (-180, 180]. */\nexport function wrapYaw(yaw: number): number {\n const w = ((((yaw + 180) % 360) + 360) % 360) - 180;\n return w === -180 ? 180 : w;\n}\n\n/** The smallest signed turn from heading `from` to heading `to`, in (-180, 180]. Use it for a difference of headings, never `to - from`. */\nexport const yawDelta = (from: number, to: number) => wrapYaw(to - from);\n\n/** Keeps a view inside its limits: heading wrapped, pitch within +-`maxPitch`, field of view within `minFov` to `maxFov`. */\nexport function clampView(view: PanoramaView, { maxPitch = 85, minFov = 20, maxFov = 120 }: { maxPitch?: number; minFov?: number; maxFov?: number } = {}): PanoramaView {\n return { yaw: wrapYaw(view.yaw), pitch: Math.min(Math.max(view.pitch, -maxPitch), maxPitch), fov: Math.min(Math.max(view.fov, minFov), maxFov) };\n}\n\nconst focal = (view: PanoramaView, size: PanoramaSize) => size.width / 2 / Math.tan((view.fov * RAD) / 2);\n\nfunction basis(view: PanoramaView) {\n const y = view.yaw * RAD;\n const p = view.pitch * RAD;\n const forward = [Math.cos(p) * Math.sin(y), Math.sin(p), Math.cos(p) * Math.cos(y)] as const;\n const right = [Math.cos(y), 0, -Math.sin(y)] as const;\n const up = [-Math.sin(p) * Math.sin(y), Math.cos(p), -Math.sin(p) * Math.cos(y)] as const;\n return { forward, right, up };\n}\nconst dot = (a: readonly number[], b: readonly number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n\n/** Where the direction (`yaw`, `pitch`) is drawn in the box for `view`, or null when it is behind the camera. */\nexport function project(view: PanoramaView, size: PanoramaSize, yaw: number, pitch: number): PanoramaPoint | null {\n const { forward, right, up } = basis(view);\n const p = pitch * RAD;\n const y = yaw * RAD;\n const d = [Math.cos(p) * Math.sin(y), Math.sin(p), Math.cos(p) * Math.cos(y)] as const;\n const z = dot(d, forward);\n if (z <= 1e-9) return null;\n const f = focal(view, size);\n const x = size.width / 2 + (f * dot(d, right)) / z;\n const yy = size.height / 2 - (f * dot(d, up)) / z;\n return { x, y: yy, inside: x >= 0 && x <= size.width && yy >= 0 && yy <= size.height };\n}\n\n/** The direction under a point of the box for `view`: the inverse of `project`. */\nexport function unproject(view: PanoramaView, size: PanoramaSize, x: number, y: number): { yaw: number; pitch: number } {\n const { forward, right, up } = basis(view);\n const f = focal(view, size);\n const a = (x - size.width / 2) / f;\n const b = -(y - size.height / 2) / f;\n const v = [forward[0] + a * right[0] + b * up[0], forward[1] + a * right[1] + b * up[1], forward[2] + a * right[2] + b * up[2]] as const;\n const length = Math.hypot(v[0], v[1], v[2]);\n return { yaw: wrapYaw(Math.atan2(v[0], v[2]) * DEG), pitch: Math.asin(Math.min(Math.max(v[1] / length, -1), 1)) * DEG };\n}\n\n/** Pixels to degrees at the middle of the box: how far a drag of `px` turns the view. */\nexport const degreesPerPixel = (view: PanoramaView, size: PanoramaSize) => (Math.atan(1 / focal(view, size)) * DEG);\n\n/** The flat picture's own mapping, for the fallback with no WebGL: longitude and latitude are straight across and down, the visible rectangle is `fov` wide and as tall as the box's shape makes it. */\nexport function projectFlat(view: PanoramaView, size: PanoramaSize, yaw: number, pitch: number): PanoramaPoint {\n const perPixel = view.fov / size.width;\n const x = size.width / 2 + yawDelta(view.yaw, yaw) / perPixel;\n const y = size.height / 2 - (pitch - view.pitch) / perPixel;\n return { x, y, inside: x >= 0 && x <= size.width && y >= 0 && y <= size.height };\n}\n\n/** The inverse of `projectFlat`. */\nexport function unprojectFlat(view: PanoramaView, size: PanoramaSize, x: number, y: number): { yaw: number; pitch: number } {\n const perPixel = view.fov / size.width;\n return { yaw: wrapYaw(view.yaw + (x - size.width / 2) * perPixel), pitch: Math.min(Math.max(view.pitch - (y - size.height / 2) * perPixel, -90), 90) };\n}\n\n/** The direction in words: \"Looking 40° right, 5° up\", \"Looking straight ahead\". Whole degrees; nothing is said for less than half a degree. */\nexport function describeView(view: Pick<PanoramaView, \"yaw\" | \"pitch\">): string {\n const yaw = Math.round(wrapYaw(view.yaw));\n const pitch = Math.round(view.pitch);\n const side = yaw === 0 ? \"\" : yaw === 180 ? \"directly behind\" : `${Math.abs(yaw)}° ${yaw > 0 ? \"right\" : \"left\"}`;\n const tilt = pitch === 0 ? \"\" : `${Math.abs(pitch)}° ${pitch > 0 ? \"up\" : \"down\"}`;\n const parts = [side, tilt].filter(Boolean);\n return parts.length === 0 ? \"Looking straight ahead\" : `Looking ${parts.join(\", \")}`;\n}\n","import * as React from \"react\";\nimport { VisuallyHidden } from \"react-aria\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\nimport { Slider } from \"../components/value-controls\";\nimport { createRenderer, type PanoramaPicture, type PanoramaRenderer } from \"./gl\";\nimport { clampView, degreesPerPixel, describeView, project, projectFlat, unproject, unprojectFlat, type PanoramaPoint, type PanoramaSize, type PanoramaView } from \"./projection\";\n\n// A 360 picture or video as a window you pan and zoom (strata-react issue #178, from strata-360, which\n// drew equirectangular footage with a hand-written WebGL2 shader and its own pointer, transport and\n// frame stepping). This is its own entry (`strata-react/panorama`) so an app that never shows 360 ships\n// no GL code. Nothing else in the package is as far from React Aria's world, so the choices:\n//\n// - **The picture is a canvas, the controls are keys and pointers on a group.** React Aria has no 360\n// view, so the viewer is ours; what it can give, it gives: the field-of-view slider is Strata's\n// `Slider` (React Aria's), and the pointer handling is plain pointer events (React Aria's `usePress`\n// is for a press, not a drag that turns a sphere; checked in its props: it reports a press and its\n// start and end, with no movement).\n// - **It does not own the video.** `video` is a ref to an element the app owns (`useMediaElement`,\n// `Transport`, `SeekBar` and `transportShortcuts` drive it as they drive any video, frame stepping\n// included). The viewer reads each new frame (`requestVideoFrameCallback`, else the element's events\n// and a frame loop while it plays) and uploads it: one texture upload per drawn frame, none for a\n// still picture, and no drawing at all while the viewer is off screen.\n// - **The view is controlled from outside** (`view`/`onViewChange`: yaw, pitch and field of view, in\n// degrees; `defaultView` to let it hold its own). It never animates: a view set from outside is\n// drawn at once, so an app's aim modes (follow a heading, a person, a point) are the app's own\n// function of time, and its pan on top is just another view.\n// - **From the keyboard and by touch, as well as the mouse**: arrow keys pan (Shift for more), `+` and\n// `-` zoom, `0` goes home; a drag pans (the picture follows the pointer), a wheel and a pinch zoom,\n// and a click that did not drag is `onPick` with the direction under it. A field-of-view slider is\n// an option. `maxPitch` stops the view short of the poles, where \"up\" stops meaning anything.\n// - **An overlay in the picture's coordinates**: `overlay` gets `project(yaw, pitch)` (the place in the\n// box, or null behind the camera), `unproject(x, y)` (the direction under a place) and the view, so\n// an app draws markers, aim dots and frame outlines in DOM, where they are text and buttons and take\n// focus. The same maths (projection.ts, with no GL) drives the shader.\n// - **Said in words.** The canvas is an image named by `label` and where it looks (\"Looking 40° right,\n// 5° up\"), always current; a polite status says it once the view has been still for a moment, never\n// per frame.\n// - **No WebGL2, no blank box**: the flat picture is drawn instead, cropped to the same window with the\n// same controls, and a line says so. `project` and `unproject` follow the flat drawing there, so\n// overlay markers still sit on what they mark.\n//\n// A GL context that is lost (a GPU reset, a tab in the background on a phone) is restored without the\n// app doing anything: the picture is sent again and the view redrawn.\n\nexport type PanoramaPictureSource = { image: string; video?: never } | { video: React.RefObject<HTMLVideoElement | null>; image?: never };\n\n/** What an overlay is given. */\nexport type PanoramaOverlayApi = {\n view: PanoramaView;\n size: PanoramaSize;\n /** Where the direction is in the box, or null behind the camera. */\n project: (yaw: number, pitch: number) => PanoramaPoint | null;\n /** The direction under a place in the box. */\n unproject: (x: number, y: number) => { yaw: number; pitch: number };\n /** The flat picture is being drawn (no WebGL2). */\n flat: boolean;\n};\n\nexport type PanoramaViewerProps = PanoramaPictureSource & {\n /** Names the viewer: \"360 view of the kitchen\". Required; the current direction is added to it. */\n label: string;\n /** The view, when the app holds it. */\n view?: PanoramaView;\n /** The view the viewer starts with, when it holds its own. Default straight ahead at 90°. */\n defaultView?: PanoramaView;\n /** The view changed (a drag, a key, a wheel, the slider). Not called for a view the app set. */\n onViewChange?: (view: PanoramaView) => void;\n /** A click that did not drag: the direction under it. */\n onPick?: (direction: { yaw: number; pitch: number }) => void;\n /** Highest and lowest look, degrees from the horizon. Default 85. */\n maxPitch?: number;\n /** Narrowest and widest field of view, degrees. Default 20 and 120. */\n minFov?: number;\n maxFov?: number;\n /** Zoom with the wheel. Default true. */\n wheelZoom?: boolean;\n /** Show a field-of-view slider under the picture. */\n fovSlider?: boolean;\n /** Markers and outlines drawn over the picture in its own coordinates. */\n overlay?: (api: PanoramaOverlayApi) => React.ReactNode;\n /** `\"flat\"` draws the flat picture even where WebGL2 is available (a low-power mode, or to see what a browser without it shows). Default `\"auto\"`. */\n mode?: \"auto\" | \"flat\";\n /** The shape of the box. Default 16/9. */\n aspect?: number | `${number}/${number}`;\n className?: string;\n};\n\nconst HOME: PanoramaView = { yaw: 0, pitch: 0, fov: 90 };\nconst STILL_MS = 600;\n\n/** A 360 picture or video as a window you pan and zoom, controlled from outside, with an overlay in the picture's coordinates. */\nexport function PanoramaViewer({ label, image, video, view: controlled, defaultView = HOME, onViewChange, onPick, maxPitch = 85, minFov = 20, maxFov = 120, wheelZoom = true, fovSlider = false, overlay, mode = \"auto\", aspect = \"16/9\", className }: PanoramaViewerProps) {\n const limits = React.useMemo(() => ({ maxPitch, minFov, maxFov }), [maxPitch, minFov, maxFov]);\n const [own, setOwn] = React.useState(() => clampView(defaultView, limits));\n const view = React.useMemo(() => clampView(controlled ?? own, limits), [controlled, own, limits]);\n const live = React.useRef({ view, controlled: controlled !== undefined, onViewChange, onPick, limits });\n live.current = { view, controlled: controlled !== undefined, onViewChange, onPick, limits };\n const change = React.useCallback((next: PanoramaView) => {\n const l = live.current;\n const clamped = clampView(next, l.limits);\n if (!l.controlled) setOwn(clamped);\n l.onViewChange?.(clamped);\n }, []);\n\n // The box, and the canvas in it.\n const box = React.useRef<HTMLDivElement>(null);\n const canvas = React.useRef<HTMLCanvasElement>(null);\n const [size, setSize] = React.useState<PanoramaSize>({ width: 0, height: 0 });\n React.useLayoutEffect(() => {\n const el = box.current;\n if (!el) return;\n const read = () => {\n const r = el.getBoundingClientRect();\n setSize((s) => (s.width === r.width && s.height === r.height ? s : { width: r.width, height: r.height }));\n };\n read();\n if (typeof ResizeObserver === \"undefined\") return;\n const ro = new ResizeObserver(read);\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n // The picture: a still is loaded once; a video is the app's element.\n const [still, setStill] = React.useState<HTMLImageElement | null>(null);\n React.useEffect(() => {\n if (image === undefined) {\n setStill(null);\n return;\n }\n const img = new Image();\n img.crossOrigin = \"anonymous\";\n let cancelled = false;\n img.onload = () => !cancelled && setStill(img);\n img.src = image;\n return () => {\n cancelled = true;\n img.onload = null;\n };\n }, [image]);\n\n // Drawing: only when something changed, and only while on screen.\n const { ref: visibleRef, inView } = useInView({ unsupported: true });\n // One stable callback: an inline one is called with null and the element on every render, and `useInView` would watch it come and go.\n const boxRef = React.useCallback(\n (el: HTMLDivElement | null) => {\n box.current = el;\n visibleRef(el);\n },\n [visibleRef],\n );\n const renderer = React.useRef<PanoramaRenderer | null>(null);\n const [flat, setFlat] = React.useState(false);\n const frame = React.useRef(0);\n const dirtyPicture = React.useRef(true);\n const current = React.useRef({ size, inView, flat });\n current.current = { size, inView, flat };\n\n const pictureNow = React.useCallback((): PanoramaPicture | null => {\n const v = video?.current;\n if (v) return v.readyState >= 2 && v.videoWidth > 0 ? v : null;\n return still;\n }, [video, still]);\n\n const paint = React.useCallback(() => {\n frame.current = 0;\n const c = canvas.current;\n const { size: s, inView: visible } = current.current;\n if (!c || !visible || s.width === 0 || s.height === 0) return;\n const picture = pictureNow();\n const dpr = Math.min(typeof devicePixelRatio === \"number\" ? devicePixelRatio : 1, 2);\n const w = Math.max(1, Math.round(s.width * dpr));\n const h = Math.max(1, Math.round(s.height * dpr));\n if (current.current.flat) {\n const ctx = c.getContext(\"2d\");\n if (!ctx) return;\n if (c.width !== w || c.height !== h) {\n c.width = w;\n c.height = h;\n }\n ctx.fillStyle = \"#000\";\n ctx.fillRect(0, 0, w, h);\n if (!picture) return;\n const sw = (picture as HTMLImageElement).naturalWidth || (picture as HTMLVideoElement).videoWidth || c.width;\n const sh = (picture as HTMLImageElement).naturalHeight || (picture as HTMLVideoElement).videoHeight || c.height;\n const v = live.current.view;\n const wide = (v.fov / 360) * sw;\n const tall = ((v.fov * (s.height / s.width)) / 180) * sh;\n const left = ((v.yaw - v.fov / 2 + 180) / 360) * sw;\n const top = ((90 - v.pitch) / 180) * sh - tall / 2;\n // Across the seam the window is two pieces of the picture side by side.\n for (const shift of [-sw, 0, sw]) {\n const a = Math.max(left + shift, 0);\n const b = Math.min(left + shift + wide, sw);\n if (b > a) ctx.drawImage(picture as CanvasImageSource, a, Math.max(top, 0), b - a, Math.min(tall, sh), ((a - (left + shift)) / wide) * w, 0, ((b - a) / wide) * w, h);\n }\n return;\n }\n const r = renderer.current;\n if (!r) return;\n if (picture && dirtyPicture.current) {\n r.upload(picture);\n dirtyPicture.current = false;\n }\n r.draw(live.current.view, w, h);\n }, [pictureNow]);\n const schedule = React.useCallback(() => {\n if (frame.current === 0) frame.current = requestAnimationFrame(paint);\n }, [paint]);\n\n // The renderer: made once, restored if the context is lost, and the flat picture if there is none.\n React.useEffect(() => {\n const c = canvas.current;\n if (!c) return;\n const make = () => {\n renderer.current?.dispose();\n renderer.current = mode === \"flat\" ? null : createRenderer(c);\n setFlat(renderer.current === null);\n dirtyPicture.current = true;\n schedule();\n };\n make();\n const lost = (e: Event) => {\n e.preventDefault();\n renderer.current = null;\n };\n c.addEventListener(\"webglcontextlost\", lost);\n c.addEventListener(\"webglcontextrestored\", make);\n return () => {\n c.removeEventListener(\"webglcontextlost\", lost);\n c.removeEventListener(\"webglcontextrestored\", make);\n renderer.current?.dispose();\n renderer.current = null;\n if (frame.current) cancelAnimationFrame(frame.current);\n frame.current = 0;\n };\n }, [schedule, mode]);\n\n // A new still, a new size, a new view, or coming into view: draw.\n React.useEffect(() => {\n dirtyPicture.current = true;\n }, [still]);\n React.useEffect(() => {\n schedule();\n }, [schedule, view.yaw, view.pitch, view.fov, size.width, size.height, still, inView, flat]);\n\n // A video: each new frame is one upload and one draw.\n React.useEffect(() => {\n const v = video?.current;\n if (!v || !inView) return;\n let stopped = false;\n let handle = 0;\n const onFrame = () => {\n if (stopped) return;\n dirtyPicture.current = true;\n schedule();\n handle = v.requestVideoFrameCallback(onFrame);\n };\n if (typeof v.requestVideoFrameCallback === \"function\") {\n handle = v.requestVideoFrameCallback(onFrame);\n return () => {\n stopped = true;\n v.cancelVideoFrameCallback?.(handle);\n };\n }\n // No frame callback: the element's own events, and a frame loop while it plays.\n const touch = () => {\n dirtyPicture.current = true;\n schedule();\n };\n const events = [\"loadeddata\", \"seeked\", \"timeupdate\", \"play\", \"pause\"] as const;\n for (const e of events) v.addEventListener(e, touch);\n let loop = 0;\n const tick = () => {\n if (!v.paused) touch();\n loop = requestAnimationFrame(tick);\n };\n loop = requestAnimationFrame(tick);\n return () => {\n for (const e of events) v.removeEventListener(e, touch);\n cancelAnimationFrame(loop);\n };\n }, [video, inView, schedule]);\n\n // Pointer: drag turns the view with the pointer, two pointers pinch, a click that did not drag picks.\n const pointers = React.useRef(new Map<number, { x: number; y: number }>());\n const gesture = React.useRef<{ moved: boolean; pinch: number | null; start: { x: number; y: number } } | null>(null);\n const hostRect = () => box.current!.getBoundingClientRect();\n const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n if (e.button !== 0 && e.pointerType === \"mouse\") return;\n pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });\n e.currentTarget.setPointerCapture?.(e.pointerId);\n const [first, second] = [...pointers.current.values()];\n const distance = second ? Math.hypot(first.x - second.x, first.y - second.y) : null;\n gesture.current = { moved: false, pinch: distance, start: { x: e.clientX, y: e.clientY } };\n e.currentTarget.focus({ preventScroll: true });\n };\n const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n const last = pointers.current.get(e.pointerId);\n if (!last || !gesture.current) return;\n const now = { x: e.clientX, y: e.clientY };\n pointers.current.set(e.pointerId, now);\n const v = live.current.view;\n const s = { width: hostRect().width, height: hostRect().height };\n if (pointers.current.size === 2) {\n const [a, b] = [...pointers.current.values()];\n const d = Math.hypot(a.x - b.x, a.y - b.y);\n if (gesture.current.pinch && d > 0) change({ ...v, fov: v.fov * (gesture.current.pinch / d) });\n gesture.current.pinch = d;\n gesture.current.moved = true;\n return;\n }\n if (Math.hypot(now.x - gesture.current.start.x, now.y - gesture.current.start.y) > 4) gesture.current.moved = true;\n if (!gesture.current.moved) return;\n // The picture follows the pointer: dragging right turns the view left.\n const per = degreesPerPixel(v, s);\n change({ ...v, yaw: v.yaw - (now.x - last.x) * per, pitch: v.pitch + (now.y - last.y) * per });\n };\n const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {\n const g = gesture.current;\n pointers.current.delete(e.pointerId);\n if (pointers.current.size === 0) {\n gesture.current = null;\n if (g && !g.moved && live.current.onPick) {\n const r = hostRect();\n const s = { width: r.width, height: r.height };\n const x = e.clientX - r.left;\n const y = e.clientY - r.top;\n live.current.onPick(current.current.flat ? unprojectFlat(live.current.view, s, x, y) : unproject(live.current.view, s, x, y));\n }\n } else if (g) g.pinch = null;\n };\n\n // The wheel zooms; native, because React's wheel listener is passive and the page must not scroll too.\n React.useEffect(() => {\n const el = box.current;\n if (!el || !wheelZoom) return;\n const onWheel = (e: WheelEvent) => {\n e.preventDefault();\n const v = live.current.view;\n change({ ...v, fov: v.fov * Math.exp(e.deltaY * 0.0015) });\n };\n el.addEventListener(\"wheel\", onWheel, { passive: false });\n return () => el.removeEventListener(\"wheel\", onWheel);\n }, [wheelZoom, change]);\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n const v = live.current.view;\n const turn = (v.fov / 12) * (e.shiftKey ? 3 : 1);\n if (e.key === \"ArrowLeft\") change({ ...v, yaw: v.yaw - turn });\n else if (e.key === \"ArrowRight\") change({ ...v, yaw: v.yaw + turn });\n else if (e.key === \"ArrowUp\") change({ ...v, pitch: v.pitch + turn });\n else if (e.key === \"ArrowDown\") change({ ...v, pitch: v.pitch - turn });\n else if (e.key === \"+\" || e.key === \"=\") change({ ...v, fov: v.fov * 0.8 });\n else if (e.key === \"-\" || e.key === \"_\") change({ ...v, fov: v.fov * 1.25 });\n else if (e.key === \"0\") change(defaultView);\n else return;\n e.preventDefault();\n };\n\n // Said in words: always on the picture; politely once the view has been still for a moment.\n const direction = describeView(view);\n const [said, setSaid] = React.useState(\"\");\n const first = React.useRef(true);\n React.useEffect(() => {\n if (first.current) {\n first.current = false;\n return;\n }\n const t = setTimeout(() => setSaid(`${direction}, field of view ${Math.round(view.fov)}°`), STILL_MS);\n return () => clearTimeout(t);\n }, [direction, view.fov]);\n\n const api: PanoramaOverlayApi = {\n view,\n size,\n flat,\n project: (yaw, pitch) => (flat ? projectFlat(view, size, yaw, pitch) : project(view, size, yaw, pitch)),\n unproject: (x, y) => (flat ? unprojectFlat(view, size, x, y) : unproject(view, size, x, y)),\n };\n const slider = fovSlider ? <Slider aria-label=\"Field of view\" value={Math.round(view.fov)} onChange={(fov) => change({ ...view, fov })} min={minFov} max={maxFov} step={1} unit=\"degree\" /> : null;\n\n return (\n <div className={cn(\"grid min-w-0 gap-2\", className)}>\n <div\n ref={boxRef}\n role=\"group\"\n aria-label={label}\n aria-describedby={undefined}\n tabIndex={0}\n onKeyDown={onKeyDown}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onPointerCancel={onPointerUp}\n className=\"relative w-full cursor-grab touch-none overflow-hidden rounded-surface bg-surface-sunken select-none active:cursor-grabbing\"\n style={{ aspectRatio: aspect }}\n >\n <canvas key={mode === \"flat\" ? \"2d\" : \"gl\"} ref={canvas} role=\"img\" aria-label={`${label}. ${direction}, field of view ${Math.round(view.fov)}°`} className=\"absolute inset-0 size-full\" />\n {overlay && size.width > 0 && <div className=\"pointer-events-none absolute inset-0\">{overlay(api)}</div>}\n </div>\n {flat && <p className=\"type-body-sm text-muted-foreground\">This browser cannot draw the 360 view, so the flat picture is shown. The controls work the same.</p>}\n {slider}\n <VisuallyHidden>\n <span role=\"status\">{said}</span>\n </VisuallyHidden>\n </div>\n );\n}\n"],"mappings":";;;;;;;AAcA,IAAM,SAAS;;;;AAKf,IAAM,WAAW;;;;;;;;;;;;;;;;;;;;AAoCjB,SAAgB,eAAe,QAAoD;CACjF,MAAM,KAAK,OAAO,WAAW,UAAU;EAAE,WAAW;EAAO,uBAAuB;EAAO,OAAO;CAAM,CAAC;CACvG,IAAI,CAAC,IAAI,OAAO;CAChB,MAAM,WAAW,MAAc,WAAmB;EAChD,MAAM,SAAS,GAAG,aAA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BAAiB;IACjB,WAAU;IACV,OAAO,EAAE,aAAa,OAAO;IAZ/B,UAAA,CAcE,oBAAC,UAAD;KAA4C,KAAK;KAAQ,MAAK;KAAM,cAAY,GAAG,MAAM,IAAI,UAAU,kBAAkB,KAAK,MAAM,KAAK,GAAG,EAAE;KAAI,WAAU;IAA8B,GAA7K,SAAS,SAAS,OAAO,IAAoJ,GACzL,WAAW,KAAK,QAAQ,KAAK,oBAAC,OAAD;KAAK,WAAU;KAAwC,UAAA,QAAQ,GAAG;IAAO,CAAA,CACpG;;GACJ,QAAQ,oBAAC,KAAD;IAAG,WAAU;IAAqC,UAAA;GAAmG,CAAA;GAC7J;GACD,oBAAC,gBAAD,EAAA,UACE,oBAAC,QAAD;IAAM,MAAK;IAAU,UAAA;GAAW,CAAA,EAClB,CAAA;EACb;;AAET"}
package/dist/testing.js CHANGED
@@ -1,5 +1,5 @@
1
- import { l as StrataQueryProvider, n as MicrophoneError, o as StrataToastRegion, s as toast, t as MicrophoneContext, u as createQueryClient } from "./microphone-CZy0bNEx.js";
2
- import { o as ThemeProvider } from "./theme-CFBAYaiu.js";
1
+ import { _ as StrataQueryProvider, c as forgetLoadedThumbnails, l as StrataToastRegion, n as MicrophoneError, t as MicrophoneContext, u as toast, v as createQueryClient } from "./microphone-Cu1u5Yml.js";
2
+ import { o as ThemeProvider } from "./theme-DXacprlw.js";
3
3
  import * as React from "react";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
5
5
  import { MemoryRouter, RouterProvider, createMemoryRouter } from "react-router";
@@ -470,6 +470,7 @@ function StrataProviders({ client, colorScheme, toasts, microphone, base, childr
470
470
  /** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */
471
471
  function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), colorScheme = "light", toasts = true, microphone, base, ...options } = {}) {
472
472
  toast.clear();
473
+ forgetLoadedThumbnails();
473
474
  const baseElement = installBase(base);
474
475
  const Wrapper = ({ children }) => /* @__PURE__ */ jsx(StrataProviders, {
475
476
  client,
@@ -493,6 +494,7 @@ function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), c
493
494
  /** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */
494
495
  function renderRoutes(routes, { route, basename, client = createTestQueryClient(), colorScheme = "light", toasts = true, microphone, base, ...options } = {}) {
495
496
  toast.clear();
497
+ forgetLoadedThumbnails();
496
498
  const baseElement = installBase(base);
497
499
  const router = createMemoryRouter(routes, {
498
500
  initialEntries: [route ?? basename ?? "/"],
@@ -1 +1 @@
1
- {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/storage.ts","../src/testing/layout.ts","../src/testing/speech.ts","../src/testing/microphone.ts","../src/testing/buttons.ts","../src/testing/intersection-observer.ts","../src/testing/index.tsx"],"sourcesContent":["// Node 25 and later define a global `localStorage` that is undefined unless Node runs with\n// `--localstorage-file`, and it shadows jsdom's. In a Vitest jsdom project on Node 26 (Strata's floor)\n// `localStorage.getItem` then throws, so any app code that reads storage (a remembered choice, a\n// `ColorSchemeChoice` on a settings screen tested with storage on) fails in its tests. Strata's own\n// tests never hit it because `renderWithStrata` turns theme storage off. Every app would have copied\n// the same dozen lines (issue #298), so `installLayoutShims` installs this when, and only when, the\n// platform's storage is unusable; where it works nothing is replaced.\n\n/** An in-memory `Storage`, with the platform's behaviour (values are strings, `key` and `length` work). */\nexport function memoryStorage(): Storage {\n const data = new Map<string, string>();\n return {\n get length() {\n return data.size;\n },\n clear: () => data.clear(),\n getItem: (key) => data.get(String(key)) ?? null,\n key: (index) => [...data.keys()][index] ?? null,\n removeItem: (key) => void data.delete(String(key)),\n setItem: (key, value) => void data.set(String(key), String(value)),\n };\n}\n\nfunction usable(name: \"localStorage\" | \"sessionStorage\"): boolean {\n try {\n return typeof (globalThis as unknown as Record<string, Storage | undefined>)[name]?.getItem === \"function\";\n } catch {\n return false;\n }\n}\n\n/**\n * Replaces `localStorage` and `sessionStorage` with in-memory ones where the runtime's are missing or throw (Node 25+ under jsdom), and empties them after each test when the test runner has a global `afterEach`.\n * Does nothing where storage works. Returns a function that puts the originals back. Called by `installLayoutShims`.\n */\nexport function installStorageShim(): () => void {\n const restore: (() => void)[] = [];\n for (const name of [\"localStorage\", \"sessionStorage\"] as const) {\n if (usable(name)) continue;\n const storage = memoryStorage();\n const targets = [globalThis, typeof window !== \"undefined\" ? window : undefined].filter((t): t is typeof globalThis => t !== undefined);\n for (const target of new Set(targets)) {\n const before = Object.getOwnPropertyDescriptor(target, name);\n Object.defineProperty(target, name, { configurable: true, value: storage });\n restore.push(() => {\n if (before) Object.defineProperty(target, name, before);\n else delete (target as unknown as Record<string, unknown>)[name];\n });\n }\n const after = (globalThis as { afterEach?: (fn: () => void) => void }).afterEach;\n if (typeof after === \"function\") after(() => storage.clear());\n }\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","// jsdom does no layout: every box is 0×0 and there is no ResizeObserver. Components that measure\n// (LineChart's width; React Aria's Virtualizer draws every row of a list in a test unless the box is mocked, which these shims do not make smaller. A virtualised table with detail rows, or a virtualised grid of tiles, measures each row by its scroll size, which jsdom reports as 0: a test of one gives `Element.prototype.scrollHeight` a value) then render nothing to\n// assert on, so an app testing a screen built from them hits the same wall Strata's own suite did.\n// These shims give every element one fixed box and a ResizeObserver that reports it once on\n// observe (and, on Node 25+, a working in-memory localStorage: see storage.ts). Real layout is checked by the visual suite in Chromium, never here.\n\nimport { installStorageShim } from \"./storage\";\n\n// jsdom has no DOMRect constructor in every version, so rects are plain objects of the same shape.\n/** A DOMRect-shaped object, for stand-ins that report geometry. */\nexport function box(x: number, y: number, width: number, height: number): DOMRect {\n return { x, y, width, height, top: y, left: x, right: x + width, bottom: y + height, toJSON() { return this; } } as DOMRect;\n}\n\n/** The box every element reports while the shims are installed. */\nexport interface LayoutBox {\n width: number;\n height: number;\n}\n\n/**\n * Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a\n * ResizeObserver that reports it on observe, so measuring components render, and an in-memory `localStorage` and `sessionStorage` where the runtime's throw (Node 25+). Defaults to 640×280.\n * Call once in a Vitest setup file; returns a function that puts the originals back.\n */\nexport function installLayoutShims({ width = 640, height = 280 }: Partial<LayoutBox> = {}): () => void {\n const restore: (() => void)[] = [];\n const replace = (target: object, prop: string, descriptor: PropertyDescriptor) => {\n const before = Object.getOwnPropertyDescriptor(target, prop);\n Object.defineProperty(target, prop, { configurable: true, ...descriptor });\n restore.push(() => {\n if (before) Object.defineProperty(target, prop, before);\n else delete (target as Record<string, unknown>)[prop];\n });\n };\n\n class FixedResizeObserver implements ResizeObserver {\n constructor(private readonly callback: ResizeObserverCallback) {}\n observe(target: Element) {\n this.callback([{ target, contentRect: { width, height } } as unknown as ResizeObserverEntry], this);\n }\n unobserve() {}\n disconnect() {}\n }\n if (!globalThis.ResizeObserver) replace(globalThis, \"ResizeObserver\", { writable: true, value: FixedResizeObserver });\n\n replace(Element.prototype, \"getBoundingClientRect\", {\n writable: true,\n value: () => box(0, 0, width, height),\n });\n for (const [prop, value] of [[\"offsetWidth\", width], [\"offsetHeight\", height], [\"clientWidth\", width], [\"clientHeight\", height]] as const) {\n replace(HTMLElement.prototype, prop, { get: () => value });\n }\n\n restore.push(installStorageShim());\n\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","// jsdom has no `speechSynthesis`, and the device's voices are a true external, so a test of a screen\n// that speaks needs a stand-in that records what was said (strata-react issue #299). This is the one\n// stand-in an app would otherwise write: it has `speak`, `cancel`, `getVoices`, `speaking` and the\n// voiceschanged event, it ends an utterance when the test says so (`finish()`), and it never makes a sound.\n// It stands in for `Audio` too (issue #310): a recorded clip that plays is said with its `clip`, `finish()`\n// ends it (the next part starts) and `failClip()` makes it fail, as a missing file or a refused autoplay does.\n\n/** One thing said aloud. */\nexport type Spoken = {\n text: string;\n lang: string;\n rate: number;\n voice: string | null;\n cancelled: boolean;\n /** The recording that was played, or null when the browser's voice said it. */\n clip: string | null;\n};\n\n/** The recording stand-in `installFakeSpeech` puts on `window`. */\nexport type FakeSpeech = {\n /** Everything said so far, in order; an utterance cut off by a later one has `cancelled: true`. */\n said: Spoken[];\n /** The texts said so far that were not cancelled. */\n texts(): string[];\n /** The clips played so far, in order (cut-off ones included). */\n clips(): string[];\n /** Ends the utterance or clip being said, as the browser does when it has finished. */\n finish(): void;\n /** Makes the clip playing now fail (a missing file, a refused autoplay): the rest of the prompt goes to the browser's voice. */\n failClip(): void;\n /** Makes these voices the device's, and fires `voiceschanged` (the late arrival some browsers have). */\n setVoices(voices: { name: string; lang: string }[]): void;\n /** Puts the browser's own back (or none). */\n uninstall(): void;\n};\n\n/**\n * Installs a recording `speechSynthesis` and `SpeechSynthesisUtterance` on `window` and returns what was said.\n * `uninstall()` after each test. `const speech = installFakeSpeech(); … expect(speech.texts()).toEqual([\"Which one is the cat?\"])`.\n */\nexport function installFakeSpeech(voices: { name: string; lang: string }[] = []): FakeSpeech {\n const hadSynth = Object.getOwnPropertyDescriptor(window, \"speechSynthesis\");\n const hadUtterance = Object.getOwnPropertyDescriptor(globalThis, \"SpeechSynthesisUtterance\");\n const hadAudio = Object.getOwnPropertyDescriptor(window, \"Audio\");\n let clip: { entry: Spoken; audio: FakeAudio } | undefined;\n let current: { entry: Spoken; utterance: FakeUtterance } | undefined;\n let installed = voices.map((v) => ({ ...v, default: false, localService: true, voiceURI: v.name }) as SpeechSynthesisVoice);\n const listeners = new Set<EventListener>();\n const said: Spoken[] = [];\n\n class FakeUtterance {\n lang = \"\";\n rate = 1;\n voice: SpeechSynthesisVoice | null = null;\n onend: (() => void) | null = null;\n onerror: (() => void) | null = null;\n constructor(public text: string) {}\n }\n\n // Only what `speak` uses of an audio element: src, title (the words), play, pause and the two events.\n class FakeAudio {\n src = \"\";\n title = \"\";\n onended: (() => void) | null = null;\n onerror: (() => void) | null = null;\n play() {\n const entry: Spoken = { text: this.title, lang: \"\", rate: 1, voice: null, cancelled: false, clip: this.src };\n said.push(entry);\n clip = { entry, audio: this };\n return Promise.resolve();\n }\n pause() {\n if (clip?.audio !== this) return;\n clip.entry.cancelled = true;\n clip = undefined;\n }\n }\n\n const synth = {\n get speaking() {\n return current !== undefined;\n },\n speak(utterance: FakeUtterance) {\n const entry: Spoken = { text: utterance.text, lang: utterance.lang, rate: utterance.rate, voice: utterance.voice?.name ?? null, cancelled: false, clip: null };\n said.push(entry);\n current = { entry, utterance };\n },\n cancel() {\n if (!current) return;\n const { entry, utterance } = current;\n current = undefined;\n entry.cancelled = true;\n utterance.onerror?.();\n },\n getVoices: () => installed,\n addEventListener: (_: string, l: EventListener) => void listeners.add(l),\n removeEventListener: (_: string, l: EventListener) => void listeners.delete(l),\n };\n\n Object.defineProperty(window, \"speechSynthesis\", { configurable: true, value: synth });\n Object.defineProperty(globalThis, \"SpeechSynthesisUtterance\", { configurable: true, writable: true, value: FakeUtterance });\n Object.defineProperty(window, \"Audio\", { configurable: true, writable: true, value: FakeAudio });\n\n return {\n said,\n texts: () => said.filter((s) => !s.cancelled).map((s) => s.text),\n clips: () => said.flatMap((s) => (s.clip === null ? [] : [s.clip])),\n finish() {\n if (clip) {\n const done = clip;\n clip = undefined;\n done.audio.onended?.();\n return;\n }\n const done = current;\n current = undefined;\n done?.utterance.onend?.();\n },\n failClip() {\n const failed = clip;\n clip = undefined;\n failed?.audio.onerror?.();\n },\n setVoices(next) {\n installed = next.map((v) => ({ ...v, default: false, localService: true, voiceURI: v.name }) as SpeechSynthesisVoice);\n for (const l of listeners) l(new Event(\"voiceschanged\"));\n },\n uninstall() {\n if (hadSynth) Object.defineProperty(window, \"speechSynthesis\", hadSynth);\n else delete (window as unknown as Record<string, unknown>).speechSynthesis;\n if (hadUtterance) Object.defineProperty(globalThis, \"SpeechSynthesisUtterance\", hadUtterance);\n else delete (globalThis as unknown as Record<string, unknown>).SpeechSynthesisUtterance;\n if (hadAudio) Object.defineProperty(window, \"Audio\", hadAudio);\n else delete (window as unknown as Record<string, unknown>).Audio;\n },\n };\n}\n","import { MicrophoneError, type Microphone } from \"../lib/microphone\";\n\n// The microphone is hardware, the one true external a recording screen has, and jsdom, Storybook and\n// the visual suite have none. This stand-in sends a sine tone at a chosen level, `speed` times faster\n// than real time (ten by default, so a test of a two-second take waits a fifth of a second), or refuses\n// to open with a sentence as the browser's refusals become (`explainMicrophoneError`). Give it to the\n// screen through `MicrophoneContext`, or `renderWithStrata(ui, { microphone })`.\n// For a hands-free screen (`useAutoRecorder`), `script` plays stretches of tone and quiet in turn, as a\n// speaker reading prompts with gaps between them would, once (then quiet) or over and over (`loop`).\n\n/** `fakeMicrophone`'s options. */\nexport type FakeMicrophoneOptions = {\n /** Peak of the tone, 0 to 1. Default 0.3 (about -10 dBFS, a good level for speech). */\n amplitude?: number;\n /** Refuse to open with this sentence, as a `MicrophoneError` (what a screen shows). */\n refuse?: string;\n /** Throw something that is not a `MicrophoneError` (an audio graph that failed). */\n crash?: boolean;\n /** What the browser calls the device. Default \"Fake USB microphone\". */\n device?: string | null;\n /** Open but never send a sample: a take held in its first moment, for a screenshot. */\n silent?: boolean;\n /** Samples a second. Default 16 000. */\n sampleRate?: number;\n /** How many times faster than real time the samples arrive. Default 10. */\n speed?: number;\n /** Stretches of tone at their own `amplitude` (0 for quiet), played in order instead of one steady tone. */\n script?: readonly FakeSpeechStretch[];\n /** Play `script` again from the start when it ends, instead of falling quiet. */\n loop?: boolean;\n};\n\n/** One stretch of a fake microphone's `script`: so many seconds at a peak (0 is quiet). */\nexport type FakeSpeechStretch = { seconds: number; amplitude: number };\n\n/** A script of `takes` stretches of speech, each `speak` seconds after `gap` seconds of quiet, at `amplitude`. */\nexport function speechScript(takes: number, { speak = 1.5, gap = 1.5, amplitude = 0.3 }: { speak?: number; gap?: number; amplitude?: number } = {}): FakeSpeechStretch[] {\n return Array.from({ length: takes }, () => [\n { seconds: gap, amplitude: 0 },\n { seconds: speak, amplitude },\n ]).flat();\n}\n\n/** A microphone that sends a tone (or refuses), for tests and stories; hardware is never touched. */\nexport function fakeMicrophone({\n amplitude = 0.3,\n refuse,\n crash,\n device = \"Fake USB microphone\",\n silent,\n sampleRate = 16_000,\n speed = 10,\n script,\n loop,\n}: FakeMicrophoneOptions = {}): Microphone {\n // The amplitude at sample `t`: the script's stretch it falls in, or the steady tone's.\n const ends = (script ?? []).reduce<number[]>((acc, s) => [...acc, (acc.at(-1) ?? 0) + Math.round(s.seconds * sampleRate)], []);\n const total = ends.at(-1) ?? 0;\n const at = (t: number): number => {\n if (!script) return amplitude;\n if (total === 0) return 0;\n const n = loop ? t % total : t;\n if (n >= total) return 0;\n const i = ends.findIndex((end) => n < end);\n return script[i].amplitude;\n };\n return {\n open(onSamples) {\n if (crash) return Promise.reject(new TypeError(\"audio graph exploded\"));\n if (refuse) return Promise.reject(new MicrophoneError(refuse));\n let t = 0;\n // A tenth of a second of sound each tick, every 100 / speed ms of real time.\n const frames = Math.round(sampleRate / 10);\n const timer = silent\n ? undefined\n : setInterval(() => {\n const chunk = new Float32Array(frames);\n for (let i = 0; i < frames; i++) chunk[i] = at(t) * Math.sin((2 * Math.PI * 220 * t++) / sampleRate);\n onSamples(chunk);\n }, 100 / speed);\n return Promise.resolve({ sampleRate, device, close: () => clearInterval(timer) });\n },\n };\n}\n","import type { Phase } from \"../components/async-button\";\n\n// Assertions for the rules a screen keeps, read from what the components draw rather than from\n// their class names (strata-react issue #48, from the Tubes Library test, which matched\n// `bg-primary`). `Button` marks its variant (`data-variant`), so \"one filled button per view\"\n// (ux-research patterns.md §2, with the BulkBar hand-over: while rows are chosen the bulk action is\n// the filled one) is a check a screen test can make after every interaction. `AsyncButton` marks\n// its phase (`data-phase`), because it keeps every phase's label in the DOM to hold its width, so\n// its text reads \"AddAdding…AddedTry again\" and only the phase says which one shows.\n\n/** Whether an element is out of the view: hidden, inert or aria-hidden, itself or by an ancestor. */\nfunction outOfView(el: Element) {\n return Boolean(el.closest('[hidden], [inert], [aria-hidden=\"true\"]'));\n}\n\n/** An element's name as a person reads it: its `aria-label`, else its text without the parts hidden from screen readers. */\nfunction nameOf(el: Element): string {\n const label = el.getAttribute(\"aria-label\");\n if (label) return label;\n const walk = (node: Node): string =>\n node.nodeType === 3\n ? (node.textContent ?? \"\")\n : node instanceof Element && node.getAttribute(\"aria-hidden\") === \"true\"\n ? \"\"\n : [...node.childNodes].map(walk).join(\"\");\n return walk(el).replace(/\\s+/g, \" \").trim();\n}\n\n/** The filled (`variant=\"default\"`) buttons and links in `container` (default the whole document) that are in view. */\nexport function filledButtons(container: ParentNode = document.body): HTMLElement[] {\n return [...container.querySelectorAll<HTMLElement>('[data-variant=\"default\"]')].filter((el) => !outOfView(el));\n}\n\n/** Throws unless `container` (default the whole document) has exactly one filled button in view; the message names the ones found. */\nexport function expectOneFilledButton(container: ParentNode = document.body): HTMLElement {\n const found = filledButtons(container);\n if (found.length === 1) return found[0];\n const names = found.map((el) => `\"${nameOf(el)}\"`).join(\", \");\n throw new Error(`Expected one filled button in the view, found ${found.length}${names ? `: ${names}` : \"\"}.`);\n}\n\n/** The phase an `AsyncButton` is in (`idle`, `pending`, `done`, `error`), from the button or any element inside it. */\nexport function asyncButtonPhase(el: Element): Phase {\n const phase = el.closest(\"[data-phase]\")?.getAttribute(\"data-phase\");\n if (phase === \"idle\" || phase === \"pending\" || phase === \"done\" || phase === \"error\") return phase;\n throw new Error(`Not an AsyncButton: ${el.outerHTML.slice(0, 120)}`);\n}\n","// jsdom has no IntersectionObserver and does no layout, so nothing a component observes ever comes\n// into view in a unit test. Infinite lists load the next page when a sentinel at the end of the\n// list intersects, and before this helper every app wrote its own firable fake to test that\n// (strata-react issue #12, from strata-listory). This one stands in for the global, records what\n// each observer watches, and lets the test say when something scrolls into view: `scrollToEnd()`\n// for the common case, `intersect(el)` for one element. Entries are delivered inside `act` so the\n// state updates they cause are flushed before the next assertion, as a real scroll would be.\n\nimport { act } from \"@testing-library/react\";\nimport { box } from \"./layout\";\n\n/** One stand-in observer: its callback, options and the elements it currently watches. */\nexport interface FakeObserver {\n readonly callback: IntersectionObserverCallback;\n readonly options: IntersectionObserverInit;\n readonly targets: ReadonlySet<Element>;\n}\n\n/** The controls `installFakeIntersectionObserver` returns. */\nexport interface FakeIntersectionObserverControls {\n /** Every observer created since install, including disconnected ones (their target sets are empty). */\n readonly observers: readonly FakeObserver[];\n /** Report `el` to every observer watching it: in view by default, or out of view with `false`. Returns how many observers were told. */\n intersect(el: Element, isIntersecting?: boolean): number;\n /** Report every watched element as in view, as if the person scrolled to the end of the list. Returns how many elements were reported. */\n scrollToEnd(): number;\n /** Put back whatever `IntersectionObserver` was there before install. */\n uninstall(): void;\n}\n\nfunction entryFor(target: Element, isIntersecting: boolean): IntersectionObserverEntry {\n const rect = target.getBoundingClientRect();\n return {\n target,\n isIntersecting,\n intersectionRatio: isIntersecting ? 1 : 0,\n boundingClientRect: rect,\n intersectionRect: isIntersecting ? rect : box(0, 0, 0, 0),\n rootBounds: null,\n time: performance.now(),\n };\n}\n\n/**\n * Replace `globalThis.IntersectionObserver` with a stand-in the test fires by hand. Call it in\n * `beforeEach` and call `uninstall()` in `afterEach`.\n *\n * @example\n * let io: FakeIntersectionObserverControls;\n * beforeEach(() => { io = installFakeIntersectionObserver(); });\n * afterEach(() => io.uninstall());\n *\n * it(\"loads the next page at the end of the list\", async () => {\n * renderWithStrata(<Pieces />);\n * await screen.findByRole(\"list\", { name: \"Pieces\" });\n * io.scrollToEnd();\n * expect(await screen.findByText(\"Celadon bowl\")).toBeInTheDocument();\n * });\n */\nexport function installFakeIntersectionObserver(): FakeIntersectionObserverControls {\n const previous = Object.getOwnPropertyDescriptor(globalThis, \"IntersectionObserver\");\n const observers: (FakeObserver & { targets: Set<Element>; self: IntersectionObserver })[] = [];\n\n class FakeIntersectionObserver implements IntersectionObserver {\n readonly root: Element | Document | null;\n readonly rootMargin: string;\n readonly thresholds: readonly number[];\n readonly scrollMargin = \"0px\";\n private readonly record: (typeof observers)[number];\n\n constructor(callback: IntersectionObserverCallback, options: IntersectionObserverInit = {}) {\n this.root = options.root ?? null;\n this.rootMargin = options.rootMargin ?? \"0px\";\n const threshold = options.threshold ?? 0;\n this.thresholds = Array.isArray(threshold) ? threshold : [threshold];\n this.record = { callback, options, targets: new Set(), self: this };\n observers.push(this.record);\n }\n observe(target: Element) {\n this.record.targets.add(target);\n }\n unobserve(target: Element) {\n this.record.targets.delete(target);\n }\n disconnect() {\n this.record.targets.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n\n Object.defineProperty(globalThis, \"IntersectionObserver\", {\n configurable: true,\n writable: true,\n value: FakeIntersectionObserver,\n });\n\n const deliver = (observer: (typeof observers)[number], targets: readonly Element[], isIntersecting: boolean) => {\n act(() => observer.callback(targets.map((t) => entryFor(t, isIntersecting)), observer.self));\n };\n\n return {\n observers,\n intersect(el, isIntersecting = true) {\n const watching = observers.filter((o) => o.targets.has(el));\n for (const o of watching) deliver(o, [el], isIntersecting);\n return watching.length;\n },\n scrollToEnd() {\n // Snapshot every observer's targets before any callback runs: a callback that loads more\n // may observe a new sentinel, on this observer or another, which the person has not\n // scrolled to yet.\n const batches = observers.map((o) => [o, [...o.targets]] as const).filter(([, targets]) => targets.length > 0);\n for (const [o, targets] of batches) deliver(o, targets, true);\n return batches.reduce((n, [, targets]) => n + targets.length, 0);\n },\n uninstall() {\n if (previous) Object.defineProperty(globalThis, \"IntersectionObserver\", previous);\n else delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n },\n };\n}\n","/**\n * Test helpers: render a component, or a whole route tree, inside a router and a query client, as\n * a Strata app runs it,\n * and fill the gaps jsdom leaves (layout, ResizeObserver, IntersectionObserver). Use with MSW for\n * the network, never module mocks.\n *\n * @module strata-react/testing\n */\nimport * as React from \"react\";\nimport { act, render, type RenderOptions } from \"@testing-library/react\";\nimport { MemoryRouter, RouterProvider, createMemoryRouter, type RouteObject, type To } from \"react-router\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { StrataQueryProvider, createQueryClient } from \"../query\";\nimport { ThemeProvider, type ColorSchemePreference } from \"../components/theme\";\nimport { StrataToastRegion, toast } from \"../components/toast\";\nimport { MicrophoneContext, type Microphone } from \"../lib/microphone\";\n\nexport { installLayoutShims, type LayoutBox } from \"./layout\";\nexport { installStorageShim, memoryStorage } from \"./storage\";\nexport { installFakeSpeech, type FakeSpeech, type Spoken } from \"./speech\";\nexport { fakeMicrophone, speechScript, type FakeMicrophoneOptions, type FakeSpeechStretch } from \"./microphone\";\nexport { filledButtons, expectOneFilledButton, asyncButtonPhase } from \"./buttons\";\nexport {\n installFakeIntersectionObserver,\n type FakeIntersectionObserverControls,\n type FakeObserver,\n} from \"./intersection-observer\";\n\n// Render a component the way a Strata app runs it: inside a router and a query client. Tests use\n// MSW for the network (see CLAUDE.md), never module mocks, so the real fetch/query/DataView path\n// runs. Each call gets a fresh QueryClient with retries off, so a test that serves a 500 sees the\n// error at once instead of after the retry delay. It also runs inside a ThemeProvider with\n// storage off, so `useColorScheme` works and a test can render the dark scheme with\n// `colorScheme: \"dark\"` without touching localStorage or leaking state into the next test.\n\n/** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */\nexport function createTestQueryClient() {\n return createQueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });\n}\n\n/** The options `renderWithStrata` and `renderRoutes` share, beside Testing Library's own. */\nexport type StrataRenderOptions = Omit<RenderOptions, \"wrapper\"> & {\n /** The URL the test starts at, with its search and hash (`/bookings?sort=pieces.desc`). Defaults to `/`. */\n route?: string;\n /** The query client; a fresh `createTestQueryClient()` when left out. */\n client?: QueryClient;\n /** The colour scheme to render; `light` when left out. */\n colorScheme?: ColorSchemePreference;\n /** Render the one `StrataToastRegion`, so `toast.show(...)` has somewhere to appear and a test can find it. Default true; pass `false` when the app's own route tree renders the region (a root layout route), or a test would see every toast twice. The queue is cleared at the start of each render, so a toast never carries into the next test. */\n toasts?: boolean;\n /** The microphone a recording screen gets from `useMicrophone()`, such as `fakeMicrophone()`; the browser's when left out (which jsdom cannot open). */\n microphone?: Microphone;\n /** The mount point of an app served behind a proxy (`\"/_home/\"`): a `<base href>` is in the document while the render lasts and removed when it unmounts, so `withBase`, `createApi` and `useSystemInfo` read what they read in production and in `strata-visual`. None when left out. */\n base?: string;\n};\n\n// A <base href> for one render (#350): `appBase()` reads the page's <base>, which jsdom does not have.\n// It is installed before the render (and before `renderRoutes` creates its router, whose loaders run\n// at creation and may call `withBase`), first in <head> so it wins over one a setup file left. It is\n// made once per render call, outside React's render, so Strict Mode cannot leave a second one behind;\n// the provider removes it when the tree unmounts (Testing Library's cleanup does that after each\n// test) and puts it back if Strict Mode's rehearsal of the effect took it out.\nfunction installBase(base: string | undefined): HTMLBaseElement | null {\n if (base === undefined || typeof document === \"undefined\") return null;\n const el = document.createElement(\"base\");\n el.setAttribute(\"href\", base);\n document.head.prepend(el);\n return el;\n}\n\nfunction useBaseElement(element: HTMLBaseElement | null | undefined) {\n React.useEffect(() => {\n if (element && !element.isConnected) document.head.prepend(element);\n return () => element?.remove();\n }, [element]);\n}\n\n// The providers every Strata app has above its router, in the order an app nests them.\nfunction StrataProviders({\n client,\n colorScheme,\n toasts,\n microphone,\n base,\n children,\n}: {\n base?: HTMLBaseElement | null;\n client: QueryClient;\n colorScheme: ColorSchemePreference;\n toasts: boolean;\n microphone?: Microphone;\n children: React.ReactNode;\n}) {\n useBaseElement(base);\n const tree = (\n <ThemeProvider defaultPreference={colorScheme} storageKey={null}>\n <StrataQueryProvider client={client}>\n {children}\n {toasts && <StrataToastRegion />}\n </StrataQueryProvider>\n </ThemeProvider>\n );\n return microphone ? <MicrophoneContext.Provider value={microphone}>{tree}</MicrophoneContext.Provider> : tree;\n}\n\n/** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */\nexport function renderWithStrata(\n ui: React.ReactElement,\n { route = \"/\", client = createTestQueryClient(), colorScheme = \"light\", toasts = true, microphone, base, ...options }: StrataRenderOptions = {},\n) {\n toast.clear(); // module state: a toast from the last test must not show in this one\n const baseElement = installBase(base);\n const Wrapper = ({ children }: { children: React.ReactNode }) => (\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts} microphone={microphone} base={baseElement}>\n <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>\n </StrataProviders>\n );\n return { client, ...render(ui, { wrapper: Wrapper, ...options }) };\n}\n\n// Render an app's own route tree: its layout routes and <Outlet />s, index routes, redirects\n// (<Navigate /> or a loader's redirect()), loaders, actions and error elements. Those only run in\n// a data router, which <MemoryRouter> is not, so renderWithStrata cannot show them; this builds\n// the memory twin of the app's createBrowserRouter from the same RouteObject[] the app exports,\n// so the test and the app cannot drift. The providers and options are renderWithStrata's.\n// `basename` is the app's own (the kiln app runs under /kiln), and `route` is the full URL,\n// basename included, as the browser would show it. The router is returned so a test can assert\n// where a redirect landed (`router.state.location`), and `navigate` moves it inside act().\n\n/** `renderRoutes`'s options: `renderWithStrata`'s, plus the app's `basename`. */\nexport type RenderRoutesOptions = StrataRenderOptions & {\n /** The base path the app is served under, as passed to `createBrowserRouter`. */\n basename?: string;\n};\n\n/** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */\nexport function renderRoutes(\n routes: RouteObject[],\n {\n route,\n basename,\n client = createTestQueryClient(),\n colorScheme = \"light\",\n toasts = true,\n microphone,\n base,\n ...options\n }: RenderRoutesOptions = {},\n) {\n toast.clear();\n const baseElement = installBase(base);\n const router = createMemoryRouter(routes, { initialEntries: [route ?? basename ?? \"/\"], basename });\n const result = render(\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts} microphone={microphone} base={baseElement}>\n <RouterProvider router={router} />\n </StrataProviders>,\n options,\n );\n const navigate = (to: To | number) =>\n act(async () => {\n await (typeof to === \"number\" ? router.navigate(to) : router.navigate(to));\n });\n return { client, router, navigate, ...result };\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,gBAAyB;CACvC,MAAM,uBAAO,IAAI,IAAoB;CACrC,OAAO;EACL,IAAI,SAAS;GACX,OAAO,KAAK;EACd;EACA,aAAa,KAAK,MAAM;EAC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O;EAAa,UAAA;CAAiC,CAAA,IAAI;AAC3G;;AAGA,SAAgB,iBACd,IACA,EAAE,QAAQ,KAAK,SAAS,sBAAsB,GAAG,cAAc,SAAS,SAAS,MAAM,YAAY,MAAM,GAAG,YAAiC,CAAC,GAC9I;CACA,MAAM,MAAM;CACZ,MAAM,cAAc,YAAY,IAAI;CACpC,MAAM,WAAW,EAAE,eACjB,oBAAC,iBAAD;EAAyB;EAAqB;EAAqB;EAAoB;EAAY,MAAM;EACvG,UAAA,oBAAC,cAAD;GAAc,gBAAgB,CAAC,KAAK;GAAI;EAAuB,CAAA;CAChD,CAAA;CAEnB,OAAO;EAAE;EAAQ,GAAG,OAAO,IAAI;GAAE,SAAS;GAAS,GAAG;EAAQ,CAAC;CAAE;AACnE;;AAkBA,SAAgB,aACd,QACA,EACE,OACA,UACA,SAAS,sBAAsB,GAC/B,cAAc,SACd,SAAS,MACT,YACA,MACA,GAAG,YACoB,CAAC,GAC1B;CACA,MAAM,MAAM;CACZ,MAAM,cAAc,YAAY,IAAI;CACpC,MAAM,SAAS,mBAAmB,QAAQ;EAAE,gBAAgB,CAAC,SAAS,YAAY,GAAG;EAAG;CAAS,CAAC;CAClG,MAAM,SAAS,OACb,oBAAC,iBAAD;EAAyB;EAAqB;EAAqB;EAAoB;EAAY,MAAM;EACvG,UAAA,oBAAC,gBAAD,EAAwB,OAAS,CAAA;CAClB,CAAA,GACjB,OACF;CACA,MAAM,YAAY,OAChB,IAAI,YAAY;EACd,OAAO,OAAO,OAAO,WAAW,OAAO,SAAS,EAAE,IAAI,OAAO,SAAS,EAAE;CAC1E,CAAC;CACH,OAAO;EAAE;EAAQ;EAAQ;EAAU,GAAG;CAAO;AAC/C"}
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/storage.ts","../src/testing/layout.ts","../src/testing/speech.ts","../src/testing/microphone.ts","../src/testing/buttons.ts","../src/testing/intersection-observer.ts","../src/testing/index.tsx"],"sourcesContent":["// Node 25 and later define a global `localStorage` that is undefined unless Node runs with\n// `--localstorage-file`, and it shadows jsdom's. In a Vitest jsdom project on Node 26 (Strata's floor)\n// `localStorage.getItem` then throws, so any app code that reads storage (a remembered choice, a\n// `ColorSchemeChoice` on a settings screen tested with storage on) fails in its tests. Strata's own\n// tests never hit it because `renderWithStrata` turns theme storage off. Every app would have copied\n// the same dozen lines (issue #298), so `installLayoutShims` installs this when, and only when, the\n// platform's storage is unusable; where it works nothing is replaced.\n\n/** An in-memory `Storage`, with the platform's behaviour (values are strings, `key` and `length` work). */\nexport function memoryStorage(): Storage {\n const data = new Map<string, string>();\n return {\n get length() {\n return data.size;\n },\n clear: () => data.clear(),\n getItem: (key) => data.get(String(key)) ?? null,\n key: (index) => [...data.keys()][index] ?? null,\n removeItem: (key) => void data.delete(String(key)),\n setItem: (key, value) => void data.set(String(key), String(value)),\n };\n}\n\nfunction usable(name: \"localStorage\" | \"sessionStorage\"): boolean {\n try {\n return typeof (globalThis as unknown as Record<string, Storage | undefined>)[name]?.getItem === \"function\";\n } catch {\n return false;\n }\n}\n\n/**\n * Replaces `localStorage` and `sessionStorage` with in-memory ones where the runtime's are missing or throw (Node 25+ under jsdom), and empties them after each test when the test runner has a global `afterEach`.\n * Does nothing where storage works. Returns a function that puts the originals back. Called by `installLayoutShims`.\n */\nexport function installStorageShim(): () => void {\n const restore: (() => void)[] = [];\n for (const name of [\"localStorage\", \"sessionStorage\"] as const) {\n if (usable(name)) continue;\n const storage = memoryStorage();\n const targets = [globalThis, typeof window !== \"undefined\" ? window : undefined].filter((t): t is typeof globalThis => t !== undefined);\n for (const target of new Set(targets)) {\n const before = Object.getOwnPropertyDescriptor(target, name);\n Object.defineProperty(target, name, { configurable: true, value: storage });\n restore.push(() => {\n if (before) Object.defineProperty(target, name, before);\n else delete (target as unknown as Record<string, unknown>)[name];\n });\n }\n const after = (globalThis as { afterEach?: (fn: () => void) => void }).afterEach;\n if (typeof after === \"function\") after(() => storage.clear());\n }\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","// jsdom does no layout: every box is 0×0 and there is no ResizeObserver. Components that measure\n// (LineChart's width; React Aria's Virtualizer draws every row of a list in a test unless the box is mocked, which these shims do not make smaller. A virtualised table with detail rows, or a virtualised grid of tiles, measures each row by its scroll size, which jsdom reports as 0: a test of one gives `Element.prototype.scrollHeight` a value) then render nothing to\n// assert on, so an app testing a screen built from them hits the same wall Strata's own suite did.\n// These shims give every element one fixed box and a ResizeObserver that reports it once on\n// observe (and, on Node 25+, a working in-memory localStorage: see storage.ts). Real layout is checked by the visual suite in Chromium, never here.\n\nimport { installStorageShim } from \"./storage\";\n\n// jsdom has no DOMRect constructor in every version, so rects are plain objects of the same shape.\n/** A DOMRect-shaped object, for stand-ins that report geometry. */\nexport function box(x: number, y: number, width: number, height: number): DOMRect {\n return { x, y, width, height, top: y, left: x, right: x + width, bottom: y + height, toJSON() { return this; } } as DOMRect;\n}\n\n/** The box every element reports while the shims are installed. */\nexport interface LayoutBox {\n width: number;\n height: number;\n}\n\n/**\n * Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a\n * ResizeObserver that reports it on observe, so measuring components render, and an in-memory `localStorage` and `sessionStorage` where the runtime's throw (Node 25+). Defaults to 640×280.\n * Call once in a Vitest setup file; returns a function that puts the originals back.\n */\nexport function installLayoutShims({ width = 640, height = 280 }: Partial<LayoutBox> = {}): () => void {\n const restore: (() => void)[] = [];\n const replace = (target: object, prop: string, descriptor: PropertyDescriptor) => {\n const before = Object.getOwnPropertyDescriptor(target, prop);\n Object.defineProperty(target, prop, { configurable: true, ...descriptor });\n restore.push(() => {\n if (before) Object.defineProperty(target, prop, before);\n else delete (target as Record<string, unknown>)[prop];\n });\n };\n\n class FixedResizeObserver implements ResizeObserver {\n constructor(private readonly callback: ResizeObserverCallback) {}\n observe(target: Element) {\n this.callback([{ target, contentRect: { width, height } } as unknown as ResizeObserverEntry], this);\n }\n unobserve() {}\n disconnect() {}\n }\n if (!globalThis.ResizeObserver) replace(globalThis, \"ResizeObserver\", { writable: true, value: FixedResizeObserver });\n\n replace(Element.prototype, \"getBoundingClientRect\", {\n writable: true,\n value: () => box(0, 0, width, height),\n });\n for (const [prop, value] of [[\"offsetWidth\", width], [\"offsetHeight\", height], [\"clientWidth\", width], [\"clientHeight\", height]] as const) {\n replace(HTMLElement.prototype, prop, { get: () => value });\n }\n\n restore.push(installStorageShim());\n\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","// jsdom has no `speechSynthesis`, and the device's voices are a true external, so a test of a screen\n// that speaks needs a stand-in that records what was said (strata-react issue #299). This is the one\n// stand-in an app would otherwise write: it has `speak`, `cancel`, `getVoices`, `speaking` and the\n// voiceschanged event, it ends an utterance when the test says so (`finish()`), and it never makes a sound.\n// It stands in for `Audio` too (issue #310): a recorded clip that plays is said with its `clip`, `finish()`\n// ends it (the next part starts) and `failClip()` makes it fail, as a missing file or a refused autoplay does.\n\n/** One thing said aloud. */\nexport type Spoken = {\n text: string;\n lang: string;\n rate: number;\n voice: string | null;\n cancelled: boolean;\n /** The recording that was played, or null when the browser's voice said it. */\n clip: string | null;\n};\n\n/** The recording stand-in `installFakeSpeech` puts on `window`. */\nexport type FakeSpeech = {\n /** Everything said so far, in order; an utterance cut off by a later one has `cancelled: true`. */\n said: Spoken[];\n /** The texts said so far that were not cancelled. */\n texts(): string[];\n /** The clips played so far, in order (cut-off ones included). */\n clips(): string[];\n /** Ends the utterance or clip being said, as the browser does when it has finished. */\n finish(): void;\n /** Makes the clip playing now fail (a missing file, a refused autoplay): the rest of the prompt goes to the browser's voice. */\n failClip(): void;\n /** Makes these voices the device's, and fires `voiceschanged` (the late arrival some browsers have). */\n setVoices(voices: { name: string; lang: string }[]): void;\n /** Puts the browser's own back (or none). */\n uninstall(): void;\n};\n\n/**\n * Installs a recording `speechSynthesis` and `SpeechSynthesisUtterance` on `window` and returns what was said.\n * `uninstall()` after each test. `const speech = installFakeSpeech(); … expect(speech.texts()).toEqual([\"Which one is the cat?\"])`.\n */\nexport function installFakeSpeech(voices: { name: string; lang: string }[] = []): FakeSpeech {\n const hadSynth = Object.getOwnPropertyDescriptor(window, \"speechSynthesis\");\n const hadUtterance = Object.getOwnPropertyDescriptor(globalThis, \"SpeechSynthesisUtterance\");\n const hadAudio = Object.getOwnPropertyDescriptor(window, \"Audio\");\n let clip: { entry: Spoken; audio: FakeAudio } | undefined;\n let current: { entry: Spoken; utterance: FakeUtterance } | undefined;\n let installed = voices.map((v) => ({ ...v, default: false, localService: true, voiceURI: v.name }) as SpeechSynthesisVoice);\n const listeners = new Set<EventListener>();\n const said: Spoken[] = [];\n\n class FakeUtterance {\n lang = \"\";\n rate = 1;\n voice: SpeechSynthesisVoice | null = null;\n onend: (() => void) | null = null;\n onerror: (() => void) | null = null;\n constructor(public text: string) {}\n }\n\n // Only what `speak` uses of an audio element: src, title (the words), play, pause and the two events.\n class FakeAudio {\n src = \"\";\n title = \"\";\n onended: (() => void) | null = null;\n onerror: (() => void) | null = null;\n play() {\n const entry: Spoken = { text: this.title, lang: \"\", rate: 1, voice: null, cancelled: false, clip: this.src };\n said.push(entry);\n clip = { entry, audio: this };\n return Promise.resolve();\n }\n pause() {\n if (clip?.audio !== this) return;\n clip.entry.cancelled = true;\n clip = undefined;\n }\n }\n\n const synth = {\n get speaking() {\n return current !== undefined;\n },\n speak(utterance: FakeUtterance) {\n const entry: Spoken = { text: utterance.text, lang: utterance.lang, rate: utterance.rate, voice: utterance.voice?.name ?? null, cancelled: false, clip: null };\n said.push(entry);\n current = { entry, utterance };\n },\n cancel() {\n if (!current) return;\n const { entry, utterance } = current;\n current = undefined;\n entry.cancelled = true;\n utterance.onerror?.();\n },\n getVoices: () => installed,\n addEventListener: (_: string, l: EventListener) => void listeners.add(l),\n removeEventListener: (_: string, l: EventListener) => void listeners.delete(l),\n };\n\n Object.defineProperty(window, \"speechSynthesis\", { configurable: true, value: synth });\n Object.defineProperty(globalThis, \"SpeechSynthesisUtterance\", { configurable: true, writable: true, value: FakeUtterance });\n Object.defineProperty(window, \"Audio\", { configurable: true, writable: true, value: FakeAudio });\n\n return {\n said,\n texts: () => said.filter((s) => !s.cancelled).map((s) => s.text),\n clips: () => said.flatMap((s) => (s.clip === null ? [] : [s.clip])),\n finish() {\n if (clip) {\n const done = clip;\n clip = undefined;\n done.audio.onended?.();\n return;\n }\n const done = current;\n current = undefined;\n done?.utterance.onend?.();\n },\n failClip() {\n const failed = clip;\n clip = undefined;\n failed?.audio.onerror?.();\n },\n setVoices(next) {\n installed = next.map((v) => ({ ...v, default: false, localService: true, voiceURI: v.name }) as SpeechSynthesisVoice);\n for (const l of listeners) l(new Event(\"voiceschanged\"));\n },\n uninstall() {\n if (hadSynth) Object.defineProperty(window, \"speechSynthesis\", hadSynth);\n else delete (window as unknown as Record<string, unknown>).speechSynthesis;\n if (hadUtterance) Object.defineProperty(globalThis, \"SpeechSynthesisUtterance\", hadUtterance);\n else delete (globalThis as unknown as Record<string, unknown>).SpeechSynthesisUtterance;\n if (hadAudio) Object.defineProperty(window, \"Audio\", hadAudio);\n else delete (window as unknown as Record<string, unknown>).Audio;\n },\n };\n}\n","import { MicrophoneError, type Microphone } from \"../lib/microphone\";\n\n// The microphone is hardware, the one true external a recording screen has, and jsdom, Storybook and\n// the visual suite have none. This stand-in sends a sine tone at a chosen level, `speed` times faster\n// than real time (ten by default, so a test of a two-second take waits a fifth of a second), or refuses\n// to open with a sentence as the browser's refusals become (`explainMicrophoneError`). Give it to the\n// screen through `MicrophoneContext`, or `renderWithStrata(ui, { microphone })`.\n// For a hands-free screen (`useAutoRecorder`), `script` plays stretches of tone and quiet in turn, as a\n// speaker reading prompts with gaps between them would, once (then quiet) or over and over (`loop`).\n\n/** `fakeMicrophone`'s options. */\nexport type FakeMicrophoneOptions = {\n /** Peak of the tone, 0 to 1. Default 0.3 (about -10 dBFS, a good level for speech). */\n amplitude?: number;\n /** Refuse to open with this sentence, as a `MicrophoneError` (what a screen shows). */\n refuse?: string;\n /** Throw something that is not a `MicrophoneError` (an audio graph that failed). */\n crash?: boolean;\n /** What the browser calls the device. Default \"Fake USB microphone\". */\n device?: string | null;\n /** Open but never send a sample: a take held in its first moment, for a screenshot. */\n silent?: boolean;\n /** Samples a second. Default 16 000. */\n sampleRate?: number;\n /** How many times faster than real time the samples arrive. Default 10. */\n speed?: number;\n /** Stretches of tone at their own `amplitude` (0 for quiet), played in order instead of one steady tone. */\n script?: readonly FakeSpeechStretch[];\n /** Play `script` again from the start when it ends, instead of falling quiet. */\n loop?: boolean;\n};\n\n/** One stretch of a fake microphone's `script`: so many seconds at a peak (0 is quiet). */\nexport type FakeSpeechStretch = { seconds: number; amplitude: number };\n\n/** A script of `takes` stretches of speech, each `speak` seconds after `gap` seconds of quiet, at `amplitude`. */\nexport function speechScript(takes: number, { speak = 1.5, gap = 1.5, amplitude = 0.3 }: { speak?: number; gap?: number; amplitude?: number } = {}): FakeSpeechStretch[] {\n return Array.from({ length: takes }, () => [\n { seconds: gap, amplitude: 0 },\n { seconds: speak, amplitude },\n ]).flat();\n}\n\n/** A microphone that sends a tone (or refuses), for tests and stories; hardware is never touched. */\nexport function fakeMicrophone({\n amplitude = 0.3,\n refuse,\n crash,\n device = \"Fake USB microphone\",\n silent,\n sampleRate = 16_000,\n speed = 10,\n script,\n loop,\n}: FakeMicrophoneOptions = {}): Microphone {\n // The amplitude at sample `t`: the script's stretch it falls in, or the steady tone's.\n const ends = (script ?? []).reduce<number[]>((acc, s) => [...acc, (acc.at(-1) ?? 0) + Math.round(s.seconds * sampleRate)], []);\n const total = ends.at(-1) ?? 0;\n const at = (t: number): number => {\n if (!script) return amplitude;\n if (total === 0) return 0;\n const n = loop ? t % total : t;\n if (n >= total) return 0;\n const i = ends.findIndex((end) => n < end);\n return script[i].amplitude;\n };\n return {\n open(onSamples) {\n if (crash) return Promise.reject(new TypeError(\"audio graph exploded\"));\n if (refuse) return Promise.reject(new MicrophoneError(refuse));\n let t = 0;\n // A tenth of a second of sound each tick, every 100 / speed ms of real time.\n const frames = Math.round(sampleRate / 10);\n const timer = silent\n ? undefined\n : setInterval(() => {\n const chunk = new Float32Array(frames);\n for (let i = 0; i < frames; i++) chunk[i] = at(t) * Math.sin((2 * Math.PI * 220 * t++) / sampleRate);\n onSamples(chunk);\n }, 100 / speed);\n return Promise.resolve({ sampleRate, device, close: () => clearInterval(timer) });\n },\n };\n}\n","import type { Phase } from \"../components/async-button\";\n\n// Assertions for the rules a screen keeps, read from what the components draw rather than from\n// their class names (strata-react issue #48, from the Tubes Library test, which matched\n// `bg-primary`). `Button` marks its variant (`data-variant`), so \"one filled button per view\"\n// (ux-research patterns.md §2, with the BulkBar hand-over: while rows are chosen the bulk action is\n// the filled one) is a check a screen test can make after every interaction. `AsyncButton` marks\n// its phase (`data-phase`), because it keeps every phase's label in the DOM to hold its width, so\n// its text reads \"AddAdding…AddedTry again\" and only the phase says which one shows.\n\n/** Whether an element is out of the view: hidden, inert or aria-hidden, itself or by an ancestor. */\nfunction outOfView(el: Element) {\n return Boolean(el.closest('[hidden], [inert], [aria-hidden=\"true\"]'));\n}\n\n/** An element's name as a person reads it: its `aria-label`, else its text without the parts hidden from screen readers. */\nfunction nameOf(el: Element): string {\n const label = el.getAttribute(\"aria-label\");\n if (label) return label;\n const walk = (node: Node): string =>\n node.nodeType === 3\n ? (node.textContent ?? \"\")\n : node instanceof Element && node.getAttribute(\"aria-hidden\") === \"true\"\n ? \"\"\n : [...node.childNodes].map(walk).join(\"\");\n return walk(el).replace(/\\s+/g, \" \").trim();\n}\n\n/** The filled (`variant=\"default\"`) buttons and links in `container` (default the whole document) that are in view. */\nexport function filledButtons(container: ParentNode = document.body): HTMLElement[] {\n return [...container.querySelectorAll<HTMLElement>('[data-variant=\"default\"]')].filter((el) => !outOfView(el));\n}\n\n/** Throws unless `container` (default the whole document) has exactly one filled button in view; the message names the ones found. */\nexport function expectOneFilledButton(container: ParentNode = document.body): HTMLElement {\n const found = filledButtons(container);\n if (found.length === 1) return found[0];\n const names = found.map((el) => `\"${nameOf(el)}\"`).join(\", \");\n throw new Error(`Expected one filled button in the view, found ${found.length}${names ? `: ${names}` : \"\"}.`);\n}\n\n/** The phase an `AsyncButton` is in (`idle`, `pending`, `done`, `error`), from the button or any element inside it. */\nexport function asyncButtonPhase(el: Element): Phase {\n const phase = el.closest(\"[data-phase]\")?.getAttribute(\"data-phase\");\n if (phase === \"idle\" || phase === \"pending\" || phase === \"done\" || phase === \"error\") return phase;\n throw new Error(`Not an AsyncButton: ${el.outerHTML.slice(0, 120)}`);\n}\n","// jsdom has no IntersectionObserver and does no layout, so nothing a component observes ever comes\n// into view in a unit test. Infinite lists load the next page when a sentinel at the end of the\n// list intersects, and before this helper every app wrote its own firable fake to test that\n// (strata-react issue #12, from strata-listory). This one stands in for the global, records what\n// each observer watches, and lets the test say when something scrolls into view: `scrollToEnd()`\n// for the common case, `intersect(el)` for one element. Entries are delivered inside `act` so the\n// state updates they cause are flushed before the next assertion, as a real scroll would be.\n\nimport { act } from \"@testing-library/react\";\nimport { box } from \"./layout\";\n\n/** One stand-in observer: its callback, options and the elements it currently watches. */\nexport interface FakeObserver {\n readonly callback: IntersectionObserverCallback;\n readonly options: IntersectionObserverInit;\n readonly targets: ReadonlySet<Element>;\n}\n\n/** The controls `installFakeIntersectionObserver` returns. */\nexport interface FakeIntersectionObserverControls {\n /** Every observer created since install, including disconnected ones (their target sets are empty). */\n readonly observers: readonly FakeObserver[];\n /** Report `el` to every observer watching it: in view by default, or out of view with `false`. Returns how many observers were told. */\n intersect(el: Element, isIntersecting?: boolean): number;\n /** Report every watched element as in view, as if the person scrolled to the end of the list. Returns how many elements were reported. */\n scrollToEnd(): number;\n /** Put back whatever `IntersectionObserver` was there before install. */\n uninstall(): void;\n}\n\nfunction entryFor(target: Element, isIntersecting: boolean): IntersectionObserverEntry {\n const rect = target.getBoundingClientRect();\n return {\n target,\n isIntersecting,\n intersectionRatio: isIntersecting ? 1 : 0,\n boundingClientRect: rect,\n intersectionRect: isIntersecting ? rect : box(0, 0, 0, 0),\n rootBounds: null,\n time: performance.now(),\n };\n}\n\n/**\n * Replace `globalThis.IntersectionObserver` with a stand-in the test fires by hand. Call it in\n * `beforeEach` and call `uninstall()` in `afterEach`.\n *\n * @example\n * let io: FakeIntersectionObserverControls;\n * beforeEach(() => { io = installFakeIntersectionObserver(); });\n * afterEach(() => io.uninstall());\n *\n * it(\"loads the next page at the end of the list\", async () => {\n * renderWithStrata(<Pieces />);\n * await screen.findByRole(\"list\", { name: \"Pieces\" });\n * io.scrollToEnd();\n * expect(await screen.findByText(\"Celadon bowl\")).toBeInTheDocument();\n * });\n */\nexport function installFakeIntersectionObserver(): FakeIntersectionObserverControls {\n const previous = Object.getOwnPropertyDescriptor(globalThis, \"IntersectionObserver\");\n const observers: (FakeObserver & { targets: Set<Element>; self: IntersectionObserver })[] = [];\n\n class FakeIntersectionObserver implements IntersectionObserver {\n readonly root: Element | Document | null;\n readonly rootMargin: string;\n readonly thresholds: readonly number[];\n readonly scrollMargin = \"0px\";\n private readonly record: (typeof observers)[number];\n\n constructor(callback: IntersectionObserverCallback, options: IntersectionObserverInit = {}) {\n this.root = options.root ?? null;\n this.rootMargin = options.rootMargin ?? \"0px\";\n const threshold = options.threshold ?? 0;\n this.thresholds = Array.isArray(threshold) ? threshold : [threshold];\n this.record = { callback, options, targets: new Set(), self: this };\n observers.push(this.record);\n }\n observe(target: Element) {\n this.record.targets.add(target);\n }\n unobserve(target: Element) {\n this.record.targets.delete(target);\n }\n disconnect() {\n this.record.targets.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n\n Object.defineProperty(globalThis, \"IntersectionObserver\", {\n configurable: true,\n writable: true,\n value: FakeIntersectionObserver,\n });\n\n const deliver = (observer: (typeof observers)[number], targets: readonly Element[], isIntersecting: boolean) => {\n act(() => observer.callback(targets.map((t) => entryFor(t, isIntersecting)), observer.self));\n };\n\n return {\n observers,\n intersect(el, isIntersecting = true) {\n const watching = observers.filter((o) => o.targets.has(el));\n for (const o of watching) deliver(o, [el], isIntersecting);\n return watching.length;\n },\n scrollToEnd() {\n // Snapshot every observer's targets before any callback runs: a callback that loads more\n // may observe a new sentinel, on this observer or another, which the person has not\n // scrolled to yet.\n const batches = observers.map((o) => [o, [...o.targets]] as const).filter(([, targets]) => targets.length > 0);\n for (const [o, targets] of batches) deliver(o, targets, true);\n return batches.reduce((n, [, targets]) => n + targets.length, 0);\n },\n uninstall() {\n if (previous) Object.defineProperty(globalThis, \"IntersectionObserver\", previous);\n else delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n },\n };\n}\n","/**\n * Test helpers: render a component, or a whole route tree, inside a router and a query client, as\n * a Strata app runs it,\n * and fill the gaps jsdom leaves (layout, ResizeObserver, IntersectionObserver). Use with MSW for\n * the network, never module mocks.\n *\n * @module strata-react/testing\n */\nimport * as React from \"react\";\nimport { act, render, type RenderOptions } from \"@testing-library/react\";\nimport { MemoryRouter, RouterProvider, createMemoryRouter, type RouteObject, type To } from \"react-router\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { StrataQueryProvider, createQueryClient } from \"../query\";\nimport { ThemeProvider, type ColorSchemePreference } from \"../components/theme\";\nimport { StrataToastRegion, toast } from \"../components/toast\";\nimport { forgetLoadedThumbnails } from \"../components/thumbnail\";\nimport { MicrophoneContext, type Microphone } from \"../lib/microphone\";\n\nexport { installLayoutShims, type LayoutBox } from \"./layout\";\nexport { installStorageShim, memoryStorage } from \"./storage\";\nexport { installFakeSpeech, type FakeSpeech, type Spoken } from \"./speech\";\nexport { fakeMicrophone, speechScript, type FakeMicrophoneOptions, type FakeSpeechStretch } from \"./microphone\";\nexport { filledButtons, expectOneFilledButton, asyncButtonPhase } from \"./buttons\";\nexport {\n installFakeIntersectionObserver,\n type FakeIntersectionObserverControls,\n type FakeObserver,\n} from \"./intersection-observer\";\n\n// Render a component the way a Strata app runs it: inside a router and a query client. Tests use\n// MSW for the network (see CLAUDE.md), never module mocks, so the real fetch/query/DataView path\n// runs. Each call gets a fresh QueryClient with retries off, so a test that serves a 500 sees the\n// error at once instead of after the retry delay. It also runs inside a ThemeProvider with\n// storage off, so `useColorScheme` works and a test can render the dark scheme with\n// `colorScheme: \"dark\"` without touching localStorage or leaking state into the next test.\n\n/** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */\nexport function createTestQueryClient() {\n return createQueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });\n}\n\n/** The options `renderWithStrata` and `renderRoutes` share, beside Testing Library's own. */\nexport type StrataRenderOptions = Omit<RenderOptions, \"wrapper\"> & {\n /** The URL the test starts at, with its search and hash (`/bookings?sort=pieces.desc`). Defaults to `/`. */\n route?: string;\n /** The query client; a fresh `createTestQueryClient()` when left out. */\n client?: QueryClient;\n /** The colour scheme to render; `light` when left out. */\n colorScheme?: ColorSchemePreference;\n /** Render the one `StrataToastRegion`, so `toast.show(...)` has somewhere to appear and a test can find it. Default true; pass `false` when the app's own route tree renders the region (a root layout route), or a test would see every toast twice. The queue is cleared at the start of each render, so a toast never carries into the next test. */\n toasts?: boolean;\n /** The microphone a recording screen gets from `useMicrophone()`, such as `fakeMicrophone()`; the browser's when left out (which jsdom cannot open). */\n microphone?: Microphone;\n /** The mount point of an app served behind a proxy (`\"/_home/\"`): a `<base href>` is in the document while the render lasts and removed when it unmounts, so `withBase`, `createApi` and `useSystemInfo` read what they read in production and in `strata-visual`. None when left out. */\n base?: string;\n};\n\n// A <base href> for one render (#350): `appBase()` reads the page's <base>, which jsdom does not have.\n// It is installed before the render (and before `renderRoutes` creates its router, whose loaders run\n// at creation and may call `withBase`), first in <head> so it wins over one a setup file left. It is\n// made once per render call, outside React's render, so Strict Mode cannot leave a second one behind;\n// the provider removes it when the tree unmounts (Testing Library's cleanup does that after each\n// test) and puts it back if Strict Mode's rehearsal of the effect took it out.\nfunction installBase(base: string | undefined): HTMLBaseElement | null {\n if (base === undefined || typeof document === \"undefined\") return null;\n const el = document.createElement(\"base\");\n el.setAttribute(\"href\", base);\n document.head.prepend(el);\n return el;\n}\n\nfunction useBaseElement(element: HTMLBaseElement | null | undefined) {\n React.useEffect(() => {\n if (element && !element.isConnected) document.head.prepend(element);\n return () => element?.remove();\n }, [element]);\n}\n\n// The providers every Strata app has above its router, in the order an app nests them.\nfunction StrataProviders({\n client,\n colorScheme,\n toasts,\n microphone,\n base,\n children,\n}: {\n base?: HTMLBaseElement | null;\n client: QueryClient;\n colorScheme: ColorSchemePreference;\n toasts: boolean;\n microphone?: Microphone;\n children: React.ReactNode;\n}) {\n useBaseElement(base);\n const tree = (\n <ThemeProvider defaultPreference={colorScheme} storageKey={null}>\n <StrataQueryProvider client={client}>\n {children}\n {toasts && <StrataToastRegion />}\n </StrataQueryProvider>\n </ThemeProvider>\n );\n return microphone ? <MicrophoneContext.Provider value={microphone}>{tree}</MicrophoneContext.Provider> : tree;\n}\n\n/** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */\nexport function renderWithStrata(\n ui: React.ReactElement,\n { route = \"/\", client = createTestQueryClient(), colorScheme = \"light\", toasts = true, microphone, base, ...options }: StrataRenderOptions = {},\n) {\n toast.clear(); // module state: a toast from the last test must not show in this one\n forgetLoadedThumbnails(); // likewise the pictures a Thumbnail has loaded: each test starts from skeletons\n const baseElement = installBase(base);\n const Wrapper = ({ children }: { children: React.ReactNode }) => (\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts} microphone={microphone} base={baseElement}>\n <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>\n </StrataProviders>\n );\n return { client, ...render(ui, { wrapper: Wrapper, ...options }) };\n}\n\n// Render an app's own route tree: its layout routes and <Outlet />s, index routes, redirects\n// (<Navigate /> or a loader's redirect()), loaders, actions and error elements. Those only run in\n// a data router, which <MemoryRouter> is not, so renderWithStrata cannot show them; this builds\n// the memory twin of the app's createBrowserRouter from the same RouteObject[] the app exports,\n// so the test and the app cannot drift. The providers and options are renderWithStrata's.\n// `basename` is the app's own (the kiln app runs under /kiln), and `route` is the full URL,\n// basename included, as the browser would show it. The router is returned so a test can assert\n// where a redirect landed (`router.state.location`), and `navigate` moves it inside act().\n\n/** `renderRoutes`'s options: `renderWithStrata`'s, plus the app's `basename`. */\nexport type RenderRoutesOptions = StrataRenderOptions & {\n /** The base path the app is served under, as passed to `createBrowserRouter`. */\n basename?: string;\n};\n\n/** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */\nexport function renderRoutes(\n routes: RouteObject[],\n {\n route,\n basename,\n client = createTestQueryClient(),\n colorScheme = \"light\",\n toasts = true,\n microphone,\n base,\n ...options\n }: RenderRoutesOptions = {},\n) {\n toast.clear();\n forgetLoadedThumbnails();\n const baseElement = installBase(base);\n const router = createMemoryRouter(routes, { initialEntries: [route ?? basename ?? \"/\"], basename });\n const result = render(\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts} microphone={microphone} base={baseElement}>\n <RouterProvider router={router} />\n </StrataProviders>,\n options,\n );\n const navigate = (to: To | number) =>\n act(async () => {\n await (typeof to === \"number\" ? router.navigate(to) : router.navigate(to));\n });\n return { client, router, navigate, ...result };\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,gBAAyB;CACvC,MAAM,uBAAO,IAAI,IAAoB;CACrC,OAAO;EACL,IAAI,SAAS;GACX,OAAO,KAAK;EACd;EACA,aAAa,KAAK,MAAM;EACxB,UAAU,QAAQ,KAAK,IAAI,OAAO,GAAG,CAAC,KAAK;EAC3C,MAAM,UAAU,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,UAAU;EAC3C,aAAa,QAAQ,KAAK,KAAK,OAAO,OAAO,GAAG,CAAC;EACjD,UAAU,KAAK,UAAU,KAAK,KAAK,IAAI,OAAO,GAAG,GAAG,OAAO,KAAK,CAAC;CACnE;AACF;AAEA,SAAS,OAAO,MAAkD;CAChE,IAAI;EACF,OAAO,OAAQ,WAA8D,KAAK,EAAE,YAAY;CAClG,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,SAAgB,qBAAiC;C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AO;EAAE;EAAQ,GAAG,OAAO,IAAI;GAAE,SAAS;GAAS,GAAG;EAAQ,CAAC;CAAE;AACnE;;AAkBA,SAAgB,aACd,QACA,EACE,OACA,UACA,SAAS,sBAAsB,GAC/B,cAAc,SACd,SAAS,MACT,YACA,MACA,GAAG,YACoB,CAAC,GAC1B;CACA,MAAM,MAAM;CACZ,uBAAuB;CACvB,MAAM,cAAc,YAAY,IAAI;CACpC,MAAM,SAAS,mBAAmB,QAAQ;EAAE,gBAAgB,CAAC,SAAS,YAAY,GAAG;EAAG;CAAS,CAAC;CAClG,MAAM,SAAS,OACb,oBAAC,iBAAD;EAAyB;EAAqB;EAAqB;EAAoB;EAAY,MAAM;EACvG,UAAA,oBAAC,gBAAD,EAAwB,OAAS,CAAA;CAClB,CAAA,GACjB,OACF;CACA,MAAM,YAAY,OAChB,IAAI,YAAY;EACd,OAAO,OAAO,OAAO,WAAW,OAAO,SAAS,EAAE,IAAI,OAAO,SAAS,EAAE;CAC1E,CAAC;CACH,OAAO;EAAE;EAAQ;EAAQ;EAAU,GAAG;CAAO;AAC/C"}
@@ -1,4 +1,4 @@
1
- import { d as cn, l as Tooltip$1, t as ChoiceGroup } from "./field-jfhLD5XX.js";
1
+ import { g as cn, l as Tooltip$1, t as ChoiceGroup } from "./field-t4Hoer0d.js";
2
2
  import * as React from "react";
3
3
  import { Radio, RadioGroup } from "react-aria-components";
4
4
  import { Monitor, Moon, Sun } from "lucide-react";
@@ -332,4 +332,4 @@ function PaletteChoice({ legend, options = palettes, compact = false, className
332
332
  }
333
333
  export { PaletteChoice as a, paletteScript as c, usePalette as d, useSystemColorScheme as f, PALETTE_STORAGE_KEY as i, palettes as l, ColorSchemeChoice as n, ThemeProvider as o, Density as p, DEFAULT_PALETTE as r, colorSchemeScript as s, COLOR_SCHEME_STORAGE_KEY as t, useColorScheme as u };
334
334
 
335
- //# sourceMappingURL=theme-CFBAYaiu.js.map
335
+ //# sourceMappingURL=theme-DXacprlw.js.map