diff --git a/packages/core/src/agent-operations/move-plan.ts b/packages/core/src/agent-operations/move-plan.ts index a1bd8d883f..2e6456898a 100644 --- a/packages/core/src/agent-operations/move-plan.ts +++ b/packages/core/src/agent-operations/move-plan.ts @@ -269,25 +269,29 @@ function planOpeningMove( : target.y === undefined ? node.position[1] : target.y + node.height / 2 - const { clampedX, clampedY, fits } = + // Fold transomHeight into cutout.height on purpose so clampDoorToWall slides the full opening instead of shrinking the transom. + const doorClamp = node.type === 'door' ? clampDoorToWall( wall, rawX, node.width, - node.height, - node, + cutout.height, + { ...node, transomHeight: undefined }, nodes as Record, ) - : clampWindowToWall( - wall, - rawX, - rawY, - node.width, - node.height, - nodes as Record, - ) - if (!fits) refuseOpeningAboveSlope(wall, nodes, node.type, node.width, node.height) + : null + const { clampedX, clampedY, fits } = doorClamp + ? { clampedX: doorClamp.clampedX, clampedY: rawY, fits: doorClamp.fits } + : clampWindowToWall( + wall, + rawX, + rawY, + node.width, + node.height, + nodes as Record, + ) + if (!fits) refuseOpeningAboveSlope(wall, nodes, node.type, cutout.width, cutout.height) // Checked where the clamp put the door: under a sloped top it may have slid to the high end. if (node.type === 'door') { const wallHeight = diff --git a/packages/core/src/building/wall-openings-slope.test.ts b/packages/core/src/building/wall-openings-slope.test.ts index 5c99915100..2be17af679 100644 --- a/packages/core/src/building/wall-openings-slope.test.ts +++ b/packages/core/src/building/wall-openings-slope.test.ts @@ -165,4 +165,45 @@ describe('agents refuse an opening no stretch of a sloped wall can take', () => expect(refusal(() => move(withOpening(sloped, door), 'door_slope'))).toBe('wall_too_low') expect(refusal(() => move(withOpening({}, door), 'door_slope'))).toBeNull() }) + + test('moving a door with a transom along a sloped wall slides until the full opening fits (#1252)', () => { + // 1 m at start rising to 3 m at x = 4 m: a 2.1 m door with a 0.4 m transom (2.5 m cutout) + // needs ceiling >= 2.5 m, which starts at x = 3.0 m (opening centre >= 3.45 m). + const rising = { height: 1, endHeightOffset: 2 } + const transomDoor = DoorNode.parse({ + ...door, + position: [2.6, 1.05, 0], + width: 0.9, + height: 2.1, + transomHeight: 0.4, + }) + const moved = move(withOpening(rising, transomDoor), 'door_slope') + expect(moved.result.clamped).toBe(true) + expect(moved.result.position[0]).toBeCloseTo(3.45, 4) + expect(moved.result.position[1]).toBeCloseTo(1.05, 6) + + // With sidelightLeft = 0.2 and transomHeight = 0.2 (1.1 m x 2.3 m cutout, leafOffsetX = +0.1 m): + // ceiling >= 2.3 m starts at x = 2.6 m, so cutout centre clamps to 3.15 m and leaf X lands at 3.25 m. + const sidelightTransomDoor = DoorNode.parse({ + ...door, + position: [2.6, 1.05, 0], + width: 0.9, + height: 2.1, + sidelightLeft: 0.2, + transomHeight: 0.2, + }) + const movedSidelight = move(withOpening(rising, sidelightTransomDoor), 'door_slope') + expect(movedSidelight.result.clamped).toBe(true) + expect(movedSidelight.result.position[0]).toBeCloseTo(3.25, 4) + expect(movedSidelight.result.position[1]).toBeCloseTo(1.05, 6) + + // Refused only when no stretch of the sloped wall clears door + transom (2.7 m cutout needs x >= 3.4 m, width 0.9 m needs 3.4 + 0.9 = 4.3 m > 4 m) + const tooTallTransom = DoorNode.parse({ + ...transomDoor, + transomHeight: 0.6, + }) + expect(refusal(() => move(withOpening(rising, tooTallTransom), 'door_slope'))).toBe( + 'wall_too_low', + ) + }) }) diff --git a/packages/editor/src/lib/glb-export-wall-t-junctions.test.ts b/packages/editor/src/lib/glb-export-wall-t-junctions.test.ts new file mode 100644 index 0000000000..38875b12a9 --- /dev/null +++ b/packages/editor/src/lib/glb-export-wall-t-junctions.test.ts @@ -0,0 +1,203 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import { + type AnyNode, + BuildingNode, + LevelNode, + SiteNode, + sceneRegistry, + useScene, + WallNode, + WindowNode, +} from '@pascal-app/core' +import { runWallBuildFrame } from '@pascal-app/viewer' +import * as THREE from 'three' +import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js' +import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js' +import { prepareSceneForExport } from './glb-export' + +function triangles(geometry: THREE.BufferGeometry): THREE.Vector3[][] { + const position = geometry.getAttribute('position') + const index = geometry.index + const count = index?.count ?? position.count + const out: THREE.Vector3[][] = [] + for (let offset = 0; offset < count; offset += 3) { + out.push( + [0, 1, 2].map((corner) => + new THREE.Vector3().fromBufferAttribute( + position, + index ? index.getX(offset + corner) : offset + corner, + ), + ), + ) + } + return out +} + +function countTJunctions(geometry: THREE.BufferGeometry): number { + const tris = triangles(geometry) + const vertices = tris.flat() + const line = new THREE.Line3() + const closest = new THREE.Vector3() + let count = 0 + for (const tri of tris) { + for (let k = 0; k < 3; k += 1) { + line.set(tri[k]!, tri[(k + 1) % 3]!) + const length = line.distance() + if (length < 1e-4) continue + for (const vertex of vertices) { + const t = line.closestPointToPointParameter(vertex, false) + if (t * length < 1e-4 || (1 - t) * length < 1e-4) continue + line.at(t, closest) + if (closest.distanceTo(vertex) < 1e-6) count += 1 + } + } + } + return count +} + +function area(geometry: THREE.BufferGeometry): number { + return triangles(geometry).reduce( + (sum, [a, b, c]) => sum + new THREE.Triangle(a, b, c).getArea(), + 0, + ) +} + +async function exportGlb(scene: THREE.Object3D): Promise { + const originalFileReader = globalThis.FileReader + class ExportFileReader { + result: ArrayBuffer | null = null + onloadend: (() => void) | null = null + readAsArrayBuffer(blob: Blob) { + void blob.arrayBuffer().then((buffer) => { + this.result = buffer + this.onloadend?.() + }) + } + } + globalThis.FileReader = ExportFileReader as unknown as typeof FileReader + try { + return (await new GLTFExporter().parseAsync(scene, { binary: true })) as ArrayBuffer + } finally { + globalThis.FileReader = originalFileReader + } +} + +async function parseGlb(buffer: ArrayBuffer): Promise { + const gltf = await new GLTFLoader().parseAsync(buffer, '') + return gltf.scene +} + +afterEach(() => { + sceneRegistry.clear() +}) + +describe('deferred wall T-junction repair on export (#1273)', () => { + test('live walls stay deferred while exported GLB repairs T-junctions without touching the live mesh', async () => { + const previousScene = useScene.getState() + const level = LevelNode.parse({ id: 'level_tj', level: 0, parentId: 'building_tj' }) + const windowNode = WindowNode.parse({ + id: 'window_tj', + wallId: 'wall_tj_main', + parentId: 'wall_tj_main', + position: [2.5, 1.4, 0], + width: 1.2, + height: 1.2, + }) + const mainWall = WallNode.parse({ + id: 'wall_tj_main', + parentId: level.id, + children: [windowNode.id], + start: [0, 0], + end: [6, 0], + height: 2.6, + thickness: 0.2, + }) + const crossWall = WallNode.parse({ + id: 'wall_tj_cross', + parentId: level.id, + start: [3, 0], + end: [3, 4], + height: 2.6, + thickness: 0.2, + }) + const building = BuildingNode.parse({ + id: 'building_tj', + parentId: 'site_tj', + children: [level.id], + }) + const site = SiteNode.parse({ + id: 'site_tj', + children: [building.id], + }) + const nodes: Record = { + [site.id]: site, + [building.id]: building, + [level.id]: { ...level, children: [mainWall.id, crossWall.id] }, + [mainWall.id]: mainWall, + [crossWall.id]: crossWall, + [windowNode.id]: windowNode, + } + + const root = new THREE.Group() + const wallMaterial = [ + new THREE.MeshStandardMaterial({ color: '#cccccc', name: 'base' }), + new THREE.MeshStandardMaterial({ color: '#dddddd', name: 'front' }), + new THREE.MeshStandardMaterial({ color: '#eeeeee', name: 'back' }), + ] + const mainMesh = new THREE.Mesh(new THREE.BufferGeometry(), wallMaterial) + mainMesh.name = mainWall.id + const crossMesh = new THREE.Mesh(new THREE.BufferGeometry(), wallMaterial) + crossMesh.name = crossWall.id + root.add(mainMesh, crossMesh) + sceneRegistry.nodes.set(mainWall.id, mainMesh) + sceneRegistry.nodes.set(crossWall.id, crossMesh) + + useScene.setState({ + nodes: nodes as never, + dirtyNodes: new Set([mainWall.id, crossWall.id] as never), + }) + + let prepared: ReturnType | null = null + try { + runWallBuildFrame() + + // Live wall mesh defers T-junction repair. + expect(mainMesh.geometry.userData.wallTJunctions).toBe('deferred') + const liveTJunctions = countTJunctions(mainMesh.geometry) + expect(liveTJunctions).toBeGreaterThan(0) + const liveArea = area(mainMesh.geometry) + + // Export preparation repairs the cloned wall meshes without mutating the live mesh. + prepared = prepareSceneForExport(root, nodes, { onlyVisible: false }) + expect(mainMesh.geometry.userData.wallTJunctions).toBe('deferred') + expect(countTJunctions(mainMesh.geometry)).toBe(liveTJunctions) + + const exportedMain = prepared.scene.getObjectByName(mainWall.id) as THREE.Mesh + expect(exportedMain).toBeDefined() + expect(exportedMain.geometry.userData.wallTJunctions).toBeUndefined() + expect(countTJunctions(exportedMain.geometry)).toBe(0) + expect(area(exportedMain.geometry)).toBeCloseTo(liveArea, 5) + expect(exportedMain.geometry.getAttribute('normal')).toBeDefined() + expect(exportedMain.geometry.getAttribute('uv')).toBeDefined() + expect(exportedMain.geometry.getAttribute('uv2')).toBeDefined() + + // Round-trip through GLTFExporter and GLTFLoader: exported GLB has 0 T-junctions. + const glb = await exportGlb(prepared.scene) + const loaded = await parseGlb(glb) + let loadedMeshCount = 0 + loaded.traverse((obj) => { + if (obj instanceof THREE.Mesh && obj.geometry) { + loadedMeshCount += 1 + expect(countTJunctions(obj.geometry)).toBe(0) + } + }) + expect(loadedMeshCount).toBeGreaterThanOrEqual(2) + } finally { + prepared?.dispose() + mainMesh.geometry.dispose() + crossMesh.geometry.dispose() + for (const m of wallMaterial) m.dispose() + useScene.setState(previousScene) + } + }) +}) diff --git a/packages/editor/src/lib/glb-export.ts b/packages/editor/src/lib/glb-export.ts index f240ab4b80..635bf945fd 100644 --- a/packages/editor/src/lib/glb-export.ts +++ b/packages/editor/src/lib/glb-export.ts @@ -28,6 +28,7 @@ import { isViewerPresentationTextureBorrowed, poseDoorMovingParts, poseWindowMovingParts, + repairDeferredWallTJunctions, restoreWindowRollerShutter, SCENE_LAYER, snapLevelsToTruePositions, @@ -596,6 +597,27 @@ async function completeSceneExportPreparation( } } +function repairDeferredWallMeshesInScene(scene: THREE.Object3D): void { + const deferredWallMeshes: THREE.Mesh[] = [] + const geometryRefCounts = new Map() + scene.traverse((object) => { + const mesh = object as THREE.Mesh + if (mesh.isMesh !== true || !mesh.geometry) return + geometryRefCounts.set(mesh.geometry, (geometryRefCounts.get(mesh.geometry) ?? 0) + 1) + if (mesh.geometry.userData.wallTJunctions === 'deferred') { + deferredWallMeshes.push(mesh) + } + }) + for (const mesh of deferredWallMeshes) { + const sharedCount = geometryRefCounts.get(mesh.geometry) ?? 1 + if (sharedCount > 1) { + geometryRefCounts.set(mesh.geometry, sharedCount - 1) + mesh.geometry = mesh.geometry.clone() + } + repairDeferredWallTJunctions(mesh) + } +} + function finishSceneExportPreparation(preparation: SceneExportPreparation): GlbExport { const { scene, cloneByOriginal, nodes, options, registryEntries } = preparation const identityNodes = new Set() @@ -605,6 +627,7 @@ function finishSceneExportPreparation(preparation: SceneExportPreparation): GlbE } const warnings = pruneNonRenderableMeshes(scene, identityNodes) + repairDeferredWallMeshesInScene(scene) sanitizeMaterialGroups(scene, identityNodes) convertMaterials(scene, options.textures ?? 'embed', options.purpose ?? 'viewer') diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts index 52404a93d4..e830d57198 100644 --- a/packages/viewer/src/index.ts +++ b/packages/viewer/src/index.ts @@ -589,10 +589,12 @@ export { generateExtrudedWall, getPendingWallRebuildCount, isWallInitialBuildActive, + repairDeferredWallTJunctions, runWallBuildFrame, type WallGeometryAdapter, type WallGeometryAdapterContext, WallSystem, + type WallTJunctionMode, } from './systems/wall/wall-system' export { advanceWindowAnimations, diff --git a/packages/viewer/src/systems/wall/wall-system.tsx b/packages/viewer/src/systems/wall/wall-system.tsx index 64bce10975..7a5369d1a2 100644 --- a/packages/viewer/src/systems/wall/wall-system.tsx +++ b/packages/viewer/src/systems/wall/wall-system.tsx @@ -1199,6 +1199,8 @@ function updateWallGeometry( terrainBottomAt, slabSupport.faceDatum, buildWallFinishLayout(node, getCachedLevelZones(node, nodes)), + nodes, + 'deferred', ) const wallAngle = Math.atan2(node.end[1] - node.start[1], node.end[0] - node.start[0]) // World transform the render mesh will apply (position + Y-rotation below). @@ -1232,6 +1234,9 @@ function updateWallGeometry( planeTop, terrainBottomAt, slabSupport.faceDatum, + undefined, + nodes, + 'deferred', ) collisionMesh.geometry.dispose() collisionMesh.geometry = collisionGeo @@ -1508,12 +1513,16 @@ function mergeWallTerrainFill( wall: WallNode, boundaryEdges: TaggedWallBoundaryEdge[], finish: WallFinishContext, + tJunctions: WallTJunctionMode = 'repaired', ): THREE.BufferGeometry { const present = fills.filter((fill): fill is THREE.BufferGeometry => fill !== null) if (present.length === 0) return body const bodyGeometry = body.index ? body.toNonIndexed() : body - if (bodyGeometry !== body) body.dispose() + if (bodyGeometry !== body) { + bodyGeometry.userData = { ...body.userData } + body.dispose() + } // The fill is part of each face below the base: it splits at the same finish bounds. const planes = getWallFinishSplitPlanes(finish) const splitFills = present.map((fill) => splitGeometryAtPlanes(fill, planes.y, planes.x)) @@ -1527,7 +1536,47 @@ function mergeWallTerrainFill( bodyGeometry.dispose() for (const fill of splitFills) fill.dispose() - return finishWallFaces(merged, wall, boundaryEdges, finish) + return finishWallFaces(merged, wall, boundaryEdges, finish, tJunctions) +} + +/** + * `repaired` (default) removes T-junctions on every wall build. `deferred` + * skips the repair during live editing and stamps `userData.wallTJunctions = + * 'deferred'` so export preparation can run it on demand on cloned meshes. + */ +export type WallTJunctionMode = 'repaired' | 'deferred' + +/** + * Runs deferred T-junction repair on a wall mesh marked by + * {@link generateExtrudedWall} with `tJunctions = 'deferred'`, recomputing + * vertex normals and the same level-relative planar UVs as the live build, and + * clears the deferred marker. Returns `true` when triangles were split. + */ +export function repairDeferredWallTJunctions(mesh: THREE.Mesh): boolean { + const geometry = mesh.geometry + if (geometry?.userData.wallTJunctions !== 'deferred') return false + + const { wallTJunctions: _deferred, ...preservedUserData } = geometry.userData + const hadUV = geometry.hasAttribute('uv') + const repaired = repairWallTJunctions(geometry) + if (repaired === geometry) { + delete geometry.userData.wallTJunctions + return false + } + + repaired.computeVertexNormals() + ensureRenderableGeometryAttributes(repaired) + repaired.userData = preservedUserData + + let finalGeometry = repaired + if (hadUV) { + mesh.updateMatrix() + finalGeometry = applyWorldPlanarWallUVs(repaired, mesh.matrix) + } + finalGeometry.computeBoundingBox() + finalGeometry.computeBoundingSphere() + mesh.geometry = finalGeometry + return true } /** @@ -1541,9 +1590,15 @@ function finishWallFaces( wall: WallNode, boundaryEdges: TaggedWallBoundaryEdge[], finish: WallFinishContext, + tJunctions: WallTJunctionMode = 'repaired', ): THREE.BufferGeometry { geometry.computeVertexNormals() assignWallMaterialGroups(geometry, wall, boundaryEdges, finish) + if (tJunctions === 'deferred') { + geometry.userData.wallTJunctions = 'deferred' + ensureRenderableGeometryAttributes(geometry) + return geometry + } const repaired = repairWallTJunctions(geometry) if (repaired !== geometry) repaired.computeVertexNormals() ensureRenderableGeometryAttributes(repaired) @@ -1638,6 +1693,7 @@ export function generateExtrudedWall( faceBase?: { a: readonly WallSlabSupportSegment[]; b: readonly WallSlabSupportSegment[] }, finishLayout: WallFinishLayout = buildWallFinishLayout(wallNode, []), sceneNodes: Readonly> = useScene.getState().nodes, + tJunctions: WallTJunctionMode = 'repaired', ): THREE.BufferGeometry { const wallStart: Point2D = { x: wallNode.start[0], y: wallNode.start[1] } const wallEnd: Point2D = { x: wallNode.end[0], y: wallNode.end[1] } @@ -1906,9 +1962,17 @@ export function generateExtrudedWall( wallNode, boundaryEdges, finish, + tJunctions, ) return withWallFinishData( - mergeWallTerrainFill(splitGeometry, belowBaseFills, wallNode, boundaryEdges, finish), + mergeWallTerrainFill( + splitGeometry, + belowBaseFills, + wallNode, + boundaryEdges, + finish, + tJunctions, + ), finish, ) } @@ -1960,10 +2024,18 @@ export function generateExtrudedWall( wallNode, boundaryEdges, finish, + tJunctions, ) return withWallFinishData( - mergeWallTerrainFill(splitResultGeometry, belowBaseFills, wallNode, boundaryEdges, finish), + mergeWallTerrainFill( + splitResultGeometry, + belowBaseFills, + wallNode, + boundaryEdges, + finish, + tJunctions, + ), finish, ) } diff --git a/packages/viewer/src/systems/wall/wall-t-junctions.test.ts b/packages/viewer/src/systems/wall/wall-t-junctions.test.ts index c9e95a6d43..be5665d2bb 100644 --- a/packages/viewer/src/systems/wall/wall-t-junctions.test.ts +++ b/packages/viewer/src/systems/wall/wall-t-junctions.test.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test' import { calculateLevelMiters, sceneRegistry, WallNode, WindowNode } from '@pascal-app/core' import * as THREE from 'three' -import { generateExtrudedWall } from './wall-system' +import { generateExtrudedWall, repairDeferredWallTJunctions } from './wall-system' import { repairWallTJunctions } from './wall-t-junctions' function triangles(geometry: THREE.BufferGeometry): THREE.Vector3[][] { @@ -94,8 +94,69 @@ describe('wall T-junctions', () => { try { const geometry = generateExtrudedWall(wall, [window], calculateLevelMiters([wall])) expect(countTJunctions(geometry)).toBe(0) + expect(geometry.userData.wallTJunctions).toBeUndefined() } finally { sceneRegistry.nodes.delete(wall.id) } }) + + test('deferred mode skips repair and marks geometry; repairDeferredWallTJunctions finishes it on demand', () => { + const wall = WallNode.parse({ + id: 'wall_t-junction-deferred', + start: [1, 2], + end: [6, 2], + height: 2.5, + thickness: 0.2, + }) + const window = WindowNode.parse({ + id: 'window_t-junction-deferred', + wallId: wall.id, + position: [2.5, 1.4, 0], + width: 1.2, + height: 1.2, + }) + const mesh = new THREE.Mesh() + mesh.position.set(wall.start[0], 0, wall.start[1]) + sceneRegistry.nodes.set(wall.id, mesh) + try { + const deferred = generateExtrudedWall( + wall, + [window], + calculateLevelMiters([wall]), + 0, + 0, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + 'deferred', + ) + deferred.userData.built = true + expect(deferred.userData.wallTJunctions).toBe('deferred') + expect(countTJunctions(deferred)).toBeGreaterThan(0) + const areaBefore = area(deferred) + const groupsBefore = deferred.groups.map((g) => g.materialIndex) + + mesh.geometry = deferred + const didRepair = repairDeferredWallTJunctions(mesh) + + expect(didRepair).toBe(true) + expect(mesh.geometry.userData.wallTJunctions).toBeUndefined() + expect(mesh.geometry.userData.built).toBe(true) + expect(countTJunctions(mesh.geometry)).toBe(0) + expect(area(mesh.geometry)).toBeCloseTo(areaBefore, 6) + expect(mesh.geometry.groups.map((g) => g.materialIndex)).toEqual(groupsBefore) + expect(mesh.geometry.getAttribute('normal')).toBeDefined() + expect(mesh.geometry.getAttribute('uv')).toBeDefined() + expect(mesh.geometry.getAttribute('uv2')).toBeDefined() + + // Calling a second time is a no-op once the deferred marker is cleared. + expect(repairDeferredWallTJunctions(mesh)).toBe(false) + } finally { + mesh.geometry.dispose() + sceneRegistry.nodes.delete(wall.id) + } + }) }) diff --git a/scripts/i18n.test.ts b/scripts/i18n.test.ts index 2926aed5c9..2931f5296b 100644 --- a/scripts/i18n.test.ts +++ b/scripts/i18n.test.ts @@ -203,6 +203,75 @@ test('rich-text validation preserves attributed and self-closing tags', () => { ) }) +test('rich-text validation catches renumbered numbered tags, broken nesting, and stricter HTML/comment tags', () => { + // Valid numbered tags and valid sibling reorder pass. + expect(validateTranslation('<0>Open <1>docs', '<1>docs <0>Ouvrir', 'fr')).toEqual( + [], + ) + // Math comparison with space is not mistaken for a tag. + expect(validateTranslation('Width < 5 m', 'Largeur < 5 m', 'fr')).toEqual([]) + + // Renumbered tags fail. + expect(validateTranslation('<0>Open', '<1>Ouvrir', 'fr')).toContain( + 'rich-text tags differ from English', + ) + + // Broken nesting fails even when the sorted tag set matches English. + expect(validateTranslation('<0><1>Open', '<0><1>Ouvrir', 'fr')).toContain( + 'broken rich-text tag nesting', + ) + expect(validateTranslation('<0>Open', 'Ouvrir<0>', 'fr')).toContain( + 'broken rich-text tag nesting', + ) + expect( + validateTranslation( + 'Open', + 'Ouvrir', + 'fr', + ), + ).toContain('broken rich-text tag nesting') + + // Stricter tag check catches slash-separated HTML tags, comments, and unclosed tags. + for (const injected of [ + 'Ouvrir ', + 'Ouvrir ', + 'Ouvrir ', + 'Ouvrir { + const english = '{gender, select, male {He} female {She} other {They}}' + + expect( + validateTranslation(english, '{gender, select, male {Il} female {Elle} other {Ils}}', 'fr'), + ).toEqual([]) + expect(validateTranslation(english, '{gender, select, male {Il} other {Ils}}', 'fr')).toContain( + 'select selector "gender" is missing branch "female"', + ) + expect(validateTranslation(english, '{gender, select, male {Il} female {Elle}}', 'fr')).toContain( + 'select selector "gender" is missing branch "other"', + ) + expect( + validateTranslation( + '{gender, select, male {He} female {She}}', + '{gender, select, male {Il} female {Elle}}', + 'fr', + ), + ).toContain('select selector "gender" is missing "other"') + expect( + validateTranslation( + '{count, plural, one {# item} other {# items}}', + '{count, plural, one {# élément}}', + 'fr', + ), + ).toContain('plural selector "count" is missing "other"') +}) + test('source drift fails checking, then extraction updates English and flags translations', () => { const root = catalogProject() const sample = join(root, 'packages/editor/src/sample.tsx') diff --git a/scripts/i18n.ts b/scripts/i18n.ts index 1bcceb009b..3712a01788 100644 --- a/scripts/i18n.ts +++ b/scripts/i18n.ts @@ -193,9 +193,17 @@ function variableNames(tokens: CompiledToken[]): string[] { return [...names].sort() } -function tags(message: string): string[] { +function extractTags(message: string): string[] { const found: string[] = [] for (let start = message.indexOf('<'); start >= 0; start = message.indexOf('<', start + 1)) { + const next = message[start + 1] + if (!next) continue + // Treat any `<` followed by a letter, `!`, or `/` as a tag (catches ``, + // ``, ``, and closing tags), plus Lingui numbered tags (`<0>`, `<0/>`). + const isStrictTagStart = /[A-Za-z!/]/.test(next) + const isNumericTagStart = /\d/.test(next) + if (!(isStrictTagStart || isNumericTagStart)) continue + let quote: '"' | "'" | undefined let end = start + 1 for (; end < message.length; end += 1) { @@ -208,11 +216,44 @@ function tags(message: string): string[] { break } } - if (end >= message.length) continue + if (end >= message.length) { + if (isStrictTagStart) found.push(message.slice(start)) + continue + } const token = message.slice(start, end + 1) - if (/^<\s*\/?\s*[A-Za-z][\w-]*(?:\s|\/?>)/.test(token)) found.push(token) + if (isStrictTagStart || /^<\d+\s*\/?>$/.test(token)) { + found.push(token) + } } - return found.sort() + return found +} + +function tags(message: string): string[] { + return extractTags(message).sort() +} + +function tagNestingErrors(orderedTags: readonly string[]): string[] { + const stack: string[] = [] + for (const token of orderedTags) { + if (!token.endsWith('>')) return ['malformed rich-text tag'] + if (token.startsWith('')) continue + const closeMatch = /^<\/\s*([A-Za-z0-9][\w-]*)\s*>$/.exec(token) + if (closeMatch) { + const name = closeMatch[1]! + if (stack.length === 0 || stack[stack.length - 1] !== name) { + return ['broken rich-text tag nesting'] + } + stack.pop() + continue + } + const openMatch = /^<\s*([A-Za-z0-9][\w-]*)(?:[\s/>]|$)/.exec(token) + if (openMatch) { + stack.push(openMatch[1]!) + } + } + if (stack.length > 0) return ['broken rich-text tag nesting'] + return [] } function plurals(tokens: CompiledToken[]): Map }> { @@ -242,6 +283,26 @@ function plurals(tokens: CompiledToken[]): Map> { + const found = new Map>() + const visit = (entries: CompiledToken[]) => { + for (const token of entries) { + if (typeof token === 'string') continue + const type = token[1] + const choices = token[2] + if (type === 'select' && choices && typeof choices === 'object') { + found.set(token[0], new Set(Object.keys(choices))) + } + if (!(choices && typeof choices === 'object')) continue + for (const branch of Object.values(choices)) { + if (Array.isArray(branch)) visit(branch as CompiledToken[]) + } + } + } + visit(tokens) + return found +} + function requiredPluralCategories(locale: string, type: string): Intl.LDMLPluralRule[] { return new Intl.PluralRules(locale, { type: type === 'selectordinal' ? 'ordinal' : 'cardinal', @@ -300,9 +361,11 @@ export function validateTranslation( ) { errors.push('placeholder names differ from English') } - if (JSON.stringify(tags(source)) !== JSON.stringify(tags(translation))) { + const translatedOrderedTags = extractTags(translation) + if (JSON.stringify(tags(source)) !== JSON.stringify([...translatedOrderedTags].sort())) { errors.push('rich-text tags differ from English') } + errors.push(...tagNestingErrors(translatedOrderedTags)) const sourcePlurals = plurals(sourceTokens) const translatedPlurals = plurals(translatedTokens) @@ -312,12 +375,44 @@ export function validateTranslation( errors.push(`plural selector "${name}" is missing or changed`) continue } - for (const category of requiredPluralCategories(locale, sourcePlural.type)) { + const required = new Set([ + ...requiredPluralCategories(locale, sourcePlural.type), + 'other', + ]) + for (const category of required) { if (!translatedPlural.categories.has(category)) { errors.push(`plural selector "${name}" is missing "${category}"`) } } } + for (const [name, translatedPlural] of translatedPlurals) { + if (!sourcePlurals.has(name) && !translatedPlural.categories.has('other')) { + errors.push(`plural selector "${name}" is missing "other"`) + } + } + + const sourceSelects = selects(sourceTokens) + const translatedSelects = selects(translatedTokens) + for (const [name, sourceBranches] of sourceSelects) { + const translatedBranches = translatedSelects.get(name) + if (!translatedBranches) { + errors.push(`select selector "${name}" is missing or changed`) + continue + } + for (const branch of sourceBranches) { + if (!translatedBranches.has(branch)) { + errors.push(`select selector "${name}" is missing branch "${branch}"`) + } + } + if (!translatedBranches.has('other')) { + errors.push(`select selector "${name}" is missing "other"`) + } + } + for (const [name, translatedBranches] of translatedSelects) { + if (!sourceSelects.has(name) && !translatedBranches.has('other')) { + errors.push(`select selector "${name}" is missing "other"`) + } + } errors.push(...validateGlossary(source, translation, locale, glossary)) return errors }