From 6129014b74e12243461085d746bded00cdcaec7f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:55:23 +0000 Subject: [PATCH] fix(xr): keep BabiaXR charts on the analysis table - babiaCompat.js (analysis-table runtime): write Babia axis lines directly (A-Frame 1.7.1 never applies the line.end animation, so an axis kept the length of its first build) and ask the containment for a re-fit when an axis resizes; let an empty babia-queryjson wait instead of fetching ''. - Anchor keeps the containment bounds (axes) on the usable tabletop; getChartStatus reports off-table instead of ok while they overhang. - Bounding boxes are recomputed when the position attribute changed. - Generated row-budgeted charts read codexrChartDataSlice__data from their first build; the slice sync never re-points them at raw data. - New opt-in browser harness test:xr-chart-bounds-harness (8 chart types x 3/30/300 files on real generated scenes) and unit tests. Part of the XR environment review epic (S3). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKtAtQus8TVjhG9bhytC --- .claude/docs/DEVELOPMENT.md | 1 + apps/vscode-extension/CHANGELOG.md | 5 + apps/vscode-extension/package.json | 1 + .../analysis/parsers/directoryXRParser.ts | 2 +- .../src/core/charts/templateCharts.ts | 29 ++- .../templates/components/COMPONENTS.md | 2 + .../analysisTableRuntime/babiaCompat.js | 121 +++++++++ .../containmentComponentCore.js | 12 +- .../analysisTableRuntime/diagnosticsAndPid.js | 56 +++- .../analysisTableRuntime/geometryUtils.js | 30 ++- .../analysisTableRuntime/manifest.json | 1 + .../policyAndRegistration.js | 6 + .../xrChartMappingUiRuntime/chartDataSlice.js | 7 + apps/vscode-extension/test/README.md | 2 +- .../test/analysis/xrChartTableBounds.test.cjs | 243 ++++++++++++++++++ .../baseline/featureBaseline.snapshot.json | 2 + .../runners/run-xr-chart-bounds-harness.cjs | 240 +++++++++++++++++ package.json | 1 + 18 files changed, 750 insertions(+), 11 deletions(-) create mode 100644 apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/babiaCompat.js create mode 100644 apps/vscode-extension/test/analysis/xrChartTableBounds.test.cjs create mode 100644 apps/vscode-extension/test/runners/run-xr-chart-bounds-harness.cjs diff --git a/.claude/docs/DEVELOPMENT.md b/.claude/docs/DEVELOPMENT.md index f59066bb..8b7ec4a7 100644 --- a/.claude/docs/DEVELOPMENT.md +++ b/.claude/docs/DEVELOPMENT.md @@ -31,6 +31,7 @@ | `npm run test:analysis` | `backend/scripts/run-analysis-tests.cjs` (venv in `backend/artifacts/analysis-test-venv`) over the `backend/manual_test/` fixtures (one per supported language); asserts XR and LivePanel produce the same `data.json`. Its venv installs the **lizard version the extension pins** (read from `backend/requirements.txt`, the generated mirror of `pythonPackageManifest.ts`) | After changing analysis output or language support | | `npm run test:htmlanalysis` | `test/runners/run-html-analysis-tests.cjs`: `test/analysis/livePanelDomIntegration.test.cjs` plus the Python suite `backend/tests/html_dom/` | After touching `backend/src/html/html_dom_parser.py` or DOM mode | | `npm run test:xr-harness` | `test/runners/run-xr-containment-harness.cjs` (browser harness, uses Playwright) | After touching table/containment runtimes | +| `npm run test:xr-chart-bounds-harness` | `test/runners/run-xr-chart-bounds-harness.cjs` (generates REAL directory scenes with the compiled generator, opens them with A-Frame + BabiaXR in Playwright, asserts every chart type ends on the table for 3/30/300 files and that row-budgeted charts only ever read the slice; `CODEXR_CHART_BOUNDS_TYPES` / `CODEXR_CHART_BOUNDS_ROWS` narrow it; about 4 minutes) | After touching chart generation, containment, the row slice or the Babia compatibility patches | | `npm run test:xr-mode-harness` | `test/runners/run-xr-mode-cycle-harness.cjs` — static contract over `test/manual/xr-mode-cycle-harness.html`, then (with Playwright) walks the analysis selector through every mode and back, asserting the controller's view/mode state at each step | After touching the analysis-mode controller, mapping UI, historical comparison or dependency graph runtimes | | `npm run test:project-evolution-harness` | `test/runners/run-project-evolution-harness.cjs` — Project Evolution playback harness (screenshots under `output/project-evolution-harness/`) | After touching project-evolution runtime | | `npm run test:xr-immersive-harness` | `test/runners/run-xr-immersive-harness.cjs` — AR/VR semantics against real A-Frame: AR hide/keep sets, rig floor-align + AR recenter, pointer handover; plus a static contract over both scene templates | After touching the scene templates, pointer-policy or immersive-rig | diff --git a/apps/vscode-extension/CHANGELOG.md b/apps/vscode-extension/CHANGELOG.md index 11922448..91fb2e35 100644 --- a/apps/vscode-extension/CHANGELOG.md +++ b/apps/vscode-extension/CHANGELOG.md @@ -39,6 +39,11 @@ - **Historical comparison and project evolution no longer refuse a folder opened through a link.** When the analyzed folder was reached through a symbolic link, a junction, or a shortened Windows path (`C:\Users\JOHNDO~1\...`), Code-XR compared it with the repository path Git reports and wrongly concluded the folder was outside the repository, so the Git-based analyses were unavailable. Both paths are now resolved to their real location before they are compared. - **The installed extension only ever runs the Python analysis scripts it ships with.** If its bundled copy of an analysis script was missing (a damaged or partially deleted install), Code-XR fell back to a developer location two folders above the extension, which in an installed copy is your home folder, and could have run a file found there. That fallback is now limited to development builds; an installed extension reports the missing script instead. - **The analysis backend loads again on Python 3.8 and 3.9.** One type annotation in the line-metrics module used syntax that only exists from Python 3.10, so on 3.8 or 3.9 every analysis failed as soon as the backend loaded, although the extension asks only for Python 3.7 or newer. The annotation now uses the older spelling; results on newer Python versions are unchanged. +- **Charts stay on the analysis table.** Bar, cylinder and map charts could end with their axis hanging up to 2.6 m past the table edge, or squeezed into a thin sliver at one end of a long empty axis, while the scene reported the chart as fitted: + - BabiaXR resizes an axis with an animation that A-Frame 1.7.1 never applies, so an axis kept the length of its first build. Axis lines are now written directly, and a resized axis triggers a new fit. + - The table fit checked the chart's size but not its position: centring the bars could push the axis off one side. The axes are now kept on the table, and a chart that still sticks out is no longer reported as fitted. + - The fit could measure a cached, outdated size of a line that had just changed. Sizes are now re-read when the geometry changes. + - Generated scenes first built every chart over all files and only then switched to the top 20/30 shown. They now build once, from the files that are shown. - A source file of the XR chart-mapping runtime contained a raw control character typed into a string. Behaviour was correct, but the file was invisible to code search and review tools. It now uses the equivalent escape sequence; the runtime value is identical. ## [1.2.0] - 2026-07-30 diff --git a/apps/vscode-extension/package.json b/apps/vscode-extension/package.json index 8ba181cb..c295ca8b 100644 --- a/apps/vscode-extension/package.json +++ b/apps/vscode-extension/package.json @@ -762,6 +762,7 @@ "test:analysis": "node ../../backend/scripts/run-analysis-tests.cjs", "test:htmlanalysis": "node test/runners/run-html-analysis-tests.cjs", "test:xr-harness": "node test/runners/run-xr-containment-harness.cjs", + "test:xr-chart-bounds-harness": "npm run compile-tests && node test/runners/run-xr-chart-bounds-harness.cjs", "test:xr-mode-harness": "node test/runners/run-xr-mode-cycle-harness.cjs", "test:xr-immersive-harness": "node test/runners/run-xr-immersive-harness.cjs", "test:project-evolution-harness": "node test/runners/run-project-evolution-harness.cjs", diff --git a/apps/vscode-extension/src/core/analysis/parsers/directoryXRParser.ts b/apps/vscode-extension/src/core/analysis/parsers/directoryXRParser.ts index 6c856b05..9be612e2 100644 --- a/apps/vscode-extension/src/core/analysis/parsers/directoryXRParser.ts +++ b/apps/vscode-extension/src/core/analysis/parsers/directoryXRParser.ts @@ -42,7 +42,7 @@ import { resolveTemplatePath } from '../../../platform/templatePaths'; * shipped as text in this order. The file parser copies the same set * (test/analysis/xrRuntimeManifestAsymmetry.test.cjs pins the pairing). */ -const DIRECTORY_XR_RUNTIME_ASSETS: ReadonlyArray Promise]> = [ +export const DIRECTORY_XR_RUNTIME_ASSETS: ReadonlyArray Promise]> = [ [CODEXR_COMMON_RUNTIME_OUTPUT_NAME, readCodeXrCommonRuntimeContent], [CODEXR_GIT_REF_PICKER_OUTPUT_NAME, readCodeXrGitRefPickerContent], [CODEXR_AVATAR_RUNTIME_OUTPUT_NAME, readCodeXrAvatarRuntimeContent], diff --git a/apps/vscode-extension/src/core/charts/templateCharts.ts b/apps/vscode-extension/src/core/charts/templateCharts.ts index 8a546da5..1a556240 100644 --- a/apps/vscode-extension/src/core/charts/templateCharts.ts +++ b/apps/vscode-extension/src/core/charts/templateCharts.ts @@ -21,6 +21,13 @@ export { serializeComponentAttributes, }; +/** + * Id of the top-N slice of the `data` producer that row-budgeted charts read. + * Must match `CHART_DATA_SLICE_PREFIX + 'data'` in the mapping-UI runtime + * (chartDataSlice.js); test/charts pins the pairing. + */ +export const CHART_DATA_SLICE_ENTITY_ID = 'codexrChartDataSlice__data'; + export const XR_TABLE_BOOTSTRAP_PLANAR_MAX = 0.84; export const XR_TABLE_STEADY_PLANAR_MIN = 0.78; export const XR_TABLE_STEADY_PLANAR_MAX = 0.92; @@ -71,10 +78,28 @@ function buildChartEntityHtml(options: { const hierarchyLayerStability = profile.preserveRelativeHierarchyLayers ? '\n codexr-boats-layout-stability="enabled: true"' : ''; + // Row-budgeted charts read the runtime's top-N slice from their FIRST + // build. Reading `data` first and being re-pointed later built every chart + // twice, the first time over all rows: an axis sized for 400 files and a + // fit computed on geometry that was about to be replaced. The slice entity + // holds no data at all, so the chart waits for the first real slice + // (analysis-table babiaCompat.js keeps Babia from fetching an empty URL); + // the mapping UI fills it as soon as `data` has rows. + const readsSlice = !!profile.rowBudget; + const sliceEntity = readsSlice + ? ` + ` + : ''; + const finalComponentValue = readsSlice + ? componentValue.replace(/^from:\s*data;/, `from: ${CHART_DATA_SLICE_ENTITY_ID};`) + : componentValue; + if (readsSlice && finalComponentValue === componentValue) { + throw new Error(`Chart template ${options.chartId} must start with "from: data;" to read the row slice`); + } return ` - axis`, which A-Frame 1.7.1 never applies to `line.end` (an axis otherwise keeps the length of its first build forever); every resize asks the enclosing containment for one re-fit. (2) A `babia-queryjson` with neither `data` nor `url` waits instead of fetching the empty URL (the page itself): generated scenes declare the row slice that way, so a row-budgeted chart's first build is already the slice. - Containment applies a per-chart fit strategy (`chartFitProfiles.js` part): `uniform` for circular charts (pie/doughnut stand rotated 90° — one factor on all axes so the disk stays circular), `planar-uniform` for row charts with flat axis labels or round geometry (x/z converge to the same scale value), per-axis for everything else. - `codexr/xr-chart-mapping-ui/xrChartMappingUiRuntime.js` - Owns Field Mapping, live chart switching, contextual panel views and transactional metric mapping. diff --git a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/babiaCompat.js b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/babiaCompat.js new file mode 100644 index 00000000..3ca5b544 --- /dev/null +++ b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/babiaCompat.js @@ -0,0 +1,121 @@ +// == analysisTableRuntime.js | babiaCompat (assembled per manifest.json; see COMPONENTS.md) == + // BabiaXR 1.3.4 resizes an axis by animating `line__axis.end` with + // A-Frame's `animation` component. Under A-Frame 1.7.1 that animation never + // changes the multi-property `line.end`, so an axis keeps the length of its + // FIRST build forever: a chart that shrinks (20-row slice after an all-rows + // build, a re-analysis, a remap, an evolution frame) leaves its axis hanging + // off the table. Every axis line is therefore written directly; the labels + // keep Babia's fade, which animates a plain number and works. + var BABIA_AXIS_COMPONENT_NAMES = ['babia-axis-x', 'babia-axis-y', 'babia-axis-z']; + var BABIA_COMPAT_PATCH_FLAG = '__codexrDirectLine'; + + // A resized axis changes the chart's footprint without any event the + // containment listens to, so a chart first built over more rows kept the + // scale fitted to the long axis (a sliver for ~15 s on 400 rows). Ask the + // enclosing containment for a re-fit once the burst of axis updates (x, y, + // labels) is over; the delay clears requestRenormalize's debounce window. + var AXIS_RESIZE_REFIT_DELAY_MS = 320; + var AXIS_RESIZE_TIMER_KEY = '__codexrAxisResizeRefitTimer'; + + function findContainmentComponent(el) { + var node = el; + while (node) { + var component = node.components && node.components[COMPONENT_NAME]; + if (component) { + return component; + } + node = node.parentNode; + } + return null; + } + + function notifyContainmentOfAxisResize(el) { + var component = findContainmentComponent(el); + if (!component || typeof component.requestRenormalize !== 'function' || typeof setTimeout !== 'function') { + return false; + } + if (component[AXIS_RESIZE_TIMER_KEY]) { + clearTimeout(component[AXIS_RESIZE_TIMER_KEY]); + } + component[AXIS_RESIZE_TIMER_KEY] = setTimeout(function () { + component[AXIS_RESIZE_TIMER_KEY] = null; + component.requestRenormalize('babia-axis-resized'); + }, AXIS_RESIZE_REFIT_DELAY_MS); + return true; + } + + function patchBabiaAxisPrototype(axis) { + var proto = axis ? Object.getPrototypeOf(axis) : null; + if (!proto || typeof proto.updateLine !== 'function' || proto.updateLine[BABIA_COMPAT_PATCH_FLAG]) { + return false; + } + var originalUpdateLine = proto.updateLine; + var directUpdateLine = function (length, color) { + var anim = this.anim; + this.anim = false; + try { + return originalUpdateLine.call(this, length, color); + } finally { + this.anim = anim; + notifyContainmentOfAxisResize(this.el); + } + }; + directUpdateLine[BABIA_COMPAT_PATCH_FLAG] = true; + proto.updateLine = directUpdateLine; + return true; + } + + function installBabiaAxisLineCompat(aframe) { + var patched = []; + if (!aframe || !aframe.components) { + return patched; + } + BABIA_AXIS_COMPONENT_NAMES.forEach(function (name) { + var registered = aframe.components[name]; + var Component = registered && registered.Component; + var proto = Component && Component.prototype; + if (!proto || typeof proto.init !== 'function' || proto.init[BABIA_COMPAT_PATCH_FLAG]) { + return; + } + var originalInit = proto.init; + var patchedInit = function () { + var result = originalInit.apply(this, arguments); + // The Axis class is private to the Babia bundle; its prototype is + // reachable only through an instance, so the first one patches it. + patchBabiaAxisPrototype(this.axis); + return result; + }; + patchedInit[BABIA_COMPAT_PATCH_FLAG] = true; + proto.init = patchedInit; + patched.push(name); + }); + return patched; + } + + // `babia-queryjson` with neither `data` nor `url` fetches the empty URL, + // i.e. the scene page itself, and fails parsing it as JSON. Generated + // scenes declare the row slice that way on purpose: an EMPTY producer, so + // the chart reading it waits for the first real slice instead of building + // over all rows (or over an empty array, which yields -Infinity axes). + function installBabiaQueryJsonCompat(aframe) { + var registered = aframe && aframe.components && aframe.components['babia-queryjson']; + var proto = registered && registered.Component && registered.Component.prototype; + if (!proto || typeof proto.update !== 'function' || proto.update[BABIA_COMPAT_PATCH_FLAG]) { + return false; + } + var originalUpdate = proto.update; + var patchedUpdate = function () { + var data = this.data || {}; + if (!data.data && !data.url) { + return undefined; + } + return originalUpdate.apply(this, arguments); + }; + patchedUpdate[BABIA_COMPAT_PATCH_FLAG] = true; + proto.update = patchedUpdate; + return true; + } + + installBabiaAxisLineCompat(AFRAME); + installBabiaQueryJsonCompat(AFRAME); + diff --git a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/containmentComponentCore.js b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/containmentComponentCore.js index 7841b272..33de6064 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/containmentComponentCore.js +++ b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/containmentComponentCore.js @@ -289,12 +289,16 @@ // guarantees no hard violation and no persistent drift, so a residual // sub-tolerance correction wish must not keep reporting a settled // chart as "still correcting". - var stabilized = (this.settled === true && !transitionActive && !heightOverflow) + // A chart whose axes hang past the usable tabletop is never "ok", even + // when its size fits: the anchor pass shifts it back on its next run. + var overhang = computeContainmentOverhang(measurements, this.data); + var offTable = !!(overhang && (overhang.x > CONTAINMENT_OVERHANG_TOLERANCE || overhang.z > CONTAINMENT_OVERHANG_TOLERANCE)); + var stabilized = !offTable && ((this.settled === true && !transitionActive && !heightOverflow) || (this.renderPhase === 'steady-fit' && (!this.pidController || !this.pidController.active) && !needsCorrection && !transitionActive - && !heightOverflow); + && !heightOverflow)); return { ready: true, valid: true, @@ -304,6 +308,8 @@ ? 'containment-transition-active' : heightOverflow ? 'height-overflow' + : offTable + ? 'off-table' : stabilized ? 'ok' : needsCorrection @@ -312,6 +318,8 @@ details: { phase: this.renderPhase, transitionActive: transitionActive, + overhangX: overhang ? toFixedNumber(overhang.x) : null, + overhangZ: overhang ? toFixedNumber(overhang.z) : null, primaryWidth: toFixedNumber(measurements.primary.size.x), primaryHeight: toFixedNumber(measurements.primary.size.y), primaryDepth: toFixedNumber(measurements.primary.size.z), diff --git a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/diagnosticsAndPid.js b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/diagnosticsAndPid.js index 101554e3..b9154196 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/diagnosticsAndPid.js +++ b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/diagnosticsAndPid.js @@ -252,10 +252,62 @@ var lift = Number.isFinite(surfaceLift) ? Math.max(0, surfaceLift) : 0; var tableTopY = getTableTopY(data) + lift; + var deltaX = data.anchorX - measurements.primary.center.x; + var deltaZ = data.anchorZ - measurements.primary.center.z; + // Centring the PRIMARY bounds (bars, sectors) can push the axes, which + // belong to the containment bounds, past the tabletop: a 3-bar chart has + // its axis running out to one side. Shift just enough to keep the whole + // containment box on the usable top (the region the size fit targets). + if (isFiniteBoundsInfo(measurements.containment)) { + var limits = computeContainmentLimits(data); + deltaX = keepSpanInsideRegion(deltaX, measurements.containment.bounds.min.x, measurements.containment.bounds.max.x, data.anchorX, limits.containmentWidthLimit); + deltaZ = keepSpanInsideRegion(deltaZ, measurements.containment.bounds.min.z, measurements.containment.bounds.max.z, data.anchorZ, limits.containmentDepthLimit); + } + return { - deltaX: data.anchorX - measurements.primary.center.x, + deltaX: deltaX, deltaY: tableTopY - measurements.primary.bounds.min.y, - deltaZ: data.anchorZ - measurements.primary.center.z + deltaZ: deltaZ + }; + } + + // Adjusts a planar shift so that [min, max] + delta lies inside + // [center - size/2, center + size/2]. A span wider than the region is + // centred on it instead (the size fit is what shrinks it). + function keepSpanInsideRegion(delta, min, max, center, size) { + if (!Number.isFinite(delta) || !Number.isFinite(min) || !Number.isFinite(max) || !Number.isFinite(center) || !(size > 0)) { + return delta; + } + var regionMin = center - (size / 2); + var regionMax = center + (size / 2); + if ((max - min) >= size) { + return center - ((min + max) / 2); + } + if (min + delta < regionMin) { + return regionMin - min; + } + if (max + delta > regionMax) { + return regionMax - max; + } + return delta; + } + + var CONTAINMENT_OVERHANG_TOLERANCE = 0.02; + + // Distance (metres) by which the containment bounds stick out of the + // usable tabletop on each planar axis; 0 when inside. + function computeContainmentOverhang(measurements, data) { + if (!measurements || !isFiniteBoundsInfo(measurements.containment) || !data) { + return null; + } + var limits = computeContainmentLimits(data); + var bounds = measurements.containment.bounds; + function overhang(min, max, center, size) { + return Math.max(0, (center - (size / 2)) - min, max - (center + (size / 2))); + } + return { + x: overhang(bounds.min.x, bounds.max.x, data.anchorX, limits.containmentWidthLimit), + z: overhang(bounds.min.z, bounds.max.z, data.anchorZ, limits.containmentDepthLimit) }; } diff --git a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/geometryUtils.js b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/geometryUtils.js index 19bf72ba..671fc168 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/geometryUtils.js +++ b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/geometryUtils.js @@ -349,6 +349,32 @@ return matchesIgnoredContainmentBoundsMeta(collectNodeMeta(node)); } + // three.js caches `geometry.boundingBox` and never invalidates it, while + // Babia axes and A-Frame lines rewrite their positions in place: a cached + // box kept measuring an axis at its old length. Recompute whenever the + // position attribute was replaced or bumped its version since the last + // measurement. + var BOUNDS_STAMP_KEY = '__codexrBoundsStamp'; + function refreshGeometryBoundingBox(geometry) { + if (!geometry || typeof geometry.computeBoundingBox !== 'function') { + return; + } + var position = geometry.attributes && geometry.attributes.position; + var stamp = position ? { attribute: position, version: position.version, count: position.count } : null; + var previous = geometry[BOUNDS_STAMP_KEY]; + var fresh = !!geometry.boundingBox && !!previous && !!stamp + && previous.attribute === stamp.attribute + && previous.version === stamp.version + && previous.count === stamp.count; + if (fresh || (geometry.boundingBox && !stamp)) { + return; + } + geometry.computeBoundingBox(); + if (stamp) { + geometry[BOUNDS_STAMP_KEY] = stamp; + } + } + function buildBoundsFromNodes(three, nodes) { if (!three || !three.Box3 || !three.Vector3 || !Array.isArray(nodes) || nodes.length === 0) { return null; @@ -362,9 +388,7 @@ return; } - if (!node.geometry.boundingBox && typeof node.geometry.computeBoundingBox === 'function') { - node.geometry.computeBoundingBox(); - } + refreshGeometryBoundingBox(node.geometry); if (!node.geometry.boundingBox || typeof node.geometry.boundingBox.clone !== 'function') { return; diff --git a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/manifest.json b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/manifest.json index 0e1909b4..cb6b2d3c 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/manifest.json +++ b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/manifest.json @@ -6,6 +6,7 @@ "containmentLimits.js", "chartFitProfiles.js", "boatsLayoutStability.js", + "babiaCompat.js", "diagnosticsAndPid.js", "containmentComponentCore.js", "measurementAndScaling.js", diff --git a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/policyAndRegistration.js b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/policyAndRegistration.js index 2653a316..8490a667 100644 --- a/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/policyAndRegistration.js +++ b/apps/vscode-extension/templates/components/codexr/analysis-table/analysisTableRuntime/policyAndRegistration.js @@ -419,6 +419,12 @@ buildMeasurementSignature: buildMeasurementSignature, isObject3DVisibleInScene: isObject3DVisibleInScene, computeAnchorOffset: computeAnchorOffset, + keepSpanInsideRegion: keepSpanInsideRegion, + refreshGeometryBoundingBox: refreshGeometryBoundingBox, + computeContainmentOverhang: computeContainmentOverhang, + installBabiaAxisLineCompat: installBabiaAxisLineCompat, + installBabiaQueryJsonCompat: installBabiaQueryJsonCompat, + notifyContainmentOfAxisResize: notifyContainmentOfAxisResize, getTableTopY: getTableTopY, resolveChartFitMode: resolveChartFitMode, resolveChartSurfaceLift: resolveChartSurfaceLift, diff --git a/apps/vscode-extension/templates/components/codexr/xr-chart-mapping-ui/xrChartMappingUiRuntime/chartDataSlice.js b/apps/vscode-extension/templates/components/codexr/xr-chart-mapping-ui/xrChartMappingUiRuntime/chartDataSlice.js index 0e64373a..03dde942 100644 --- a/apps/vscode-extension/templates/components/codexr/xr-chart-mapping-ui/xrChartMappingUiRuntime/chartDataSlice.js +++ b/apps/vscode-extension/templates/components/codexr/xr-chart-mapping-ui/xrChartMappingUiRuntime/chartDataSlice.js @@ -255,6 +255,13 @@ } var currentSource = String(currentData.from); var resolved = resolveChartDataSourceId(chartId, currentSource, mapping); + if (getSourceIdFromSliceId(currentSource) && !getSourceIdFromSliceId(resolved)) { + // Generated scenes start on the slice (an empty one until `data` has + // rows). Falling back to the raw source here would bring back the + // all-rows first build; keep the slice and try again shortly. + synced = false; + return; + } if (resolved !== currentSource) { chartEntity.setAttribute(componentName, 'from', resolved); } else if (!getSourceIdFromSliceId(currentSource)) { diff --git a/apps/vscode-extension/test/README.md b/apps/vscode-extension/test/README.md index eb9b191d..674c6573 100644 --- a/apps/vscode-extension/test/README.md +++ b/apps/vscode-extension/test/README.md @@ -28,7 +28,7 @@ Every `*.test.cjs` below `test/` is collected by `npm run test:unit`, except und - `npm run test:all`: run both the Node and Python suites. - `npm run test:analysis`: per-language end-to-end metrics over `backend/manual_test/` with the pinned lizard. - `npm run test:htmlanalysis`: the HTML/DOM analysis suite. -- `npm run test:xr-harness`, `test:xr-mode-harness`, `test:xr-immersive-harness`, `test:project-evolution-harness`: browser harnesses (Playwright's Chromium and live CDNs; local only). +- `npm run test:xr-harness`, `test:xr-mode-harness`, `test:xr-immersive-harness`, `test:project-evolution-harness`, `test:xr-chart-bounds-harness`: browser harnesses (Playwright's Chromium and live CDNs; local only). The full table, with when to run each, is in `.claude/docs/DEVELOPMENT.md`. diff --git a/apps/vscode-extension/test/analysis/xrChartTableBounds.test.cjs b/apps/vscode-extension/test/analysis/xrChartTableBounds.test.cjs new file mode 100644 index 00000000..5df6247f --- /dev/null +++ b/apps/vscode-extension/test/analysis/xrChartTableBounds.test.cjs @@ -0,0 +1,243 @@ +/** + * Charts end on the table (XR review epic, S3): the BabiaXR compatibility + * patches, the anchor clamp, the fresh bounding boxes and the generated + * scene reading the row slice. The end-to-end check in a real browser is + * `npm run test:xr-chart-bounds-harness`. + */ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const vm = require('node:vm'); + +const projectRoot = path.resolve(__dirname, '..', '..'); +const { readAssembledRuntime } = require(path.join(projectRoot, 'test', 'helpers', 'runtimeAssembly.cjs')); +const { createFakeVscode, withFakeVscode } = require(path.join(projectRoot, 'test', 'helpers', 'fakeVscode.cjs')); +const runtimeSource = readAssembledRuntime('analysis-table', 'analysisTableRuntime.js'); +const mappingUiSource = readAssembledRuntime('xr-chart-mapping-ui', 'xrChartMappingUiRuntime.js'); + +// The shape of BabiaXR 1.3.4's private Axis class: with `anim` on, the line +// end goes through an `animation__axis` attribute, which A-Frame 1.7.1 +// never applies to `line.end`. One class per sandbox: the runtime patches its +// prototype, as it does the real bundle's. +function makeFakeBabiaAxisClass() { + return class FakeBabiaAxis { + constructor(el, axis, anim) { + this.el = el; + this.axis = axis; + this.anim = anim; + } + + updateLine(length) { + const end = { x: 0, y: 0, z: 0 }; + end[this.axis] = length; + if (this.anim) { + this.el.attributes[`animation__${this.axis}axis`] = { property: `line__${this.axis}axis.end`, to: end }; + } else { + this.el.attributes[`line__${this.axis}axis`] = { end }; + } + } + }; +} + +function babiaComponent(axis, FakeBabiaAxis) { + function Component(el) { + this.el = el; + this.data = { animation: true }; + } + Component.prototype.init = function () { + this.axis = new FakeBabiaAxis(this.el, axis, this.data.animation); + }; + return { Component }; +} + +function loadSandbox() { + const timers = []; + const queryJsonUpdates = []; + const FakeBabiaAxis = makeFakeBabiaAxisClass(); + function QueryJson() {} + QueryJson.prototype.update = function () { + queryJsonUpdates.push(Object.assign({}, this.data)); + }; + const sandbox = { + console: { log() {}, warn() {}, error() {}, table() {} }, + setTimeout(callback, delay) { + timers.push({ callback, delay }); + return timers.length; + }, + clearTimeout(id) { + if (timers[id - 1]) { + timers[id - 1].cleared = true; + } + }, + AFRAME: { + components: { + 'babia-axis-x': babiaComponent('x', FakeBabiaAxis), + 'babia-axis-y': babiaComponent('y', FakeBabiaAxis), + 'babia-axis-z': babiaComponent('z', FakeBabiaAxis), + 'babia-queryjson': { Component: QueryJson }, + }, + registerComponent(name, definition) { + this.components[name] = definition; + }, + }, + }; + sandbox.window = sandbox; + vm.runInNewContext(runtimeSource, sandbox, { filename: 'analysisTableRuntime.js' }); + return { + sandbox, + timers, + queryJsonUpdates, + QueryJson, + testing: sandbox.CodeXRAnalysisTableRuntime.__testing, + }; +} + +function boundsInfo(min, max) { + return { + bounds: { min, max }, + size: { x: max.x - min.x, y: max.y - min.y, z: max.z - min.z }, + center: { x: (min.x + max.x) / 2, y: (min.y + max.y) / 2, z: (min.z + max.z) / 2 }, + }; +} + +const TABLE_DATA = { + anchorX: 0, + anchorY: 1, + anchorZ: -18, + targetWidth: 5.614, + targetDepth: 3.218, + tableTopPadding: 0.9, + tableEdgeMargin: 0.18, + tableTopSurfaceOffsetY: -0.08, +}; + +test('Babia axis lines are written directly, so an axis shrinks with its data', () => { + const { sandbox } = loadSandbox(); + for (const name of ['babia-axis-x', 'babia-axis-y', 'babia-axis-z']) { + const { Component } = sandbox.AFRAME.components[name]; + const axisName = name.slice(-1); + const el = { attributes: {}, parentNode: null }; + const instance = new Component(el); + instance.init(); + instance.axis.updateLine(50); + instance.axis.updateLine(25); + assert.deepEqual(el.attributes[`line__${axisName}axis`].end[axisName], 25, name); + assert.equal(el.attributes[`animation__${axisName}axis`], undefined, `${name} still animates its line`); + // The flag is restored: labels keep Babia's fade. + assert.equal(instance.axis.anim, true); + } +}); + +test('installing the Babia compatibility twice does not wrap twice', () => { + const { sandbox, testing } = loadSandbox(); + const initBefore = sandbox.AFRAME.components['babia-axis-x'].Component.prototype.init; + assert.equal(testing.installBabiaAxisLineCompat(sandbox.AFRAME).length, 0); + assert.equal(sandbox.AFRAME.components['babia-axis-x'].Component.prototype.init, initBefore); + assert.equal(testing.installBabiaQueryJsonCompat(sandbox.AFRAME), false); +}); + +test('a resized axis asks its chart containment for one re-fit after the burst', () => { + const { sandbox, timers, testing } = loadSandbox(); + const reasons = []; + const chart = { components: { 'codexr-chart-containment': { requestRenormalize: (reason) => reasons.push(reason) } }, parentNode: null }; + const axisEl = { attributes: {}, parentNode: chart }; + const instance = new sandbox.AFRAME.components['babia-axis-x'].Component(axisEl); + instance.init(); + instance.axis.updateLine(40); + instance.axis.updateLine(20); + const live = timers.filter((timer) => !timer.cleared); + assert.equal(live.length, 1, 'updates in one burst coalesce'); + assert.ok(live[0].delay > 280, 'the re-fit lands after requestRenormalize\'s debounce window'); + live[0].callback(); + assert.deepEqual(reasons, ['babia-axis-resized']); + // An axis outside any chart has nobody to tell. + assert.equal(testing.notifyContainmentOfAxisResize({ parentNode: null }), false); +}); + +test('an empty babia-queryjson waits instead of fetching the page itself', () => { + const { QueryJson, queryJsonUpdates } = loadSandbox(); + const empty = new QueryJson(); + empty.data = { url: '', data: '' }; + empty.update({}); + assert.deepEqual(queryJsonUpdates, []); + const filled = new QueryJson(); + filled.data = { url: '', data: '[{"a":1}]' }; + filled.update({}); + const fromUrl = new QueryJson(); + fromUrl.data = { url: 'data.json', data: '' }; + fromUrl.update({}); + assert.equal(queryJsonUpdates.length, 2); +}); + +test('the anchor keeps the axes on the table when centring the bars would push them off', () => { + const { testing } = loadSandbox(); + // Three bars centred at x = 0, with an axis running 2.4 m to the right of + // them: centring the bars alone leaves the axis 0.33 m past the edge. + const primary = boundsInfo({ x: -1, y: 0.92, z: -18.5 }, { x: 1, y: 1.6, z: -17.5 }); + const containment = boundsInfo({ x: -1, y: 0.92, z: -18.5 }, { x: 4.4, y: 1.6, z: -17.5 }); + const measurements = { full: containment, primary, containment, content: primary, peakHeight: 0.6 }; + const offset = testing.computeAnchorOffset(measurements, TABLE_DATA); + const limit = 6.514 - 0.36; // usable top: table + padding minus the edge margins + const shiftedMax = containment.bounds.max.x + offset.deltaX; + const shiftedMin = containment.bounds.min.x + offset.deltaX; + assert.ok(shiftedMax <= TABLE_DATA.anchorX + limit / 2 + 1e-9, `axis ends at ${shiftedMax}`); + assert.ok(shiftedMin >= TABLE_DATA.anchorX - limit / 2 - 1e-9, `axis starts at ${shiftedMin}`); + assert.equal(offset.deltaZ, TABLE_DATA.anchorZ - primary.center.z, 'z was already inside: plain centring'); + + const overhangBefore = testing.computeContainmentOverhang(measurements, TABLE_DATA); + assert.ok(overhangBefore.x > 1, 'unplaced chart reports its overhang'); +}); + +test('a span wider than the usable top is centred, and an inside span is left alone', () => { + const { testing } = loadSandbox(); + assert.equal(testing.keepSpanInsideRegion(0.5, -1, 1, 0, 4), 0.5); + assert.equal(testing.keepSpanInsideRegion(1.5, -1, 1, 0, 4), 1); + assert.equal(testing.keepSpanInsideRegion(-1.5, -1, 1, 0, 4), -1); + assert.equal(testing.keepSpanInsideRegion(3, -2, 8, 0, 4), -3); + assert.ok(Number.isNaN(testing.keepSpanInsideRegion(Number.NaN, -1, 1, 0, 4))); +}); + +test('bounding boxes are recomputed when a line rewrites its positions in place', () => { + const { testing } = loadSandbox(); + let computed = 0; + const position = { version: 0, count: 2 }; + const geometry = { + attributes: { position }, + boundingBox: null, + computeBoundingBox() { + computed += 1; + this.boundingBox = { maxX: position.version === 0 ? 50 : 25 }; + }, + }; + testing.refreshGeometryBoundingBox(geometry); + testing.refreshGeometryBoundingBox(geometry); + assert.equal(computed, 1, 'an unchanged geometry keeps its cached box'); + assert.equal(geometry.boundingBox.maxX, 50); + position.version += 1; // needsUpdate = true after an in-place rewrite + testing.refreshGeometryBoundingBox(geometry); + assert.equal(computed, 2); + assert.equal(geometry.boundingBox.maxX, 25); + geometry.attributes.position = { version: 1, count: 4 }; // replaced attribute + testing.refreshGeometryBoundingBox(geometry); + assert.equal(computed, 3); +}); + +test('generated row-budgeted charts read the slice from their first build; boats keeps its tree', async () => { + await withFakeVscode(createFakeVscode(), async ({ requireOut }) => { + const { chartTemplates, CHART_DATA_SLICE_ENTITY_ID } = requireOut('core/charts/templateCharts.js'); + const { CHART_PRESENTATION_PROFILES } = requireOut('core/charts/chartPresentation.js'); + // Pinned against the runtime that fills the slice. + assert.match(mappingUiSource, /var CHART_DATA_SLICE_PREFIX = 'codexrChartDataSlice__';/); + assert.equal(CHART_DATA_SLICE_ENTITY_ID, 'codexrChartDataSlice__data'); + for (const chart of chartTemplates) { + const budgeted = !!CHART_PRESENTATION_PROFILES[chart.id]?.rowBudget; + if (budgeted) { + assert.match(chart.htmlTemplate, /<\/a-entity>/, chart.id); + assert.match(chart.htmlTemplate, /="from: codexrChartDataSlice__data;/, chart.id); + assert.doesNotMatch(chart.htmlTemplate, /from: data;/, chart.id); + } else { + assert.doesNotMatch(chart.htmlTemplate, /codexrChartDataSlice__/, chart.id); + } + } + }); +}); diff --git a/apps/vscode-extension/test/baseline/featureBaseline.snapshot.json b/apps/vscode-extension/test/baseline/featureBaseline.snapshot.json index d9c05417..e00306f7 100644 --- a/apps/vscode-extension/test/baseline/featureBaseline.snapshot.json +++ b/apps/vscode-extension/test/baseline/featureBaseline.snapshot.json @@ -169,6 +169,7 @@ "test:project-evolution-harness", "test:python", "test:unit", + "test:xr-chart-bounds-harness", "test:xr-harness", "test:xr-immersive-harness", "test:xr-mode-harness", @@ -404,6 +405,7 @@ "components/codexr/analysis-mode/analysisModeRuntime/snapshotsAndLifecycles.js", "components/codexr/analysis-mode/analysisModeRuntime/surfaceAndRefresh.js", "components/codexr/analysis-mode/analysisModeRuntime/transitionsAndViews.js", + "components/codexr/analysis-table/analysisTableRuntime/babiaCompat.js", "components/codexr/analysis-table/analysisTableRuntime/boatsLayoutStability.js", "components/codexr/analysis-table/analysisTableRuntime/chartFitProfiles.js", "components/codexr/analysis-table/analysisTableRuntime/containmentComponentCore.js", diff --git a/apps/vscode-extension/test/runners/run-xr-chart-bounds-harness.cjs b/apps/vscode-extension/test/runners/run-xr-chart-bounds-harness.cjs new file mode 100644 index 00000000..392deace --- /dev/null +++ b/apps/vscode-extension/test/runners/run-xr-chart-bounds-harness.cjs @@ -0,0 +1,240 @@ +/** + * Chart-bounds harness (XR review epic, S3): generates REAL directory scenes + * with the compiled generator and runtime assets, opens each one in headless + * Chromium with A-Frame and BabiaXR, and asserts that every chart type ends on + * the analysis table — axes included — for 3, 30 and 300 files. + * + * Opt-in like the other browser harnesses (it needs Playwright's Chromium and + * the A-Frame/BabiaXR CDNs): `npm run test:xr-chart-bounds-harness`. + * CODEXR_CHART_BOUNDS_TYPES=bars,pie and CODEXR_CHART_BOUNDS_ROWS=3,300 narrow it. + */ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const http = require('node:http'); +const os = require('node:os'); +const path = require('node:path'); + +const { createFakeVscode, fakeExtensionContext, withFakeVscode } = require('../helpers/fakeVscode.cjs'); + +const projectRoot = path.resolve(__dirname, '..', '..'); +const CHART_TYPES = (process.env.CODEXR_CHART_BOUNDS_TYPES || 'bars,barsmap,cyls,cylsmap,pie,donut,bubbles,boats').split(','); +const ROW_COUNTS = (process.env.CODEXR_CHART_BOUNDS_ROWS || '3,30,300').split(',').map(Number); +const SETTLE_TIMEOUT_MS = 25000; +// The physical tabletop (codexr-analysis-table) and how far a mesh may poke +// past it (float noise, sub-centimetre bevels). +const TABLE = { width: 6.514, depth: 4.118 }; +const TOLERANCE_M = 0.02; +const SLICE_ID = 'codexrChartDataSlice__data'; + +const FIELD_TYPES = { + fileName: 'text', filePath: 'text', relativePath: 'text', language: 'text', + totalLines: 'numeric', codeLines: 'numeric', commentLines: 'numeric', blankLines: 'numeric', + commentRatio: 'numeric', classCount: 'numeric', functionCount: 'numeric', maxComplexity: 'numeric', + cyclomaticComplexityNumber: 'numeric', fileSizeBytes: 'numeric', +}; + +const MAPPINGS = { + boats: { area: 'functionCount', height: 'totalLines', color: 'cyclomaticComplexityNumber' }, + bars: { x_axis: 'fileName', height: 'totalLines' }, + barsmap: { x_axis: 'fileName', z_axis: 'language', height: 'totalLines' }, + cyls: { x_axis: 'fileName', height: 'totalLines', radius: 'cyclomaticComplexityNumber' }, + cylsmap: { x_axis: 'fileName', z_axis: 'language', height: 'totalLines', radius: 'cyclomaticComplexityNumber' }, + pie: { key: 'fileName', size: 'totalLines' }, + donut: { key: 'fileName', size: 'totalLines' }, + bubbles: { x_axis: 'fileName', z_axis: 'language', height: 'totalLines', radius: 'cyclomaticComplexityNumber' }, +}; + +function makeRows(count) { + let seed = 7; + const random = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); + const languages = ['TypeScript', 'JavaScript', 'Python', 'Go', 'Rust']; + const directories = ['src/core', 'src/features/a', 'src/features/b', 'src/platform', 'lib/x/y', 'test']; + return Array.from({ length: count }, (_, index) => { + const directory = directories[index % directories.length]; + const fileName = `file_${index}.ts`; + const totalLines = Math.floor(10 + random() * 2000); + return { + fileName, filePath: `/proj/${directory}/${fileName}`, relativePath: `${directory}/${fileName}`, + language: languages[index % languages.length], totalLines, + codeLines: Math.floor(totalLines * 0.8), commentLines: Math.floor(totalLines * 0.1), + blankLines: Math.floor(totalLines * 0.1), commentRatio: 0.1, classCount: Math.floor(random() * 5), + functionCount: 1 + Math.floor(random() * 60), maxComplexity: 1 + Math.floor(random() * 40), + cyclomaticComplexityNumber: +(1 + random() * 12).toFixed(2), fileSizeBytes: totalLines * 30, + }; + }); +} + +/** Writes the same files the directory parser produces into `outDir`. */ +async function generateScene(outDir, chartId, rowCount) { + fs.mkdirSync(outDir, { recursive: true }); + const rows = makeRows(rowCount); + await withFakeVscode(createFakeVscode(), async ({ requireOut }) => { + const { TemplateProcessor } = requireOut('core/charts/processing/templateProcessor.js'); + const { DIRECTORY_XR_RUNTIME_ASSETS } = requireOut('core/analysis/parsers/directoryXRParser.js'); + const { readCodeXrRoomTextureContents } = requireOut('core/analysis/scene-assets/codexrRoomComponentAsset.js'); + const context = fakeExtensionContext({ extensionPath: projectRoot }); + requireOut('core/charts/settings/settingsAccessors.js').initializeSettingsAccessors(context); + const mappings = Object.entries(MAPPINGS[chartId]).map(([dimension, dataField]) => ({ dimension, dataField })); + const result = await TemplateProcessor.generateXRVisualization( + chartId, mappings, 'Directory Analysis: proj', 'data.json', context, path.join(outDir, 'index.html'), rows, + { babiaUiVisibleByDefault: true, xrTargetType: 'directory', fieldTypeMap: FIELD_TYPES }, + ); + assert.ok(result.success, `scene generation failed for ${chartId}: ${result.error}`); + fs.copyFileSync(path.join(projectRoot, 'templates', 'xr', 'sse', 'live_sse_fileXR.js'), path.join(outDir, 'main.js')); + for (const [outputName, readContent] of DIRECTORY_XR_RUNTIME_ASSETS) { + fs.writeFileSync(path.join(outDir, outputName), await readContent(projectRoot)); + } + for (const asset of await readCodeXrRoomTextureContents(projectRoot)) { + const target = path.join(outDir, asset.relativeOutputPath); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, asset.content); + } + }); + fs.writeFileSync(path.join(outDir, 'data.json'), JSON.stringify(rows)); +} + +function serve(directory) { + const types = { '.html': 'text/html', '.js': 'application/javascript', '.json': 'application/json', '.svg': 'image/svg+xml' }; + const server = http.createServer((request, response) => { + const { pathname } = new URL(request.url, 'http://localhost'); + if (pathname === '/events') { + // Live reload stays connected and silent. + response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' }); + response.write(': ready\n\n'); + return; + } + const filePath = path.join(directory, decodeURIComponent(pathname === '/' ? '/index.html' : pathname)); + if (!filePath.startsWith(directory) || !fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { + response.writeHead(404); + response.end(); + return; + } + response.writeHead(200, { 'Content-Type': types[path.extname(filePath)] || 'application/octet-stream' }); + fs.createReadStream(filePath).pipe(response); + }); + return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve({ + url: `http://127.0.0.1:${server.address().port}/`, + close: () => { server.closeAllConnections(); return new Promise((done) => server.close(done)); }, + }))); +} + +// World-space bounds of every visible non-text mesh under #chart (text labels +// are camera-facing billboards and legitimately overhang), the containment +// status, and which producer the Babia component reads. +function probeChart(table) { + const el = document.querySelector('#chart'); + const THREE = window.AFRAME.THREE; + const containment = el && el.components['codexr-chart-containment']; + if (!el || !containment) { + return null; + } + el.object3D.updateMatrixWorld(true); + const isText = (object) => { + for (let node = object; node && node !== el.object3D; node = node.parent) { + if (node.el && (node.el.tagName === 'A-TEXT' || node.el.hasAttribute('text') || node.el.hasAttribute('troika-text'))) { + return true; + } + } + return false; + }; + const box = new THREE.Box3(); + let meshes = 0; + el.object3D.traverseVisible((object) => { + if (!object.geometry || isText(object)) { + return; + } + object.geometry.computeBoundingBox(); + const bounds = object.geometry.boundingBox.clone().applyMatrix4(object.matrixWorld); + if (Number.isFinite(bounds.min.x) && Number.isFinite(bounds.max.x)) { + box.union(bounds); + meshes += 1; + } + }); + const data = containment.data; + const overhang = (min, max, center, size) => Math.max(0, (center - size / 2) - min, max - (center + size / 2)); + const component = Object.keys(el.components).find((name) => name.startsWith('babia-')); + const status = containment.getChartStatus(); + return { + meshes, + from: component ? (el.getAttribute(component) || {}).from : null, + offTableX: meshes ? overhang(box.min.x, box.max.x, data.anchorX, table.width) : 0, + offTableZ: meshes ? overhang(box.min.z, box.max.z, data.anchorZ, table.depth) : 0, + width: meshes ? box.max.x - box.min.x : 0, + stabilized: !!(status && status.stabilized), + reason: status && status.reason, + }; +} + +async function checkScene(browser, chartId, rowCount, workRoot) { + const directory = path.join(workRoot, `${chartId}-${rowCount}`); + await generateScene(directory, chartId, rowCount); + const html = fs.readFileSync(path.join(directory, 'index.html'), 'utf8'); + const budgeted = chartId !== 'boats'; + if (budgeted) { + // CHARTS-6: the generated chart reads the row slice from its first build. + assert.match(html, new RegExp(`id="${SLICE_ID}"`), `${chartId}: slice entity missing`); + assert.match(html, new RegExp(`from: ${SLICE_ID};`), `${chartId}: chart does not read the slice`); + } + const server = await serve(directory); + const page = await browser.newPage({ viewport: { width: 1000, height: 700 } }); + const pageErrors = []; + page.on('pageerror', (error) => pageErrors.push(String(error && error.message || error))); + try { + await page.goto(server.url, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction(() => document.querySelector('a-scene')?.hasLoaded, null, { timeout: 60000 }); + const started = Date.now(); + let probe = null; + const sources = new Set(); + while (Date.now() - started < SETTLE_TIMEOUT_MS) { + probe = await page.evaluate(probeChart, TABLE); + if (probe && probe.from) { + sources.add(probe.from); + } + if (probe && probe.meshes > 0 && probe.stabilized && Date.now() - started > 3000) { + break; + } + await page.waitForTimeout(250); + } + const label = `${chartId} with ${rowCount} files`; + assert.ok(probe && probe.meshes > 0, `${label}: nothing rendered`); + assert.ok(probe.stabilized, `${label}: never stabilized (last reason ${probe.reason})`); + assert.ok(probe.offTableX <= TOLERANCE_M && probe.offTableZ <= TOLERANCE_M, + `${label}: ends off the table by x=${probe.offTableX.toFixed(3)} m, z=${probe.offTableZ.toFixed(3)} m`); + if (budgeted) { + assert.deepEqual([...sources], [SLICE_ID], `${label}: chart read ${[...sources].join(', ')}`); + } + assert.deepEqual(pageErrors, [], `${label}: page errors`); + console.log(`[chart-bounds] ${label}: ok (width ${probe.width.toFixed(2)} m, settled in ${Date.now() - started} ms)`); + } finally { + await page.close(); + await server.close(); + } +} + +async function main() { + let chromium; + try { + ({ chromium } = require('playwright')); + } catch { + console.log('[chart-bounds] Playwright is not installed; skipped.'); + return; + } + const workRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-chart-bounds-')); + const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'] }); + try { + for (const chartId of CHART_TYPES) { + for (const rowCount of ROW_COUNTS) { + await checkScene(browser, chartId, rowCount, workRoot); + } + } + } finally { + await browser.close(); + fs.rmSync(workRoot, { recursive: true, force: true }); + } + console.log('[chart-bounds] Chart bounds harness passed.'); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/package.json b/package.json index 853dc395..657079c2 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "test:analysis": "npm run test:analysis --workspace=code-xr", "test:htmlanalysis": "npm run test:htmlanalysis --workspace=code-xr", "test:xr-harness": "npm run test:xr-harness --workspace=code-xr", + "test:xr-chart-bounds-harness": "npm run test:xr-chart-bounds-harness --workspace=code-xr", "test:xr-mode-harness": "npm run test:xr-mode-harness --workspace=code-xr", "test:xr-immersive-harness": "npm run test:xr-immersive-harness --workspace=code-xr", "test:project-evolution-harness": "npm run test:project-evolution-harness --workspace=code-xr",