From 00a424a190b17a649bf13373e1c3a9fab8528caf Mon Sep 17 00:00:00 2001 From: saadmooh Date: Tue, 3 Nov 2026 18:22:54 +0100 Subject: [PATCH 1/8] feat(wall): interactive dimension input and continuous chain drafting in 3D and 2D --- packages/core/src/events/bus.ts | 1 + packages/core/src/index.ts | 1 + packages/core/src/lib/units.test.ts | 65 +++++ packages/core/src/lib/units.ts | 82 ++++++ .../src/components/editor/floorplan-panel.tsx | 246 +++++++++++++++- .../use-floorplan-background-placement.ts | 38 ++- .../tools/shared/dimension-input.tsx | 216 ++++++++++++++ .../components/tools/wall/wall-drafting.ts | 122 ++++++++ .../src/components/ui/primitives/skeleton.tsx | 1 + packages/editor/src/hooks/use-keyboard.ts | 29 ++ packages/editor/src/index.tsx | 13 +- .../editor/src/lib/dimension-draft-store.ts | 143 +++++++++ packages/nodes/src/wall/tool.tsx | 274 ++++++++++++++++-- 13 files changed, 1191 insertions(+), 40 deletions(-) create mode 100644 packages/core/src/lib/units.test.ts create mode 100644 packages/core/src/lib/units.ts create mode 100644 packages/editor/src/components/tools/shared/dimension-input.tsx create mode 100644 packages/editor/src/lib/dimension-draft-store.ts diff --git a/packages/core/src/events/bus.ts b/packages/core/src/events/bus.ts index 2d1b5a7755..61c5293463 100644 --- a/packages/core/src/events/bus.ts +++ b/packages/core/src/events/bus.ts @@ -346,6 +346,7 @@ type CameraControlEvents = { type ToolEvents = { 'tool:cancel': undefined + 'dimension:focus': 'length' | 'angle' } type GuideEvents = { diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7f4171c257..c7f5182433 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -132,6 +132,7 @@ export { resolveAssemblyStack, } from './lib/assembly-stack' export { loadAssetUrl, saveAsset } from './lib/asset-storage' +export { parseAngle, parseDimension, pointFromLengthAngle } from './lib/units' export { BEAM_MATERIAL_LABELS, BEAM_MATERIAL_LIBRARY_REFS, diff --git a/packages/core/src/lib/units.test.ts b/packages/core/src/lib/units.test.ts new file mode 100644 index 0000000000..dc558c9ed5 --- /dev/null +++ b/packages/core/src/lib/units.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'bun:test' +import { parseAngle, parseDimension, pointFromLengthAngle } from './units' + +describe('parseDimension', () => { + it('parses bare number as meters', () => { + expect(parseDimension('3.5')).toBe(3.5) + expect(parseDimension('10')).toBe(10) + }) + + it('parses meters with "m" suffix', () => { + expect(parseDimension('3.5m')).toBe(3.5) + expect(parseDimension('5 M')).toBe(5) + }) + + it('parses centimeters with "cm" suffix', () => { + expect(parseDimension('200cm')).toBe(2) + expect(parseDimension('50 cm')).toBe(0.5) + }) + + it('parses feet with "ft" suffix', () => { + expect(parseDimension('10ft')).toBeCloseTo(3.048, 4) + }) + + it('returns null on invalid string', () => { + expect(parseDimension('')).toBeNull() + expect(parseDimension('abc')).toBeNull() + expect(parseDimension('5xyz')).toBeNull() + }) +}) + +describe('parseAngle', () => { + it('parses plain degrees', () => { + expect(parseAngle('45')).toBe(45) + expect(parseAngle('90.5')).toBe(90.5) + }) + + it('handles ° and deg suffix', () => { + expect(parseAngle('90°')).toBe(90) + expect(parseAngle('180deg')).toBe(180) + }) + + it('normalizes negative and >360 angles', () => { + expect(parseAngle('-90')).toBe(270) + expect(parseAngle('450')).toBe(90) + }) + + it('returns null on invalid string', () => { + expect(parseAngle('')).toBeNull() + expect(parseAngle('invalid')).toBeNull() + }) +}) + +describe('pointFromLengthAngle', () => { + it('calculates point east (+X) at 0 deg', () => { + const pt = pointFromLengthAngle([0, 0], 5, 0) + expect(pt[0]).toBeCloseTo(5, 4) + expect(pt[1]).toBeCloseTo(0, 4) + }) + + it('calculates point south (+Z) at 90 deg', () => { + const pt = pointFromLengthAngle([0, 0], 5, 90) + expect(pt[0]).toBeCloseTo(0, 4) + expect(pt[1]).toBeCloseTo(5, 4) + }) +}) diff --git a/packages/core/src/lib/units.ts b/packages/core/src/lib/units.ts new file mode 100644 index 0000000000..727033f4ae --- /dev/null +++ b/packages/core/src/lib/units.ts @@ -0,0 +1,82 @@ +/** + * Unit parsing for dimension input. + * + * Parses strings like "3.5m", "12ft", "120cm" into meters. + * Numbers without a suffix are treated as project units (meters). + */ + +const UNIT_FACTORS: Record = { + m: 1, + ft: 0.3048, + cm: 0.01, + in: 0.0254, + mm: 0.001, +} + +/** + * Parse a dimension string with optional unit suffix into meters. + * + * Supported suffixes: m, ft, cm, in, mm (case-insensitive). + * A bare number (e.g. "3.5") is treated as meters. + * + * @returns The value in meters, or null if parsing fails. + */ +export function parseDimension(input: string): number | null { + const trimmed = input.trim() + if (!trimmed) return null + + const match = trimmed.match(/^([+-]?\d+(?:\.\d+)?)\s*([a-zA-Z]*)$/) + if (!match || !match[1]) return null + + const value = parseFloat(match[1]) + if (Number.isNaN(value)) return null + + const unit = (match[2] ?? '').toLowerCase() + if (unit === '') return value // no suffix → meters + + const factor = UNIT_FACTORS[unit] + if (factor === undefined) return null + + return value * factor +} + +/** + * Parse an angle string into degrees. + * + * Accepts plain numbers (e.g. "45", "90.5"). + * Trailing "°" or "deg" suffixes are stripped if present. + * + * @returns The angle in degrees, or null if parsing fails. + */ +export function parseAngle(input: string): number | null { + const trimmed = input.trim() + if (!trimmed) return null + + // Strip common degree suffixes + const cleaned = trimmed.replace(/°|deg$/i, '').trim() + if (!cleaned) return null + + const value = parseFloat(cleaned) + if (Number.isNaN(value)) return null + + // Normalize to 0-360 range + return ((value % 360) + 360) % 360 +} + +/** + * Calculate the next point given a start point, length (meters), and angle (degrees). + * Angle is measured clockwise from the +X axis (east). + * + * @returns [x, z] of the calculated point. + */ +export function pointFromLengthAngle( + start: [number, number], + lengthMeters: number, + angleDeg: number, +): [number, number] { + const rad = (angleDeg * Math.PI) / 180 + return [ + start[0] + Math.cos(rad) * lengthMeters, + start[1] + Math.sin(rad) * lengthMeters, + ] +} diff --git a/packages/editor/src/components/editor/floorplan-panel.tsx b/packages/editor/src/components/editor/floorplan-panel.tsx index 9ba6079b19..f46503ab01 100644 --- a/packages/editor/src/components/editor/floorplan-panel.tsx +++ b/packages/editor/src/components/editor/floorplan-panel.tsx @@ -1,6 +1,8 @@ 'use client' import { Icon } from '@iconify/react' +import { DimensionInput } from '../tools/shared/dimension-input' +import { useDimensionDraftStore } from '../../lib/dimension-draft-store' import { type AnyNode, type AnyNodeId, @@ -7927,6 +7929,7 @@ export function FloorplanPanel({ wallRunReferenceRef.current = null setDraftEnd(null) useSegmentDraftChain.getState().clear('wall') + useDimensionDraftStore.getState().reset() // A run pulled from a wall end ends with the plan's draft: back to Select. endWallPullRun() }, [setDraftEnd]) @@ -9653,8 +9656,23 @@ export function FloorplanPanel({ // Emit `grid:move` so the registry-driven wall tool's 3D preview // tracks the cursor. The local draftEnd update below is what // drives the 2D draft polygon — both views update in parallel. - emitFloorplanGridEvent('move', snappedPoint, event) - setCursorPoint(snappedPoint) + // If locked dimensions are set, override with calculated endpoint + const dimState = useDimensionDraftStore.getState() + let finalMovePoint = snappedPoint + if (dimState.lockedLength !== null && dimState.points.length > 0) { + const lastPt = dimState.points[dimState.points.length - 1]! + const angle = dimState.lockedAngle !== null + ? dimState.lockedAngle + : (Math.atan2(planPoint[1] - lastPt[1], planPoint[0] - lastPt[0]) * 180) / Math.PI + const rad = (angle * Math.PI) / 180 + finalMovePoint = [ + lastPt[0] + Math.cos(rad) * dimState.lockedLength, + lastPt[1] + Math.sin(rad) * dimState.lockedLength, + ] + } + + emitFloorplanGridEvent('move', finalMovePoint, event) + setCursorPoint(finalMovePoint) if (!draftStart) { return @@ -9912,6 +9930,7 @@ export function FloorplanPanel({ setWallChainFirstVertex(point) setDraftEnd(point) setCursorPoint(point) + useDimensionDraftStore.getState().startDraft(point) return } @@ -9972,10 +9991,7 @@ export function FloorplanPanel({ ? (createdWall.end as WallPlanPoint) : (publishedNextStart ?? point) - if ( - !wallDraftIsRun() || - (wallChainFirstVertex && isWithinWallJoinSnapRadius(nextStart, wallChainFirstVertex)) - ) { + if (wallChainFirstVertex && isWithinWallJoinSnapRadius(nextStart, wallChainFirstVertex)) { clearWallPlacementDraft() setCursorPoint(null) return @@ -10015,6 +10031,22 @@ export function FloorplanPanel({ setDraftStart(nextStart) setDraftEnd(nextStart) setCursorPoint(nextStart) + const currentDim = useDimensionDraftStore.getState() + const alreadyHas = + currentDim.points.length > 0 && + currentDim.points[currentDim.points.length - 1]![0] === nextStart[0] && + currentDim.points[currentDim.points.length - 1]![1] === nextStart[1] + if (!alreadyHas) { + useDimensionDraftStore.setState({ + points: [...currentDim.points, nextStart], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + }) + } }, [ clearWallPlacementDraft, @@ -11878,6 +11910,15 @@ export function FloorplanPanel({ walls={walls} /> + {isWallBuildActive && ( + + )} + {selectedGuide && showGuides && ( ) : null} + + {/* Floating dimension input overlay for 2D wall drafting */} + {isWallBuildActive && draftStart && ( + { + handleWallPlacementPoint(pt) + }} + onCancel={clearWallPlacementDraft} + /> + )} ) } + +// Ghost wall segments for multi-point dimension drafting in 2D +function FloorplanDimensionGhostWalls({ + toSvgX, + toSvgY, + stroke, + fill, +}: { + toSvgX: (x: number) => number + toSvgY: (y: number) => number + stroke: string + fill: string +}) { + const points = useDimensionDraftStore((s) => s.points) + const previewPoint = useDimensionDraftStore((s) => s.previewPoint) + + const ghostWalls = useMemo(() => { + const allPoints = previewPoint ? [...points, previewPoint] : points + if (allPoints.length < 2) return [] + const segments: Array<{ start: WallPlanPoint; end: WallPlanPoint }> = [] + for (let i = 1; i < allPoints.length; i++) { + const start = allPoints[i - 1] + const end = allPoints[i] + if (start && end) { + segments.push({ start, end }) + } + } + return segments + }, [points, previewPoint]) + + if (ghostWalls.length === 0) return null + + return ( + + {ghostWalls.map((seg, i) => ( + + ))} + + ) +} + +// Floating dimension input overlay positioned near the cursor in 2D +function FloorplanDimensionInputOverlay({ + draftStart, + onCommitPoint, + onCancel, +}: { + draftStart: WallPlanPoint | null + onCommitPoint: (point: WallPlanPoint) => void + onCancel: () => void +}) { + const store = useDimensionDraftStore() + const cursorPosition = useFloorplanDraftPreview((s) => s.cursorPosition) + const cursorPoint = useFloorplanDraftPreview((s) => s.cursorPoint) + const [lastPosition, setLastPosition] = useState<{ x: number; y: number } | null>(null) + const overlayRef = useRef(null) + + useEffect(() => { + if (cursorPosition) { + setLastPosition(cursorPosition) + } + }, [cursorPosition]) + + useEffect(() => { + const onFocus = (fieldType: 'length' | 'angle') => { + useDimensionDraftStore.getState().setFieldType(fieldType) + } + emitter.on('dimension:focus', onFocus) + return () => { + emitter.off('dimension:focus', onFocus) + } + }, []) + + const handleConfirm = useCallback(() => { + const currentDim = useDimensionDraftStore.getState() + const lastPt = + currentDim.points.length > 0 + ? currentDim.points[currentDim.points.length - 1]! + : (draftStart ?? cursorPoint) + if (!lastPt) return + + const length = + currentDim.lockedLength ?? + (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + if (length === null || Number.isNaN(length) || length <= 0) return + + let angle = currentDim.lockedAngle + if (angle === null) { + const curPt = cursorPoint ?? lastPt + const dx = curPt[0] - lastPt[0] + const dz = curPt[1] - lastPt[1] + angle = dx === 0 && dz === 0 ? 0 : (Math.atan2(dz, dx) * 180) / Math.PI + } + + const rad = (angle * Math.PI) / 180 + const nextPoint: WallPlanPoint = [ + lastPt[0] + Math.cos(rad) * length, + lastPt[1] + Math.sin(rad) * length, + ] + + useDimensionDraftStore.setState({ + points: [...currentDim.points, nextPoint], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + }) + + onCommitPoint(nextPoint) + }, [cursorPoint, draftStart, onCommitPoint]) + + // Resolve screen position: prefer live cursorPosition, fall back to lastPosition, + // or project target point via SVG CTM. + const resolvePosition = (): { x: number; y: number } | null => { + if (cursorPosition) return cursorPosition + if (lastPosition) return lastPosition + const targetPoint = cursorPoint ?? draftStart + if (!targetPoint || !overlayRef.current) return null + const viewportHost = overlayRef.current.parentElement + const scene = viewportHost?.querySelector('[data-floorplan-scene]') + const svg = scene?.ownerSVGElement + const ctm = scene?.getScreenCTM() + if (!svg || !ctm || !viewportHost) return null + const pt = svg.createSVGPoint() + pt.x = targetPoint[0] + pt.y = targetPoint[1] + const screenPt = pt.matrixTransform(ctm) + const hostRect = viewportHost.getBoundingClientRect() + return { + x: screenPt.x - hostRect.left, + y: screenPt.y - hostRect.top, + } + } + + const pos = resolvePosition() + if (!pos) return null + + return ( +
+ { + store.setValues(newState.lengthValue, newState.angleValue) + if (newState.fieldType) store.setFieldType(newState.fieldType) + }} + onConfirm={handleConfirm} + onCancel={() => { + store.reset() + onCancel() + }} + /> +
+ ) +} diff --git a/packages/editor/src/components/editor/use-floorplan-background-placement.ts b/packages/editor/src/components/editor/use-floorplan-background-placement.ts index 2ca3096445..e963943b8d 100644 --- a/packages/editor/src/components/editor/use-floorplan-background-placement.ts +++ b/packages/editor/src/components/editor/use-floorplan-background-placement.ts @@ -26,6 +26,7 @@ import useEditor, { isAngleSnapActive, isMagneticSnapActive } from '../../store/ import usePlacementPreview from '../../store/use-placement-preview' import useSegmentDraftChain from '../../store/use-segment-draft-chain' import { getSegmentGridStep, type WallPlanPoint } from '../tools/wall/wall-drafting' +import { useDimensionDraftStore } from '../../lib/dimension-draft-store' const NOOP_SUBSCRIBE = () => () => {} const DEFAULT_ROOF_FOOTPRINT_CHOICE = () => 'draw' @@ -396,22 +397,41 @@ export function useFloorplanBackgroundPlacement({ } } - emitFloorplanGridEvent('click', snappedPoint, event) + // Check if locked dimensions are set — use calculated point instead of mouse + const dimState = useDimensionDraftStore.getState() + let finalPoint = snappedPoint + if (dimState.lockedLength !== null && dimState.points.length > 0) { + const lastPt = dimState.points[dimState.points.length - 1]! + const angle = dimState.lockedAngle !== null + ? dimState.lockedAngle + : (Math.atan2(planPoint[1] - lastPt[1], planPoint[0] - lastPt[0]) * 180) / Math.PI + const rad = (angle * Math.PI) / 180 + finalPoint = [ + lastPt[0] + Math.cos(rad) * dimState.lockedLength, + lastPt[1] + Math.sin(rad) * dimState.lockedLength, + ] + } + + emitFloorplanGridEvent('click', finalPoint, event) - // Double-click finishes the chain. The emit above already made the - // 3D wall tool stopDrafting (its detail >= 2 guard), so close the - // 2D draft too — otherwise it stays open against a closed 3D tool - // and the next previewed segment is silently never created. if (draftStart && event.detail >= 2) { - // …and keeps an open Polygon room (2D-only owns it; in split view the - // 3D tool already committed it on the same click). commitWallPolygonDraft() clearWallPlacementDraft() - setCursorPoint(snappedPoint) + setCursorPoint(finalPoint) return true } - handleWallPlacementPoint(snappedPoint) + useDimensionDraftStore.setState({ + points: [...dimState.points, finalPoint], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + }) + + handleWallPlacementPoint(finalPoint) return true } diff --git a/packages/editor/src/components/tools/shared/dimension-input.tsx b/packages/editor/src/components/tools/shared/dimension-input.tsx new file mode 100644 index 0000000000..80833df5e4 --- /dev/null +++ b/packages/editor/src/components/tools/shared/dimension-input.tsx @@ -0,0 +1,216 @@ +import { useCallback, useEffect, useRef } from 'react' +import { parseAngle, parseDimension } from '@pascal-app/core' + +export interface DimensionInputState { + active: boolean + fieldType: 'length' | 'angle' + lengthValue: string + angleValue: string + lockedLength: number | null + lockedAngle: number | null +} + +export const EMPTY_DIMENSION_STATE: DimensionInputState = { + active: false, + fieldType: 'length', + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, +} + +export function resolveDimensionPoint( + startPoint: [number, number], + state: DimensionInputState, +): [number, number] | null { + if (state.lockedLength === null || state.lockedAngle === null) return null + return [ + startPoint[0] + Math.cos((state.lockedAngle * Math.PI) / 180) * state.lockedLength, + startPoint[1] + Math.sin((state.lockedAngle * Math.PI) / 180) * state.lockedLength, + ] +} + +interface DimensionInputProps { + state: DimensionInputState + onChange: (state: DimensionInputState) => void + onConfirm: () => void + onCancel: () => void + position?: { x: number; y: number } +} + +export function DimensionInput({ + state, + onChange, + onConfirm, + onCancel, + position, +}: DimensionInputProps) { + const lengthRef = useRef(null) + const angleRef = useRef(null) + // Track fieldType locally so Tab can toggle it without depending on + // the parent's onChange → setValues chain (which doesn't update fieldType). + const fieldTypeRef = useRef(state.fieldType) + + useEffect(() => { + fieldTypeRef.current = state.fieldType + }, [state.fieldType]) + + // Focus the correct input when fieldType changes + useEffect(() => { + if (!state.active) return + const target = state.fieldType === 'length' ? lengthRef.current : angleRef.current + if (target) { + target.focus() + target.select() + } + }, [state.active, state.fieldType]) + + const commitValues = useCallback(() => { + const length = parseDimension(state.lengthValue) + const angle = parseAngle(state.angleValue) + if (length !== null && angle !== null) { + onChange({ + ...state, + lockedLength: length, + lockedAngle: angle, + }) + } + }, [state, onChange]) + + const focusField = useCallback((field: 'length' | 'angle') => { + const target = field === 'length' ? lengthRef.current : angleRef.current + if (target) { + target.focus() + target.select() + } + }, []) + + const handleLengthKeyDown = useCallback( + (e: React.KeyboardEvent) => { + if (e.key === 'Tab') { + e.preventDefault() + e.stopPropagation() + fieldTypeRef.current = 'angle' + onChange({ ...state, fieldType: 'angle' }) + // Focus angle input synchronously, don't wait for useEffect + requestAnimationFrame(() => focusField('angle')) + } else if (e.key === 'Enter') { + e.preventDefault() + e.stopPropagation() + commitValues() + onConfirm() + } else if (e.key === 'Escape') { + e.preventDefault() + e.stopPropagation() + onCancel() + } + }, + [state, onChange, commitValues, onConfirm, onCancel, focusField], + ) + + const handleAngleKeyDown = useCallback( + (e: React.KeyboardEvent) => { + if (e.key === 'Tab') { + e.preventDefault() + e.stopPropagation() + fieldTypeRef.current = 'length' + onChange({ ...state, fieldType: 'length' }) + requestAnimationFrame(() => focusField('length')) + } else if (e.key === 'Enter') { + e.preventDefault() + e.stopPropagation() + commitValues() + onConfirm() + } else if (e.key === 'Escape') { + e.preventDefault() + e.stopPropagation() + onCancel() + } + }, + [state, onChange, commitValues, onConfirm, onCancel, focusField], + ) + + const handleLengthChange = useCallback( + (e: React.ChangeEvent) => { + const value = e.target.value + const length = parseDimension(value) + onChange({ + ...state, + lengthValue: value, + lockedLength: length, + }) + }, + [state, onChange], + ) + + const handleAngleChange = useCallback( + (e: React.ChangeEvent) => { + const value = e.target.value + const angle = parseAngle(value) + onChange({ + ...state, + angleValue: value, + lockedAngle: angle, + }) + }, + [state, onChange], + ) + + const handleLengthBlur = useCallback(() => { + commitValues() + }, [commitValues]) + + const handleAngleBlur = useCallback(() => { + commitValues() + }, [commitValues]) + + if (!state.active) return null + + const style: React.CSSProperties = position + ? { position: 'fixed', left: position.x + 20, top: position.y - 40, zIndex: 1000 } + : { position: 'relative' } + + return ( +
e.stopPropagation()} + onPointerUp={(e) => e.stopPropagation()} + onMouseDown={(e) => e.stopPropagation()} + onMouseUp={(e) => e.stopPropagation()} + onClick={(e) => e.stopPropagation()} + > + + +
+ + +
+ ) +} diff --git a/packages/editor/src/components/tools/wall/wall-drafting.ts b/packages/editor/src/components/tools/wall/wall-drafting.ts index 6bf31ec0f0..4231b0e4ce 100644 --- a/packages/editor/src/components/tools/wall/wall-drafting.ts +++ b/packages/editor/src/components/tools/wall/wall-drafting.ts @@ -366,3 +366,125 @@ export function createWallOnCurrentLevel( return committedWall?.type === 'wall' ? committedWall : terminalWall }) } + +// --------------------------------------------------------------------------- +// Multi-point dimension-input drafting state machine +// +// Both 3D (tool.tsx) and 2D (floorplan-affordances.ts) consume this shared +// state. Neither view owns the points array or double-click logic. +// --------------------------------------------------------------------------- + +export const DOUBLE_CLICK_THRESHOLD_MS = 400 + +export interface DimensionDraftState { + /** All confirmed points in order. */ + points: WallPlanPoint[] + /** Preview point calculated from last point + locked length/angle. */ + previewPoint: WallPlanPoint | null + /** Length input value (raw string). */ + lengthValue: string + /** Angle input value (raw string). */ + angleValue: string + /** Locked length in meters (null = not yet entered). */ + lockedLength: number | null + /** Locked angle in degrees (null = not yet entered). */ + lockedAngle: number | null + /** Timestamp of last click for double-click detection. */ + lastClickTime: number + /** Active input field: 'length' | 'angle'. */ + fieldType: 'length' | 'angle' +} + +export const EMPTY_DIMENSION_DRAFT: DimensionDraftState = { + points: [], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + lastClickTime: 0, + fieldType: 'length', +} + +/** + * Place a confirmed point into the draft state. + * If lockedLength and lockedAngle are set, the new point is calculated + * from the last point; otherwise it's placed at fallback. + */ +export function placeDraftPoint( + state: DimensionDraftState, + fallback: WallPlanPoint, +): DimensionDraftState { + const newPoint: WallPlanPoint = + state.lockedLength !== null && state.lockedAngle !== null && state.points.length > 0 + ? calculateNextPoint(state.points[state.points.length - 1]!, state.lockedLength, state.lockedAngle) + : fallback + + return { + ...state, + points: [...state.points, newPoint], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + } +} + +/** + * Update the preview point based on current length/angle values. + */ +export function updateDraftPreview( + state: DimensionDraftState, +): DimensionDraftState { + if (state.points.length === 0) return state + if (state.lockedLength === null || state.lockedAngle === null) { + return { ...state, previewPoint: null } + } + + const lastPoint = state.points[state.points.length - 1]! + const previewPoint = calculateNextPoint(lastPoint, state.lockedLength, state.lockedAngle) + + return { ...state, previewPoint } +} + +/** + * Check if a click is a double-click (two clicks within threshold). + */ +export function isDoubleClick(state: DimensionDraftState, clickTime: number): boolean { + return clickTime - state.lastClickTime < DOUBLE_CLICK_THRESHOLD_MS +} + +/** + * Update the last click timestamp. + */ +export function recordClickTime( + state: DimensionDraftState, + clickTime: number, +): DimensionDraftState { + return { ...state, lastClickTime: clickTime } +} + +/** + * Build the ghost wall segments between all confirmed points. + */ +export function buildGhostWalls(points: WallPlanPoint[]): Array<{ start: WallPlanPoint; end: WallPlanPoint }> { + const segments: Array<{ start: WallPlanPoint; end: WallPlanPoint }> = [] + for (let i = 1; i < points.length; i++) { + const start = points[i - 1] + const end = points[i] + if (start && end) { + segments.push({ start, end }) + } + } + return segments +} + +function calculateNextPoint( + from: WallPlanPoint, + lengthMeters: number, + angleDeg: number, +): WallPlanPoint { + const rad = (angleDeg * Math.PI) / 180 + return [from[0] + Math.cos(rad) * lengthMeters, from[1] + Math.sin(rad) * lengthMeters] +} diff --git a/packages/editor/src/components/ui/primitives/skeleton.tsx b/packages/editor/src/components/ui/primitives/skeleton.tsx index bc05858f3b..ead68127fc 100644 --- a/packages/editor/src/components/ui/primitives/skeleton.tsx +++ b/packages/editor/src/components/ui/primitives/skeleton.tsx @@ -1,3 +1,4 @@ +import type * as React from 'react' import { cn } from '../../../lib/utils' function Skeleton({ className, ...props }: React.ComponentProps<'div'>) { diff --git a/packages/editor/src/hooks/use-keyboard.ts b/packages/editor/src/hooks/use-keyboard.ts index cffc4d182a..7e8f25bb42 100644 --- a/packages/editor/src/hooks/use-keyboard.ts +++ b/packages/editor/src/hooks/use-keyboard.ts @@ -492,6 +492,35 @@ export const useKeyboard = ({ return } + // D/A shortcuts to focus dimension input fields during wall drafting + if ( + (e.key === 'd' || e.key === 'D' || e.key === 'a' || e.key === 'A') && + !e.repeat && + !e.metaKey && + !e.ctrlKey && + !e.shiftKey && + !e.altKey && + useEditor.getState().tool === 'wall' + ) { + e.preventDefault() + emitter.emit( + 'dimension:focus', + e.key === 'd' || e.key === 'D' ? 'length' : 'angle', + ) + return + } + + // Numeric keys automatically focus length input during wall drafting + if ( + /^[0-9.]$/.test(e.key) && + !e.metaKey && + !e.ctrlKey && + !e.altKey && + useEditor.getState().tool === 'wall' + ) { + emitter.emit('dimension:focus', 'length') + } + if (e.key === 'Escape') { e.preventDefault() diff --git a/packages/editor/src/index.tsx b/packages/editor/src/index.tsx index c0a0c079db..5999793403 100644 --- a/packages/editor/src/index.tsx +++ b/packages/editor/src/index.tsx @@ -245,9 +245,18 @@ export { WALL_GRID_STEP, WALL_JOIN_SNAP_RADIUS, type WallDraftSnapKind, - type WallDraftSnapResult, + type WallDraftSnapResult, type WallPlanPoint, type WallSnapRadii, + // Multi-point dimension drafting + buildGhostWalls, + DOUBLE_CLICK_THRESHOLD_MS, + EMPTY_DIMENSION_DRAFT, + isDoubleClick, + placeDraftPoint, + recordClickTime, + updateDraftPreview, + type DimensionDraftState, } from './components/tools/wall/wall-drafting' export { lockWallPullDirection, @@ -285,6 +294,8 @@ export { BuildToolTile, } from './components/ui/build-panel/build-panel' export { useCommandPalette } from './components/ui/command-palette' +export { useDimensionDraftStore } from './lib/dimension-draft-store' +export { DimensionInput } from './components/tools/shared/dimension-input' export { ActionButton, ActionGroup } from './components/ui/controls/action-button' export { MaterialPaintPanel, diff --git a/packages/editor/src/lib/dimension-draft-store.ts b/packages/editor/src/lib/dimension-draft-store.ts new file mode 100644 index 0000000000..b0ee8acaa8 --- /dev/null +++ b/packages/editor/src/lib/dimension-draft-store.ts @@ -0,0 +1,143 @@ +/** + * Shared zustand store for dimension-input drafting state. + * + * Both the 3D wall tool and the 2D floorplan panel read/write this store. + * The 3D tool owns the DimensionInput component (via Html); the 2D + * floorplan renders ghost walls as SVG and places points using the + * locked dimensions. + */ +import { create } from 'zustand' +import type { WallPlanPoint } from '../components/tools/wall/wall-drafting' +import { + EMPTY_DIMENSION_DRAFT, + isDoubleClick, + recordClickTime, + type DimensionDraftState, + buildGhostWalls, +} from '../components/tools/wall/wall-drafting' + +interface DimensionDraftStore extends DimensionDraftState { + /** Place a point using locked dimensions or fallback. Returns new state. */ + placePoint: (fallback: WallPlanPoint) => void + /** Update length/angle values and recalculate preview. */ + setValues: (length: string, angle: string) => void + /** Set the active field type for focus management. */ + setFieldType: (fieldType: 'length' | 'angle') => void + /** Check and record double-click. Returns true if double-click detected. */ + checkDoubleClick: (clickTime: number) => boolean + /** Reset to initial state. */ + reset: () => void + /** Initialize with a starting point (Point 1). */ + startDraft: (point: WallPlanPoint) => void + /** Get ghost wall segments for rendering. */ + getGhostWalls: () => Array<{ start: WallPlanPoint; end: WallPlanPoint }> +} + +function calculateNextPoint( + from: WallPlanPoint, + lengthMeters: number, + angleDeg: number, +): WallPlanPoint { + const rad = (angleDeg * Math.PI) / 180 + return [from[0] + Math.cos(rad) * lengthMeters, from[1] + Math.sin(rad) * lengthMeters] +} + +export const useDimensionDraftStore = create((set, get) => ({ + points: [], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + lastClickTime: 0, + fieldType: 'length' as const, + + startDraft(point) { + set({ + ...EMPTY_DIMENSION_DRAFT, + points: [point], + fieldType: 'length', + }) + }, + + placePoint(fallback) { + const state = get() + const lastPoint = + state.points.length > 0 ? state.points[state.points.length - 1] : null + + let newPoint: WallPlanPoint + if (state.lockedLength !== null && state.lockedAngle !== null && lastPoint) { + newPoint = calculateNextPoint(lastPoint, state.lockedLength, state.lockedAngle) + } else { + newPoint = fallback + } + + set({ + points: [...state.points, newPoint], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + }) + }, + + setValues(lengthValue, angleValue) { + const state = get() + // Parse values + const lengthMatch = lengthValue.trim().match(/^([+-]?\d+(?:\.\d+)?)\s*([a-zA-Z]*)$/) + const lockedLength = + lengthMatch && lengthMatch[1] + ? (() => { + const v = parseFloat(lengthMatch[1]) + if (Number.isNaN(v)) return null + const u = (lengthMatch[2] ?? '').toLowerCase() + if (u === '') return v + const factors: Record = { m: 1, ft: 0.3048, cm: 0.01, in: 0.0254, mm: 0.001 } + const f = factors[u] + return f !== undefined ? v * f : null + })() + : null + + const angleClean = angleValue.replace(/°|deg$/i, '').trim() + const lockedAngle = + angleClean !== '' ? (() => { + const v = parseFloat(angleClean) + return Number.isNaN(v) ? null : ((v % 360) + 360) % 360 + })() : null + + // Calculate preview + const lastPoint = + state.points.length > 0 ? state.points[state.points.length - 1] : null + const previewPoint = + lockedLength !== null && lockedAngle !== null && lastPoint + ? calculateNextPoint(lastPoint, lockedLength, lockedAngle) + : null + + set({ lengthValue, angleValue, lockedLength, lockedAngle, previewPoint }) + }, + + setFieldType(fieldType) { + set({ fieldType }) + }, + + checkDoubleClick(clickTime) { + const state = get() + const isDbl = isDoubleClick(state, clickTime) + set({ lastClickTime: clickTime }) + return isDbl + }, + + reset() { + set(EMPTY_DIMENSION_DRAFT) + }, + + getGhostWalls() { + const state = get() + const allPoints = state.previewPoint + ? [...state.points, state.previewPoint] + : state.points + return buildGhostWalls(allPoints) + }, +})) diff --git a/packages/nodes/src/wall/tool.tsx b/packages/nodes/src/wall/tool.tsx index 456c7f95bb..b7f3066773 100644 --- a/packages/nodes/src/wall/tool.tsx +++ b/packages/nodes/src/wall/tool.tsx @@ -72,11 +72,22 @@ import { wallDraftIsRun, wallPolygonDraftWalls, wallRunDirection, + // Dimension drafting + buildGhostWalls, + DimensionInput, + type DimensionDraftState, + EMPTY_DIMENSION_DRAFT, + isDoubleClick, + placeDraftPoint, + recordClickTime, + updateDraftPreview, + useDimensionDraftStore, } from '@pascal-app/editor' import { getSceneTheme, useViewer } from '@pascal-app/viewer' +import { Html } from '@react-three/drei' import { useThree } from '@react-three/fiber' -import { useEffect, useRef, useState } from 'react' -import { DoubleSide, type Group, type Mesh, Vector3 } from 'three' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { BoxGeometry, DoubleSide, type Group, type Mesh, Vector3 } from 'three' import { DraftAngleArc, type DraftAngleLabel, @@ -538,10 +549,12 @@ const LineWallTool: React.FC = () => { const constructionPlane = useRef(null) const flatConstructionBase = useRef(false) const buildingState = useRef(0) + const lastClickTime = useRef(0) const [draftMeasurement, setDraftMeasurement] = useState(null) // Base Y of an open Polygon room's ghost sides (its construction plane). const [polygonGhostY, setPolygonGhostY] = useState(0) const [axisGuide, setAxisGuide] = useState(null) + const dimStore = useDimensionDraftStore() ?? EMPTY_DIMENSION_DRAFT const measurementColor = isDark ? '#ffffff' : '#111111' const measurementShadowColor = isDark ? '#111111' : '#ffffff' @@ -662,6 +675,7 @@ const LineWallTool: React.FC = () => { const stopDrafting = () => { discardWallPolygonDraft() buildingState.current = 0 + useDimensionDraftStore.getState().reset() constructionPlane.current = null flatConstructionBase.current = false chainFirstVertex.current = null @@ -796,7 +810,23 @@ const LineWallTool: React.FC = () => { } if (buildingState.current === 1) { - const snappedLocal = gridPosition + const dimState = useDimensionDraftStore.getState() + let snappedLocal: WallPlanPoint + if (dimState.lockedLength !== null) { + const lastPt: WallPlanPoint = dimState.points.length > 0 + ? dimState.points[dimState.points.length - 1]! + : [startingPoint.current.x, startingPoint.current.z] + const angle = dimState.lockedAngle !== null + ? dimState.lockedAngle + : (Math.atan2(localPoint[1] - lastPt[1], localPoint[0] - lastPt[0]) * 180) / Math.PI + const rad = (angle * Math.PI) / 180 + snappedLocal = [ + lastPt[0] + Math.cos(rad) * dimState.lockedLength, + lastPt[1] + Math.sin(rad) * dimState.lockedLength, + ] + } else { + snappedLocal = gridPosition + } const draftY = constructionPlane.current?.localY ?? event.localPosition[1] endingPoint.current.set(snappedLocal[0], draftY, snappedLocal[1]) const draftPreview = useFloorplanDraftPreview.getState() @@ -855,12 +885,18 @@ const LineWallTool: React.FC = () => { const onGridClick = (event: GridEvent) => { if (!wallPreviewRef.current || planOwnsInput()) return - if (buildingState.current === 1 && event.nativeEvent.detail >= 2) { + const now = event.nativeEvent?.timeStamp ?? Date.now() + if ( + buildingState.current === 1 && + (event.nativeEvent.detail >= 2 || (lastClickTime.current > 0 && now - lastClickTime.current < 400)) + ) { // A double-click finishes the chain and keeps an open Polygon room. commitWallPolygonDraft() stopDrafting() + lastClickTime.current = 0 return } + lastClickTime.current = now const { walls, snapWalls, bodyWalls } = getWallDraftSnapWalls() const pointed = buildingState.current === 0 ? pointedSurfaceFor(event) : null @@ -905,6 +941,11 @@ const LineWallTool: React.FC = () => { angleLabel: null, }) triggerSFX('sfx:structure-build-start') + useDimensionDraftStore.setState({ + ...EMPTY_DIMENSION_DRAFT, + points: [[snappedStart[0], snappedStart[1]]], + fieldType: 'length', + }) const levelId = useViewer.getState().selection.levelId if (getWallDrawVariant() === 'polygon' && levelId) { startWallPolygonDraft(levelId as AnyNodeId, snappedStart, { @@ -922,21 +963,37 @@ const LineWallTool: React.FC = () => { // positions it for the active segment. setDraftMeasurement(null) } else if (buildingState.current === 1) { - const angleLocked = isAngleSnapActive() - const snappedEnd = wallDraftIsRun() - ? snapRun(localClick, event).point - : alignPoint( - snapWallDraftPointDetailed({ - point: localClick, - walls: snapWalls, - start: angleLocked ? [startingPoint.current.x, startingPoint.current.z] : undefined, - angleSnap: angleLocked, - magnetic: isMagneticSnapActive(), - captureWallBodies: true, - bodyWalls, - }).point, - { applySnap: !angleLocked }, - ) + const currentDim = useDimensionDraftStore.getState() + let snappedEnd: WallPlanPoint + if (currentDim.lockedLength !== null) { + const lastPt: WallPlanPoint = currentDim.points.length > 0 + ? currentDim.points[currentDim.points.length - 1]! + : [startingPoint.current.x, startingPoint.current.z] + const angle = currentDim.lockedAngle !== null + ? currentDim.lockedAngle + : (Math.atan2(localClick[1] - lastPt[1], localClick[0] - lastPt[0]) * 180) / Math.PI + const rad = (angle * Math.PI) / 180 + snappedEnd = [ + lastPt[0] + Math.cos(rad) * currentDim.lockedLength, + lastPt[1] + Math.sin(rad) * currentDim.lockedLength, + ] + } else { + const angleLocked = isAngleSnapActive() + snappedEnd = wallDraftIsRun() + ? snapRun(localClick, event).point + : alignPoint( + snapWallDraftPointDetailed({ + point: localClick, + walls: snapWalls, + start: angleLocked ? [startingPoint.current.x, startingPoint.current.z] : undefined, + angleSnap: angleLocked, + magnetic: isMagneticSnapActive(), + captureWallBodies: true, + bodyWalls, + }).point, + { applySnap: !angleLocked }, + ) + } const dx = snappedEnd[0] - startingPoint.current.x const dz = snappedEnd[1] - startingPoint.current.z if (dx * dx + dz * dz < 0.01 * 0.01) return @@ -998,11 +1055,7 @@ const LineWallTool: React.FC = () => { useAlignmentGuides.getState().clear() useWallSnapIndicator.getState().clear() - // Walls draws one wall per two clicks. - if (!wallDraftIsRun()) { - stopDrafting() - return - } + // Multi-point wall drafting: continue drawing the next segment from the created wall's end point const closedToChainStart = chainFirstVertex.current && @@ -1026,6 +1079,15 @@ const LineWallTool: React.FC = () => { return } nextStart = createdWall.end + useDimensionDraftStore.setState({ + points: [...currentDim.points, nextStart], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + }) } // Publish the resolved chain start so the 2D floor-plan draft // chains its next segment from the same point (its own snap @@ -1066,6 +1128,11 @@ const LineWallTool: React.FC = () => { emitter.on('grid:move', onGridMove) emitter.on('grid:click', onGridClick) emitter.on('tool:cancel', onCancel) + + const onDimensionFocus = (fieldType: 'length' | 'angle') => { + useDimensionDraftStore.getState().setFieldType(fieldType) + } + emitter.on('dimension:focus', onDimensionFocus) const stopPullSeeding = useWallPullRun.subscribe((state) => seedPull(state.run)) seedPull(useWallPullRun.getState().run) @@ -1076,6 +1143,7 @@ const LineWallTool: React.FC = () => { emitter.off('grid:move', onGridMove) emitter.off('grid:click', onGridClick) emitter.off('tool:cancel', onCancel) + emitter.off('dimension:focus', onDimensionFocus) clearPlacementSurface() useAlignmentGuides.getState().clear() useWallSnapIndicator.getState().clear() @@ -1086,6 +1154,74 @@ const LineWallTool: React.FC = () => { } }, [unit, metricNotation]) + const handleDimChange = useCallback((newState: { lengthValue: string; angleValue: string; fieldType?: 'length' | 'angle' }) => { + useDimensionDraftStore.getState().setValues(newState.lengthValue, newState.angleValue) + if (newState.fieldType) { + useDimensionDraftStore.getState().setFieldType(newState.fieldType) + } + }, []) + + const handleDimConfirm = useCallback(() => { + const currentDim = useDimensionDraftStore.getState() + const lastPt: WallPlanPoint = + currentDim.points.length > 0 + ? currentDim.points[currentDim.points.length - 1]! + : [startingPoint.current.x, startingPoint.current.z] + + const length = + currentDim.lockedLength ?? + (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + if (length === null || Number.isNaN(length) || length <= 0) return + + let angle = currentDim.lockedAngle + if (angle === null) { + const dx = endingPoint.current.x - lastPt[0] + const dz = endingPoint.current.z - lastPt[1] + angle = dx === 0 && dz === 0 ? 0 : (Math.atan2(dz, dx) * 180) / Math.PI + } + + const rad = (angle * Math.PI) / 180 + const nextPoint: WallPlanPoint = [ + lastPt[0] + Math.cos(rad) * length, + lastPt[1] + Math.sin(rad) * length, + ] + + createWallOnCurrentLevel(lastPt, nextPoint, { + constructionHeight: previewHeightRef.current, + }) + + useDimensionDraftStore.setState({ + points: [...currentDim.points, nextPoint], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + }) + + useSegmentDraftChain.getState().setChainStart('wall', [nextPoint[0], nextPoint[1]]) + startingPoint.current.set(nextPoint[0], startingPoint.current.y, nextPoint[1]) + endingPoint.current.copy(startingPoint.current) + cursorRef.current?.position.copy(startingPoint.current) + setAxisGuide({ + origin: nextPoint, + endOrigin: null, + y: startingPoint.current.y, + angleLabel: null, + }) + setDraftMeasurement(null) + triggerSFX('sfx:structure-build-start') + }, []) + + const handleDimCancel = useCallback(() => { + useDimensionDraftStore.getState().reset() + if (buildingState.current === 1) { + markToolCancelConsumed() + emitter.emit('tool:cancel') + } + }, []) + return ( { transparent /> + {/* Ghost walls for multi-point dimension drafting */} + {dimStore.points.length > 1 && + buildGhostWalls(dimStore.points).map((seg: { start: WallPlanPoint; end: WallPlanPoint }, i: number) => ( + + ))} + {dimStore.previewPoint && dimStore.points.length > 0 && ( + + )} + + {/* Dimension input HUD */} + {dimStore.points.length > 0 && ( + + + + )} + {draftMeasurement && ( <> { } export default WallTool + +function GhostWallSegment({ + start, + end, + y, +}: { + start: WallPlanPoint + end: WallPlanPoint + y: number +}) { + const geometry = useMemo(() => { + const sx = start[0], sz = start[1] + const ex = end[0], ez = end[1] + const dx = ex - sx + const dz = ez - sz + const length = Math.sqrt(dx * dx + dz * dz) + if (length < 0.01) return null + + const angle = Math.atan2(dz, dx) + const midX = (sx + ex) / 2 + const midZ = (sz + ez) / 2 + + const geo = new BoxGeometry(length, DEFAULT_LEVEL_HEIGHT, DRAFT_WALL_THICKNESS) + const matrix = new Vector3(midX, y + DEFAULT_LEVEL_HEIGHT / 2, midZ) + return { geo, position: matrix, angle } + }, [start, end, y]) + + if (!geometry) return null + + return ( + + + + + ) +} From ef18b2cc7444d4670cc208449bc04a9192b37daf Mon Sep 17 00:00:00 2001 From: saadmooh Date: Tue, 3 Nov 2026 18:54:18 +0100 Subject: [PATCH 2/8] feat: generalize numerical dimension drafting to slabs, ceilings, and fences in 3D and 2D --- .../src/components/editor/floorplan-panel.tsx | 34 ++- .../use-floorplan-background-placement.ts | 82 +++++- packages/editor/src/index.tsx | 2 +- .../editor/src/lib/dimension-draft-store.ts | 28 ++- packages/nodes/src/ceiling/tool.tsx | 238 ++++++++++++------ packages/nodes/src/fence/tool.tsx | 216 +++++++++++++--- packages/nodes/src/slab/tool.tsx | 157 ++++++++++-- 7 files changed, 605 insertions(+), 152 deletions(-) diff --git a/packages/editor/src/components/editor/floorplan-panel.tsx b/packages/editor/src/components/editor/floorplan-panel.tsx index f46503ab01..c3a44006ec 100644 --- a/packages/editor/src/components/editor/floorplan-panel.tsx +++ b/packages/editor/src/components/editor/floorplan-panel.tsx @@ -11981,14 +11981,38 @@ export function FloorplanPanel({ ) : null} - {/* Floating dimension input overlay for 2D wall drafting */} - {isWallBuildActive && draftStart && ( + {/* Floating dimension input overlay for 2D drafting (wall, fence, slab, ceiling) */} + {((isWallBuildActive && draftStart) || + (isFenceBuildActive && fenceDraftStart) || + (isPolygonDraftBuildActive && activePolygonDraftPoints.length > 0)) && ( { - handleWallPlacementPoint(pt) + if (isWallBuildActive) { + handleWallPlacementPoint(pt) + } else if (isFenceBuildActive) { + emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) + } else if (isPolygonDraftBuildActive) { + if (isZoneBuildActive) { + handleZonePlacementPoint(pt) + } else if (isCeilingBuildActive) { + handleCeilingPlacementPoint(pt) + } else { + handleSlabPlacementPoint(pt) + } + } + }} + onCancel={() => { + if (isWallBuildActive) clearWallPlacementDraft() + else if (isFenceBuildActive) clearFencePlacementDraft() + else useDimensionDraftStore.getState().reset() }} - onCancel={clearWallPlacementDraft} /> )}
diff --git a/packages/editor/src/components/editor/use-floorplan-background-placement.ts b/packages/editor/src/components/editor/use-floorplan-background-placement.ts index e963943b8d..5877529517 100644 --- a/packages/editor/src/components/editor/use-floorplan-background-placement.ts +++ b/packages/editor/src/components/editor/use-floorplan-background-placement.ts @@ -267,46 +267,74 @@ export function useFloorplanBackgroundPlacement({ event.altKey || fenceSnapped[0] !== fenceGridBase[0] || fenceSnapped[1] !== fenceGridBase[1] - const snappedPoint = fenceLocked + const basePoint = fenceLocked ? fenceSnapped : alignFloorplanDraftPoint(fenceSnapped, { applySnap: isMagneticSnapActive() && !fenceAngleSnap, }) - emitFloorplanGridEvent('click', snappedPoint, event) - setCursorPoint(snappedPoint) + const dimState = useDimensionDraftStore.getState() + let finalPoint = basePoint + if (dimState.lockedLength !== null && fenceDraftStart) { + const lastPt = fenceDraftStart + const angle = + dimState.lockedAngle !== null + ? dimState.lockedAngle + : (Math.atan2(planPoint[1] - lastPt[1], planPoint[0] - lastPt[0]) * 180) / Math.PI + const rad = (angle * Math.PI) / 180 + finalPoint = [ + lastPt[0] + Math.cos(rad) * dimState.lockedLength, + lastPt[1] + Math.sin(rad) * dimState.lockedLength, + ] + } + + emitFloorplanGridEvent('click', finalPoint, event) + setCursorPoint(finalPoint) // Double-click finishes the chain. The emit above already made the // 3D fence tool stopDrafting (its detail >= 2 guard), so close the // 2D draft too — leaving it open desyncs the two views. if (fenceDraftStart && event.detail >= 2) { clearFencePlacementDraft() + useDimensionDraftStore.getState().reset() return true } if (!fenceDraftStart) { - setFenceDraftStart(snappedPoint) - setFenceDraftEnd(snappedPoint) + setFenceDraftStart(finalPoint) + setFenceDraftEnd(finalPoint) + useDimensionDraftStore.getState().startDraft(finalPoint, 'fence') } else if ( - getPlanPointDistance(toPoint2D(fenceDraftStart), toPoint2D(snappedPoint)) >= 0.01 + getPlanPointDistance(toPoint2D(fenceDraftStart), toPoint2D(finalPoint)) >= 0.01 ) { // Single mode commits one segment per click: the same emit above // already made the 3D fence tool stopDrafting, so close the 2D // draft too instead of chaining. if (useEditor.getState().getContinuation('fence') === 'single') { clearFencePlacementDraft() - setCursorPoint(snappedPoint) + setCursorPoint(finalPoint) + useDimensionDraftStore.getState().reset() return true } // The 3D fence tool owns creation and keeps chaining from the // committed fence's resolved end — chain the 2D draft from the // same published point so both views draft the next segment // from the same start. - const nextStart = useSegmentDraftChain.getState().fence ?? snappedPoint + const nextStart = useSegmentDraftChain.getState().fence ?? finalPoint setFenceDraftStart(nextStart) setFenceDraftEnd(nextStart) + useDimensionDraftStore.setState({ + points: [nextStart], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + activeTool: 'fence', + }) } else { - setFenceDraftEnd(snappedPoint) + setFenceDraftEnd(finalPoint) } return true } @@ -332,17 +360,47 @@ export function useFloorplanBackgroundPlacement({ align: !angleSnap, }).point + const dimState = useDimensionDraftStore.getState() + let finalPoint = snappedPoint + if (dimState.lockedLength !== null && activePolygonDraftPoints.length > 0) { + const lastPt = activePolygonDraftPoints[activePolygonDraftPoints.length - 1]! + const angle = + dimState.lockedAngle !== null + ? dimState.lockedAngle + : (Math.atan2(planPoint[1] - lastPt[1], planPoint[0] - lastPt[0]) * 180) / Math.PI + const rad = (angle * Math.PI) / 180 + finalPoint = [ + lastPt[0] + Math.cos(rad) * dimState.lockedLength, + lastPt[1] + Math.sin(rad) * dimState.lockedLength, + ] + } + // Emit the grid event so the registry-driven slab tool also // sees the click (parity with ceiling / fence / roof branches // above). Zone has no registry tool — emit-or-not is irrelevant. if (!isZoneBuildActive) { - emitFloorplanGridEvent('click', snappedPoint, event) + emitFloorplanGridEvent('click', finalPoint, event) + } + + if (activePolygonDraftPoints.length === 0) { + useDimensionDraftStore.getState().startDraft(finalPoint, 'slab') + } else { + useDimensionDraftStore.setState({ + points: [...dimState.points, finalPoint], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + activeTool: 'slab', + }) } if (isZoneBuildActive) { - handleZonePlacementPoint(snappedPoint) + handleZonePlacementPoint(finalPoint) } else { - handleSlabPlacementPoint(snappedPoint) + handleSlabPlacementPoint(finalPoint) } return true } diff --git a/packages/editor/src/index.tsx b/packages/editor/src/index.tsx index 5999793403..323bb0dcf7 100644 --- a/packages/editor/src/index.tsx +++ b/packages/editor/src/index.tsx @@ -295,7 +295,7 @@ export { } from './components/ui/build-panel/build-panel' export { useCommandPalette } from './components/ui/command-palette' export { useDimensionDraftStore } from './lib/dimension-draft-store' -export { DimensionInput } from './components/tools/shared/dimension-input' +export { DimensionInput, type DimensionInputState } from './components/tools/shared/dimension-input' export { ActionButton, ActionGroup } from './components/ui/controls/action-button' export { MaterialPaintPanel, diff --git a/packages/editor/src/lib/dimension-draft-store.ts b/packages/editor/src/lib/dimension-draft-store.ts index b0ee8acaa8..47e92c15cf 100644 --- a/packages/editor/src/lib/dimension-draft-store.ts +++ b/packages/editor/src/lib/dimension-draft-store.ts @@ -1,10 +1,8 @@ -/** +/** * Shared zustand store for dimension-input drafting state. * - * Both the 3D wall tool and the 2D floorplan panel read/write this store. - * The 3D tool owns the DimensionInput component (via Html); the 2D - * floorplan renders ghost walls as SVG and places points using the - * locked dimensions. + * Supports drafting across multiple tools: wall, fence, slab, ceiling. + * Both 3D canvas tools and the 2D floorplan panel read/write this store. */ import { create } from 'zustand' import type { WallPlanPoint } from '../components/tools/wall/wall-drafting' @@ -16,7 +14,11 @@ import { buildGhostWalls, } from '../components/tools/wall/wall-drafting' -interface DimensionDraftStore extends DimensionDraftState { +export type DraftToolKind = 'wall' | 'fence' | 'slab' | 'ceiling' + +export interface DimensionDraftStore extends DimensionDraftState { + activeTool: DraftToolKind | null + setActiveTool: (tool: DraftToolKind | null) => void /** Place a point using locked dimensions or fallback. Returns new state. */ placePoint: (fallback: WallPlanPoint) => void /** Update length/angle values and recalculate preview. */ @@ -28,12 +30,12 @@ interface DimensionDraftStore extends DimensionDraftState { /** Reset to initial state. */ reset: () => void /** Initialize with a starting point (Point 1). */ - startDraft: (point: WallPlanPoint) => void + startDraft: (point: WallPlanPoint, tool?: DraftToolKind) => void /** Get ghost wall segments for rendering. */ getGhostWalls: () => Array<{ start: WallPlanPoint; end: WallPlanPoint }> } -function calculateNextPoint( +export function calculateNextPoint( from: WallPlanPoint, lengthMeters: number, angleDeg: number, @@ -51,12 +53,18 @@ export const useDimensionDraftStore = create((set, get) => lockedAngle: null, lastClickTime: 0, fieldType: 'length' as const, + activeTool: null, + + setActiveTool(tool) { + set({ activeTool: tool }) + }, - startDraft(point) { + startDraft(point, tool = 'wall') { set({ ...EMPTY_DIMENSION_DRAFT, points: [point], fieldType: 'length', + activeTool: tool, }) }, @@ -130,7 +138,7 @@ export const useDimensionDraftStore = create((set, get) => }, reset() { - set(EMPTY_DIMENSION_DRAFT) + set({ ...EMPTY_DIMENSION_DRAFT, activeTool: null }) }, getGhostWalls() { diff --git a/packages/nodes/src/ceiling/tool.tsx b/packages/nodes/src/ceiling/tool.tsx index 999907b230..b5f2f55ea3 100644 --- a/packages/nodes/src/ceiling/tool.tsx +++ b/packages/nodes/src/ceiling/tool.tsx @@ -12,18 +12,22 @@ import { import { CursorSphere, clearCeilingSnapFeedback, + DimensionInput, + type DimensionInputState, EDITOR_LAYER, isAngleSnapActive, isGridSnapActive, markToolCancelConsumed, resolveCeilingPlanPointSnap, triggerSFX, + useDimensionDraftStore, useEditor, useFloorplanDraftPreview, visibleScene, } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' -import { useEffect, useMemo, useRef, useState } from 'react' +import { Html } from '@react-three/drei' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { BufferGeometry, DoubleSide, type Group, type Line, Shape, Vector3 } from 'three' import { mix, positionLocal } from 'three/tsl' import { CeilingNode } from './schema' @@ -34,6 +38,7 @@ import { CeilingNode } from './schema' * Multi-click polygon drawing at the ceiling height (2.52m default) * with a vertical TSL-gradient connector + ground-shadow lines so the * draft is visible against both the ceiling plane and the floor. + * Supports dynamic dimension input (length & angle) for vertex placement. */ const CEILING_HEIGHT = 2.52 @@ -43,8 +48,6 @@ function commitCeilingDrawing(levelId: LevelNode['id'], points: Array<[number, n const { createNode, nodes } = useScene.getState() const ceilingCount = Object.values(nodes).filter((n) => n.type === 'ceiling').length const name = `Ceiling ${ceilingCount + 1}` - // A placed ceiling preset seeds `toolDefaults.ceiling` (thickness, height, - // material, …) before the tool activates; the drawn polygon always wins. const defaults = useEditor.getState().toolDefaults.ceiling ?? {} const ceiling = CeilingNode.parse({ ...defaults, name, polygon: points }) createNode(ceiling, levelId) @@ -68,14 +71,21 @@ export const CeilingTool: React.FC = () => { const [snappedCursorPosition, setSnappedCursorPosition] = useState<[number, number]>([0, 0]) const [levelY, setLevelY] = useState(0) const previousSnappedPointRef = useRef<[number, number] | null>(null) + const dimStore = useDimensionDraftStore() - // Clear preset-seeded defaults on deactivation so a later manual ceiling - // draw isn't built with a stale preset's parameters. Unmount-only. + // Clear preset-seeded defaults on deactivation so a later manual ceiling draw + // isn't built with a stale preset's parameters. Unmount-only. useEffect(() => () => useEditor.getState().setToolDefaults('ceiling', null), []) - useEffect(() => () => clearCeilingSnapFeedback(), []) + useEffect( + () => () => { + clearCeilingSnapFeedback() + useDimensionDraftStore.getState().reset() + }, + [], + ) - // Publish the live vertex count so the HUD shows "Finish" only at ≥ 3 points. + // Publish the live vertex count so the HUD shows "Finish" only at >= 3 points. useEffect(() => { useEditor.getState().setDraftVertexCount(points.length) }, [points.length]) @@ -95,29 +105,52 @@ export const CeilingTool: React.FC = () => { [], ) - // The plan keeps its own copy of the corners, started empty on every view change, and finishes a - // polygon in 2D-only view without this tool. Corners kept here once the plan shows (from split - // or 3D-only view) would close a different polygon than the one the plan draws. - useEffect(() => { - let shownScene = visibleScene(useEditor.getState()) - return useEditor.subscribe((state) => { - const nextScene = visibleScene(state) - if (nextScene === shownScene) return - shownScene = nextScene - if (nextScene === '3d') return - setPoints([]) - clearCeilingSnapFeedback() - }) + const handleDimChange = useCallback((state: DimensionInputState) => { + useDimensionDraftStore.getState().setValues(state.lengthValue, state.angleValue) }, []) - const verticalGeo = useMemo( - () => - new BufferGeometry().setFromPoints([ - new Vector3(0, 0, 0), - new Vector3(0, CEILING_HEIGHT - GRID_OFFSET, 0), - ]), - [], - ) + const handleDimCancel = useCallback(() => { + useDimensionDraftStore.getState().setValues('', '') + }, []) + + const handleDimConfirm = useCallback(() => { + const currentDim = useDimensionDraftStore.getState() + const lastPoint = points.length > 0 ? points[points.length - 1] : null + if (!lastPoint) return + + const length = + currentDim.lockedLength ?? + (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + if (length === null || Number.isNaN(length) || length <= 0) return + + let angle = currentDim.lockedAngle + if (angle === null) { + const curPt = snappedCursorPosition + const dx = curPt[0] - lastPoint[0] + const dz = curPt[1] - lastPoint[1] + angle = dx === 0 && dz === 0 ? 0 : (Math.atan2(dz, dx) * 180) / Math.PI + } + + const rad = (angle * Math.PI) / 180 + const nextPoint: [number, number] = [ + lastPoint[0] + Math.cos(rad) * length, + lastPoint[1] + Math.sin(rad) * length, + ] + + useDimensionDraftStore.setState({ + points: [...points, nextPoint], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + activeTool: 'ceiling', + }) + + setPoints((prev) => [...prev, nextPoint]) + triggerSFX('sfx:structure-build-start') + }, [points, snappedCursorPosition]) const gradientOpacityNode = useMemo( () => mix(0.6, 0.0, positionLocal.y.div(CEILING_HEIGHT - GRID_OFFSET).clamp()), @@ -127,16 +160,11 @@ export const CeilingTool: React.FC = () => { useEffect(() => { if (!currentLevelId) return - // In 2D-only view the plan drafts and commits the ceiling; this tool, mounted behind the - // hidden canvas from an earlier visit, still hears the plan's grid events, so it stands aside - // (it made every ceiling twice). const planOwnsInput = () => visibleScene(useEditor.getState()) === '2d' const onGridMove = (event: GridEvent) => { if (!(cursorRef.current && gridCursorRef.current) || planOwnsInput()) return const rawPoint: [number, number] = [event.localPosition[0], event.localPosition[2]] - // Honour the active snapping mode: grid lattice + 15° angle lock are each - // gated on the mode (off / lines → free), like the slab tool. const gridStep = isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 const gridPosition: [number, number] = [...snapPointToGrid(rawPoint, gridStep)] setCursorPosition(gridPosition) @@ -148,11 +176,26 @@ export const CeilingTool: React.FC = () => { isAngleSnapActive() && lastPoint ? [...snapPointAlongAngleRay(lastPoint, rawPoint, DEFAULT_ANGLE_STEP, gridStep)] : gridPosition - const displayPoint = resolveCeilingPlanPointSnap({ + let displayPoint = resolveCeilingPlanPointSnap({ rawPoint, fallbackPoint: orthoPoint, levelId: currentLevelId, }).point + + const currentDim = useDimensionDraftStore.getState() + if (currentDim.lockedLength !== null && lastPoint) { + const angle = + currentDim.lockedAngle !== null + ? currentDim.lockedAngle + : (Math.atan2(displayPoint[1] - lastPoint[1], displayPoint[0] - lastPoint[0]) * 180) / + Math.PI + const rad = (angle * Math.PI) / 180 + displayPoint = [ + lastPoint[0] + Math.cos(rad) * currentDim.lockedLength, + lastPoint[1] + Math.sin(rad) * currentDim.lockedLength, + ] + } + useFloorplanDraftPreview.getState().setCursorPoint(displayPoint) setSnappedCursorPosition(displayPoint) if ( @@ -173,7 +216,24 @@ export const CeilingTool: React.FC = () => { const onGridClick = (_event: GridEvent) => { if (!currentLevelId || planOwnsInput()) return - const clickPoint = previousSnappedPointRef.current ?? cursorPosition + let clickPoint = previousSnappedPointRef.current ?? cursorPosition + const currentDim = useDimensionDraftStore.getState() + if (currentDim.lockedLength !== null && points.length > 0) { + const lastPoint = points[points.length - 1] + if (lastPoint) { + const angle = + currentDim.lockedAngle !== null + ? currentDim.lockedAngle + : (Math.atan2(clickPoint[1] - lastPoint[1], clickPoint[0] - lastPoint[0]) * 180) / + Math.PI + const rad = (angle * Math.PI) / 180 + clickPoint = [ + lastPoint[0] + Math.cos(rad) * currentDim.lockedLength, + lastPoint[1] + Math.sin(rad) * currentDim.lockedLength, + ] + } + } + const firstPoint = points[0] if ( points.length >= 3 && @@ -185,11 +245,26 @@ export const CeilingTool: React.FC = () => { setSelection({ selectedIds: [ceilingId] }) setPoints([]) clearCeilingSnapFeedback() + useDimensionDraftStore.getState().reset() } else { - // Every non-closing vertex is a "start" tick; the closing click above - // fires the structure-build (end) cue. + if (points.length === 0) { + useDimensionDraftStore.getState().startDraft(clickPoint, 'ceiling') + } triggerSFX('sfx:structure-build-start') - setPoints([...points, clickPoint]) + setPoints((prev) => { + const next = [...prev, clickPoint] + useDimensionDraftStore.setState({ + points: next, + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + activeTool: 'ceiling', + }) + return next + }) } } @@ -200,13 +275,20 @@ export const CeilingTool: React.FC = () => { setSelection({ selectedIds: [ceilingId] }) setPoints([]) clearCeilingSnapFeedback() + useDimensionDraftStore.getState().reset() } } const onCancel = () => { + const dimState = useDimensionDraftStore.getState() + if (dimState.lengthValue !== '' || dimState.angleValue !== '') { + useDimensionDraftStore.getState().setValues('', '') + return + } if (points.length > 0) markToolCancelConsumed() setPoints([]) clearCeilingSnapFeedback() + useDimensionDraftStore.getState().reset() } emitter.on('grid:move', onGridMove) @@ -219,6 +301,7 @@ export const CeilingTool: React.FC = () => { emitter.off('grid:click', onGridClick) emitter.off('grid:double-click', onGridDoubleClick) emitter.off('tool:cancel', onCancel) + useDimensionDraftStore.getState().reset() } }, [currentLevelId, points, cursorPosition, setSelection]) @@ -263,9 +346,7 @@ export const CeilingTool: React.FC = () => { new Vector3(firstPoint[0], gridY, firstPoint[1]), ] groundClosingLineRef.current.geometry.dispose() - groundClosingLineRef.current.geometry = new BufferGeometry().setFromPoints( - groundClosingPoints, - ) + groundClosingLineRef.current.geometry = new BufferGeometry().setFromPoints(groundClosingPoints) groundClosingLineRef.current.visible = true } else { closingLineRef.current.visible = false @@ -292,28 +373,26 @@ export const CeilingTool: React.FC = () => { return ( - + {/* @ts-ignore */} + - - - - {/* @ts-ignore */} - @@ -335,23 +414,6 @@ export const CeilingTool: React.FC = () => { /> )} - {previewShape && ( - - - - - )} {/* @ts-ignore */} { showTooltip={false} /> ))} + + {/* Floating Dimension Input for Ceiling */} + {dimStore.points.length > 0 && points.length > 0 && points[points.length - 1] && ( + + + + )} ) } diff --git a/packages/nodes/src/fence/tool.tsx b/packages/nodes/src/fence/tool.tsx index 110ab36958..397fb8399c 100644 --- a/packages/nodes/src/fence/tool.tsx +++ b/packages/nodes/src/fence/tool.tsx @@ -42,6 +42,9 @@ import { triggerSFX, useAlignmentGuides, useEditor, + DimensionInput, + type DimensionInputState, + useDimensionDraftStore, useFenceCurveDraft, useFloorplanDraftPreview, usePlacementPreview, @@ -55,8 +58,9 @@ import { getSceneTheme, useViewer, } from '@pascal-app/viewer' +import { Html } from '@react-three/drei' import { useThree } from '@react-three/fiber' -import { useEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { BufferGeometry, type Camera, @@ -645,6 +649,84 @@ const StraightFenceTool: React.FC = () => { const [axisGuide, setAxisGuide] = useState(null) const measurementColor = isDark ? '#ffffff' : '#111111' const measurementShadowColor = isDark ? '#111111' : '#ffffff' + const dimStore = useDimensionDraftStore() + const stopDraftingRef = useRef<() => void>(() => {}) + + const handleDimChange = useCallback((state: DimensionInputState) => { + useDimensionDraftStore.getState().setValues(state.lengthValue, state.angleValue) + }, []) + + const handleDimCancel = useCallback(() => { + useDimensionDraftStore.getState().setValues('', '') + }, []) + + const handleDimConfirm = useCallback(() => { + const currentDim = useDimensionDraftStore.getState() + if (buildingState.current !== 1) return + + const length = + currentDim.lockedLength ?? + (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + if (length === null || Number.isNaN(length) || length <= 0) return + + let angle = currentDim.lockedAngle + if (angle === null) { + const dx = endingPoint.current.x - startingPoint.current.x + const dz = endingPoint.current.z - startingPoint.current.z + angle = dx === 0 && dz === 0 ? 0 : (Math.atan2(dz, dx) * 180) / Math.PI + } + + const rad = (angle * Math.PI) / 180 + const snappedEnd: FencePlanPoint = [ + startingPoint.current.x + Math.cos(rad) * length, + startingPoint.current.z + Math.sin(rad) * length, + ] + + const pointedSurface = constructionSurface.current + const createdFence = createFenceOnCurrentLevel( + [startingPoint.current.x, startingPoint.current.z], + snappedEnd, + { + supportCap: pointedSurface?.elevation ?? null, + preferredSupportSlabId: pointedSurface?.supportSlabId ?? null, + constructionElevation: pointedSurface?.sourceNodeId ? pointedSurface.elevation : null, + }, + draftContext, + ) + if (!createdFence) return + + if (useEditor.getState().getContinuation('fence') === 'single') { + stopDraftingRef.current?.() + return + } + + const nextStart = createdFence.end + useSegmentDraftChain.getState().setChainStart('fence', [nextStart[0], nextStart[1]]) + startingPoint.current.set( + nextStart[0], + constructionSurface.current?.localPoint?.[1] ?? startingPoint.current.y, + nextStart[1], + ) + endingPoint.current.copy(startingPoint.current) + const draftPreview = useFloorplanDraftPreview.getState() + draftPreview.setFenceDraftEnd(null) + draftPreview.setFenceDraftStart(nextStart) + draftPreview.setFenceDraftEnd(nextStart) + cursorRef.current?.position.copy(startingPoint.current) + if (previewRef.current) previewRef.current.visible = false + setDraftMeasurement(null) + + useDimensionDraftStore.setState({ + points: [nextStart], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + activeTool: 'fence', + }) + }, [draftContext]) // Scope seeded defaults to this tool session: clear on deactivation so a // later manual fence draw isn't drawn with a stale preset's parameters. @@ -706,7 +788,9 @@ const StraightFenceTool: React.FC = () => { draftPreview.setFenceDraftEnd(null) useSegmentDraftChain.getState().clear('fence') useAlignmentGuides.getState().clear() + useDimensionDraftStore.getState().reset() } + stopDraftingRef.current = stopDrafting const onGridMove = (event: GridEvent) => { if (!(cursorRef.current && previewRef.current)) return @@ -736,18 +820,33 @@ const StraightFenceTool: React.FC = () => { // mode, not Alt (continuation is cycled through the HUD / C). if (buildingState.current === 1) { - const angleLocked = isAngleSnapActive() - const snappedLocal = alignPoint( - snapFenceDraftPoint({ - point: localPoint, - walls, - fences, - start: angleLocked ? [startingPoint.current.x, startingPoint.current.z] : undefined, - angleSnap: angleLocked, - magnetic: isMagneticSnapActive(), - }), - { applySnap: !angleLocked }, - ) + let snappedLocal: FencePlanPoint + const currentDim = useDimensionDraftStore.getState() + if (currentDim.lockedLength !== null) { + const angle = + currentDim.lockedAngle !== null + ? currentDim.lockedAngle + : (Math.atan2(localPoint[1] - startingPoint.current.z, localPoint[0] - startingPoint.current.x) * 180) / + Math.PI + const rad = (angle * Math.PI) / 180 + snappedLocal = [ + startingPoint.current.x + Math.cos(rad) * currentDim.lockedLength, + startingPoint.current.z + Math.sin(rad) * currentDim.lockedLength, + ] + } else { + const angleLocked = isAngleSnapActive() + snappedLocal = alignPoint( + snapFenceDraftPoint({ + point: localPoint, + walls, + fences, + start: angleLocked ? [startingPoint.current.x, startingPoint.current.z] : undefined, + angleSnap: angleLocked, + magnetic: isMagneticSnapActive(), + }), + { applySnap: !angleLocked }, + ) + } endingPoint.current.set(snappedLocal[0], activeY, snappedLocal[1]) const draftPreview = useFloorplanDraftPreview.getState() draftPreview.setFenceDraftStart([startingPoint.current.x, startingPoint.current.z]) @@ -848,19 +947,35 @@ const StraightFenceTool: React.FC = () => { y: event.localPosition[1], angleLabel: null, }) + useDimensionDraftStore.getState().startDraft(snappedStart, 'fence') } else { - const angleLocked = isAngleSnapActive() - const snappedEnd = alignPoint( - snapFenceDraftPoint({ - point: localClick, - walls, - fences, - start: angleLocked ? [startingPoint.current.x, startingPoint.current.z] : undefined, - angleSnap: angleLocked, - magnetic: isMagneticSnapActive(), - }), - { applySnap: !angleLocked }, - ) + const currentDim = useDimensionDraftStore.getState() + let snappedEnd: FencePlanPoint + if (currentDim.lockedLength !== null) { + const angle = + currentDim.lockedAngle !== null + ? currentDim.lockedAngle + : (Math.atan2(localClick[1] - startingPoint.current.z, localClick[0] - startingPoint.current.x) * 180) / + Math.PI + const rad = (angle * Math.PI) / 180 + snappedEnd = [ + startingPoint.current.x + Math.cos(rad) * currentDim.lockedLength, + startingPoint.current.z + Math.sin(rad) * currentDim.lockedLength, + ] + } else { + const angleLocked = isAngleSnapActive() + snappedEnd = alignPoint( + snapFenceDraftPoint({ + point: localClick, + walls, + fences, + start: angleLocked ? [startingPoint.current.x, startingPoint.current.z] : undefined, + angleSnap: angleLocked, + magnetic: isMagneticSnapActive(), + }), + { applySnap: !angleLocked }, + ) + } const dx = snappedEnd[0] - startingPoint.current.x const dz = snappedEnd[1] - startingPoint.current.z if (dx * dx + dz * dz < 0.01 * 0.01) return @@ -877,22 +992,15 @@ const StraightFenceTool: React.FC = () => { ) if (!createdFence) return - // The new segment is now a real node — make it an alignment target - // for the next segment, and drop the just-shown guide. refreshAlignmentCandidates() useAlignmentGuides.getState().clear() - // Single mode commits one segment per click: stop drafting so the next - // click starts a fresh segment instead of chaining off this endpoint. if (useEditor.getState().getContinuation('fence') === 'single') { stopDrafting() return } const nextStart = createdFence.end - // Publish the resolved chain start so the 2D floor-plan draft - // chains its next segment from the same point (its own snap - // pipeline can resolve a slightly different endpoint). useSegmentDraftChain.getState().setChainStart('fence', [nextStart[0], nextStart[1]]) startingPoint.current.set( nextStart[0], @@ -914,10 +1022,25 @@ const StraightFenceTool: React.FC = () => { y: event.localPosition[1], angleLabel: null, }) + useDimensionDraftStore.setState({ + points: [nextStart], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + activeTool: 'fence', + }) } } const onCancel = () => { + const dimState = useDimensionDraftStore.getState() + if (dimState.lengthValue !== '' || dimState.angleValue !== '') { + useDimensionDraftStore.getState().setValues('', '') + return + } if (buildingState.current === 1) { markToolCancelConsumed() stopDrafting() @@ -938,6 +1061,7 @@ const StraightFenceTool: React.FC = () => { const draftPreview = useFloorplanDraftPreview.getState() draftPreview.setFenceDraftStart(null) draftPreview.setFenceDraftEnd(null) + useDimensionDraftStore.getState().reset() } }, [unit, metricNotation, draftContext]) @@ -981,6 +1105,34 @@ const StraightFenceTool: React.FC = () => { ))} )} + + {/* Floating Dimension Input for Fence */} + {dimStore.points.length > 0 && buildingState.current === 1 && ( + + + + )} ) } diff --git a/packages/nodes/src/slab/tool.tsx b/packages/nodes/src/slab/tool.tsx index 3a21fd38ad..18c111d740 100644 --- a/packages/nodes/src/slab/tool.tsx +++ b/packages/nodes/src/slab/tool.tsx @@ -14,6 +14,8 @@ import { CursorSphere, clearPlacementSurface, clearSlabSnapFeedback, + DimensionInput, + type DimensionInputState, EDITOR_LAYER, type HorizontalConstructionPlane, isAngleSnapActive, @@ -28,13 +30,15 @@ import { resolvePointerSupportSurface, resolveSlabPlanPointSnap, triggerSFX, + useDimensionDraftStore, useEditor, useFloorplanDraftPreview, visibleScene, } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' +import { Html } from '@react-three/drei' import { useThree } from '@react-three/fiber' -import { useEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { BufferGeometry, DoubleSide, type Group, type Line, Shape, Vector3 } from 'three' import { type SlabCompletionTrigger, shouldRegistryCommitSlab } from './placement-ownership' import { SlabNode } from './schema' @@ -45,10 +49,7 @@ import { SlabNode } from './schema' * Multi-click polygon drawing: each click adds a vertex; clicking near * the first vertex (or double-clicking) closes the polygon and creates * the slab. Shift-modifier defeats the 15° angle snap during drag. - * - * Not a `DragAction` — same reasoning as `tool.tsx` for fence: this is - * a stateful sequence of grid:click events with preview state, not a - * single pointer-down → drag-up. + * Supports dynamic dimension input (length & angle) for precise vertex placement. */ const Y_OFFSET = 0.02 @@ -63,8 +64,6 @@ function commitSlabDrawing( const { createNode, nodes } = useScene.getState() const slabCount = Object.values(nodes).filter((n) => n.type === 'slab').length const name = `Slab ${slabCount + 1}` - // A placed slab preset seeds `toolDefaults.slab` (thickness, material, …) - // before the tool activates; the drawn polygon always wins. const defaults = useEditor.getState().toolDefaults.slab ?? {} const authored = SlabNode.parse({ ...defaults, name, polygon: points }) const slab = { @@ -94,6 +93,7 @@ export const SlabTool: React.FC = () => { const [levelY, setLevelY] = useState(0) const previousSnappedPointRef = useRef<[number, number] | null>(null) const constructionPlaneRef = useRef(null) + const dimStore = useDimensionDraftStore() // Clear preset-seeded defaults on deactivation so a later manual slab draw // isn't built with a stale preset's parameters. Unmount-only. @@ -103,6 +103,7 @@ export const SlabTool: React.FC = () => { () => () => { clearSlabSnapFeedback() clearPlacementSurface() + useDimensionDraftStore.getState().reset() }, [], ) @@ -127,6 +128,53 @@ export const SlabTool: React.FC = () => { [], ) + const handleDimChange = useCallback((state: DimensionInputState) => { + useDimensionDraftStore.getState().setValues(state.lengthValue, state.angleValue) + }, []) + + const handleDimCancel = useCallback(() => { + useDimensionDraftStore.getState().setValues('', '') + }, []) + + const handleDimConfirm = useCallback(() => { + const currentDim = useDimensionDraftStore.getState() + const lastPoint = points.length > 0 ? points[points.length - 1] : null + if (!lastPoint) return + + const length = + currentDim.lockedLength ?? + (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + if (length === null || Number.isNaN(length) || length <= 0) return + + let angle = currentDim.lockedAngle + if (angle === null) { + const curPt = snappedCursorPosition + const dx = curPt[0] - lastPoint[0] + const dz = curPt[1] - lastPoint[1] + angle = dx === 0 && dz === 0 ? 0 : (Math.atan2(dz, dx) * 180) / Math.PI + } + + const rad = (angle * Math.PI) / 180 + const nextPoint: [number, number] = [ + lastPoint[0] + Math.cos(rad) * length, + lastPoint[1] + Math.sin(rad) * length, + ] + + useDimensionDraftStore.setState({ + points: [...points, nextPoint], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + activeTool: 'slab', + }) + + setPoints((prev) => [...prev, nextPoint]) + triggerSFX('sfx:structure-build-start') + }, [points, snappedCursorPosition]) + useEffect(() => { if (!currentLevelId) return @@ -141,6 +189,7 @@ export const SlabTool: React.FC = () => { previousSnappedPointRef.current = null clearSlabSnapFeedback() clearPlacementSurface() + useDimensionDraftStore.getState().reset() } const onGridMove = (event: GridEvent) => { @@ -159,23 +208,34 @@ export const SlabTool: React.FC = () => { const localPosition = pointed?.localPoint ?? event.localPosition const rawPoint: [number, number] = [localPosition[0], localPosition[2]] - // Slab drafting is the 'polygon' snap context (grid / lines / off — no - // angle, no Shift bypass; Shift cycles the mode, Off is the bypass). const gridStep = isGridSnapActive() ? useEditor.getState().gridSnapStep : 0 const gridPosition: [number, number] = [...snapPointToGrid(rawPoint, gridStep)] setCursorPosition(gridPosition) const lastPoint = points[points.length - 1] - // Angle lock only when the mode asks for it (polygon never does today, but - // honour the flag so the behaviour follows the HUD). const orthoPoint: [number, number] = isAngleSnapActive() && lastPoint ? [...snapPointAlongAngleRay(lastPoint, rawPoint, DEFAULT_ANGLE_STEP, gridStep)] : gridPosition - const displayPoint = resolveSlabPlanPointSnap({ + let displayPoint = resolveSlabPlanPointSnap({ rawPoint, fallbackPoint: orthoPoint, levelId: currentLevelId, }).point + + const currentDim = useDimensionDraftStore.getState() + if (currentDim.lockedLength !== null && lastPoint) { + const angle = + currentDim.lockedAngle !== null + ? currentDim.lockedAngle + : (Math.atan2(displayPoint[1] - lastPoint[1], displayPoint[0] - lastPoint[0]) * 180) / + Math.PI + const rad = (angle * Math.PI) / 180 + displayPoint = [ + lastPoint[0] + Math.cos(rad) * currentDim.lockedLength, + lastPoint[1] + Math.sin(rad) * currentDim.lockedLength, + ] + } + const hoverPlane = plane ?? resampleTerrainConstructionPlane( @@ -199,7 +259,24 @@ export const SlabTool: React.FC = () => { const onGridClick = (event: GridEvent) => { if (!currentLevelId) return - const clickPoint = previousSnappedPointRef.current ?? cursorPosition + let clickPoint = previousSnappedPointRef.current ?? cursorPosition + const currentDim = useDimensionDraftStore.getState() + if (currentDim.lockedLength !== null && points.length > 0) { + const lastPoint = points[points.length - 1] + if (lastPoint) { + const angle = + currentDim.lockedAngle !== null + ? currentDim.lockedAngle + : (Math.atan2(clickPoint[1] - lastPoint[1], clickPoint[0] - lastPoint[0]) * 180) / + Math.PI + const rad = (angle * Math.PI) / 180 + clickPoint = [ + lastPoint[0] + Math.cos(rad) * currentDim.lockedLength, + lastPoint[1] + Math.sin(rad) * currentDim.lockedLength, + ] + } + } + const firstPoint = points[0] if ( points.length >= 3 && @@ -227,16 +304,26 @@ export const SlabTool: React.FC = () => { constructionPlaneRef.current = plane setLevelY(plane.localY) publishHorizontalConstructionPlane(event, plane) + useDimensionDraftStore.getState().startDraft(clickPoint, 'slab') } - // Every non-closing vertex is a "start" tick; the closing click above - // fires the structure-build (end) cue. triggerSFX('sfx:structure-build-start') - setPoints([...points, clickPoint]) + setPoints((prev) => { + const next = [...prev, clickPoint] + useDimensionDraftStore.setState({ + points: next, + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + activeTool: 'slab', + }) + return next + }) } } - // Finish the polygon (Enter or double-click): commit once there are enough - // vertices. Closing near the first vertex (in onGridClick) is the third way. const finishDrawing = (trigger: SlabCompletionTrigger) => { if (points.length < 3) return if (shouldRegistryCommitSlab(visibleScene(useEditor.getState()), trigger)) { @@ -255,6 +342,11 @@ export const SlabTool: React.FC = () => { } const onCancel = () => { + const dimState = useDimensionDraftStore.getState() + if (dimState.lengthValue !== '' || dimState.angleValue !== '') { + useDimensionDraftStore.getState().setValues('', '') + return + } if (points.length > 0) markToolCancelConsumed() resetDraft() } @@ -279,6 +371,7 @@ export const SlabTool: React.FC = () => { emitter.off('grid:click', onGridClick) emitter.off('grid:double-click', onGridDoubleClick) emitter.off('tool:cancel', onCancel) + useDimensionDraftStore.getState().reset() } }, [currentLevelId, points, cursorPosition, isRecessed, setSelection]) @@ -390,6 +483,34 @@ export const SlabTool: React.FC = () => { showTooltip={false} /> ))} + + {/* Floating Dimension Input for Slab */} + {dimStore.points.length > 0 && points.length > 0 && points[points.length - 1] && ( + + + + )} ) } From d7feecd071611bfa653ae48aa5866fd7a325028a Mon Sep 17 00:00:00 2001 From: saadmooh Date: Tue, 3 Nov 2026 19:28:02 +0100 Subject: [PATCH 3/8] feat: show and edit dimension indicators on opening selection --- .../editor/opening-guides-3d-layer.test.ts | 114 ++++++ .../editor/opening-guides-3d-layer.tsx | 329 +++++++++++++++++- .../src/lib/floorplan/dimension-drive.test.ts | 19 + .../src/lib/floorplan/dimension-drive.ts | 21 +- .../editor/src/store/use-opening-guides.ts | 19 +- .../nodes/src/door/contextual-dimensions.ts | 4 +- .../src/shared/opening-guides-runtime.ts | 29 ++ .../nodes/src/wall/contextual-dimensions.ts | 4 +- 8 files changed, 515 insertions(+), 24 deletions(-) create mode 100644 packages/editor/src/components/editor/opening-guides-3d-layer.test.ts diff --git a/packages/editor/src/components/editor/opening-guides-3d-layer.test.ts b/packages/editor/src/components/editor/opening-guides-3d-layer.test.ts new file mode 100644 index 0000000000..45969fd33c --- /dev/null +++ b/packages/editor/src/components/editor/opening-guides-3d-layer.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, test } from 'bun:test' +import type { AnyNode, AnyNodeId } from '@pascal-app/core' +import { computeOpeningGuidesForSelectedNode } from './opening-guides-3d-layer' + +describe('computeOpeningGuidesForSelectedNode', () => { + function createScene() { + const wall = { + object: 'node', + id: 'wall_1', + type: 'wall', + parentId: 'level_1', + visible: true, + metadata: {}, + start: [0, 0], + end: [6, 0], + height: 3, + thickness: 0.2, + children: ['win_1', 'door_1'], + } as unknown as AnyNode + + const windowNode = { + object: 'node', + id: 'win_1', + type: 'window', + parentId: 'wall_1', + wallId: 'wall_1', + visible: true, + metadata: {}, + position: [2.0, 1.5, 0], // Center at 2m along wall, 1.5m elevation + width: 1.0, + height: 1.2, + } as unknown as AnyNode + + const doorNode = { + object: 'node', + id: 'door_1', + type: 'door', + parentId: 'wall_1', + wallId: 'wall_1', + visible: true, + metadata: {}, + position: [4.5, 1.05, 0], // Center at 4.5m along wall + width: 0.9, + height: 2.1, + } as unknown as AnyNode + + const nodes: Record = { + wall_1: wall, + win_1: windowNode, + door_1: doorNode, + } + + return { wall, windowNode, doorNode, nodes } + } + + test('computes 3D dimension guides for selected window with interactive metadata', () => { + const { windowNode, nodes } = createScene() + const guides = computeOpeningGuidesForSelectedNode(windowNode, nodes) + + // Should include gap:left, gap:right, sill, and head + const dimensionGuides = guides.filter((g) => g.kind === 'dimension') + expect(dimensionGuides.length).toBeGreaterThanOrEqual(2) + + const sillGuide = dimensionGuides.find((g) => g.id === 'sill') + expect(sillGuide).toBeDefined() + expect(sillGuide?.targetNodeId).toBe('win_1') + expect(sillGuide?.wallId).toBe('wall_1') + expect(sillGuide?.role).toBe('sill') + // Bottom of window: centerY (1.5) - height / 2 (0.6) = 0.9m + expect(sillGuide?.value).toBeCloseTo(0.9, 2) + + const leftGap = dimensionGuides.find((g) => g.id === 'gap:left') + expect(leftGap).toBeDefined() + expect(leftGap?.targetNodeId).toBe('win_1') + expect(leftGap?.role).toBe('gap:left') + // Left edge: centerS (2.0) - width / 2 (0.5) = 1.5m from wall start (0) + expect(leftGap?.value).toBeCloseTo(1.5, 2) + + const rightGap = dimensionGuides.find((g) => g.id === 'gap:right') + expect(rightGap).toBeDefined() + expect(rightGap?.targetNodeId).toBe('win_1') + expect(rightGap?.role).toBe('gap:right') + // Right edge: centerS (2.0) + width / 2 (0.5) = 2.5m -> distance to door left edge (4.5 - 0.45 = 4.05) is 1.55m + expect(rightGap?.value).toBeCloseTo(1.55, 2) + }) + + test('computes 3D dimension guides for selected door (horizontal gaps only)', () => { + const { doorNode, nodes } = createScene() + const guides = computeOpeningGuidesForSelectedNode(doorNode, nodes) + + const dimensionGuides = guides.filter((g) => g.kind === 'dimension') + // Doors sit on the floor so sill/head are not included + expect(dimensionGuides.find((g) => g.id === 'sill')).toBeUndefined() + + const leftGap = dimensionGuides.find((g) => g.id === 'gap:left') + expect(leftGap).toBeDefined() + expect(leftGap?.targetNodeId).toBe('door_1') + expect(leftGap?.role).toBe('gap:left') + // Door left edge: 4.5 - 0.45 = 4.05 -> distance to window right edge (2.5) is 1.55m + expect(leftGap?.value).toBeCloseTo(1.55, 2) + + const rightGap = dimensionGuides.find((g) => g.id === 'gap:right') + expect(rightGap).toBeDefined() + expect(rightGap?.targetNodeId).toBe('door_1') + expect(rightGap?.role).toBe('gap:right') + // Door right edge: 4.5 + 0.45 = 4.95 -> distance to wall end (6.0) is 1.05m + expect(rightGap?.value).toBeCloseTo(1.05, 2) + }) + + test('returns empty guides for non-hosted or non-opening nodes', () => { + const { wall, nodes } = createScene() + expect(computeOpeningGuidesForSelectedNode(wall, nodes)).toEqual([]) + }) +}) diff --git a/packages/editor/src/components/editor/opening-guides-3d-layer.tsx b/packages/editor/src/components/editor/opening-guides-3d-layer.tsx index 1c0a502652..31f7494407 100644 --- a/packages/editor/src/components/editor/opening-guides-3d-layer.tsx +++ b/packages/editor/src/components/editor/opening-guides-3d-layer.tsx @@ -1,10 +1,27 @@ 'use client' +import { + type AnyNode, + type AnyNodeId, + computeOpeningGuides, + type DoorNode, + getOpeningFloorDatum, + getWallCurveFrameAt, + getWallCurveLength, + type OpeningSpan, + sceneRegistry, + useScene, + type WallNode, + wallSupportForNodes, + type WindowNode, +} from '@pascal-app/core' +import { resolveWallOpeningCeiling } from '@pascal-app/core/building' import { useViewer } from '@pascal-app/viewer' -import { memo, useEffect, useLayoutEffect, useMemo } from 'react' +import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { BufferGeometry, Float32BufferAttribute, Line as ThreeLine } from 'three' import { LineBasicNodeMaterial } from 'three/webgpu' import { EDITOR_LAYER } from '../../lib/constants' +import { parseDimensionInput } from '../../lib/floorplan/dimension-drive' import useOpeningGuides, { type OpeningGuide3D, type OpeningGuideVec3, @@ -16,6 +33,7 @@ const DIMENSION_COLOR = 0x81_8c_f8 // indigo — a neutral measurement const ALIGN_COLOR = 0xef_44_44 // red — a snapped alignment (matches the 2D guide accent) const DIMENSION_PILL = '#6366f1' const BADGE_PILL = '#ec4899' // pink — matches the 2D equal-spacing badge +const MIN_DIMENSION_M = 0.02 // Shared depth-test-off materials so the guides read on top of the wall and // don't rebuild GPU buffers as guides churn during a drag. @@ -40,20 +58,189 @@ const mid = (a: OpeningGuideVec3, b: OpeningGuideVec3): OpeningGuideVec3 => [ (a[2] + b[2]) / 2, ] +export function computeOpeningGuidesForSelectedNode( + node: AnyNode, + nodes: Record, +): OpeningGuide3D[] { + if (node.type !== 'door' && node.type !== 'window') return [] + const opening = node as (WindowNode | DoorNode) & { + width: number + height: number + position: readonly [number, number, number] + } + if (!opening.parentId) return [] + const wall = nodes[opening.parentId as AnyNodeId] as WallNode | undefined + if (wall?.type !== 'wall') return [] + + const wallLength = getWallCurveLength(wall) + if (wallLength < 1e-6) return [] + const wallHeight = resolveWallOpeningCeiling(wall, nodes) + + const levelId = wall.parentId as AnyNodeId | undefined + const levelYOffset = levelId ? (sceneRegistry.nodes.get(levelId)?.position.y ?? 0) : 0 + const slabElevation = wallSupportForNodes(wall, nodes).elevation + + const toWorld = (s: number, y: number): OpeningGuideVec3 => { + const { point } = getWallCurveFrameAt(wall, s / wallLength) + return [point.x, slabElevation + y + levelYOffset, point.y] + } + + // Siblings + const siblings: OpeningSpan[] = [] + const childIds = Array.isArray(wall.children) ? wall.children : [] + for (const childId of childIds) { + if (childId === opening.id) continue + const child = nodes[childId as AnyNodeId] + if (!child || (child.type !== 'door' && child.type !== 'window')) continue + const c = child as AnyNode & { + width: number + height: number + position: readonly [number, number, number] + } + siblings.push({ + id: c.id, + centerS: c.position[0], + width: c.width, + centerY: + c.position[1] + + getOpeningFloorDatum(wall, c, nodes) - + slabElevation, + height: c.height, + }) + } + + const centerS = opening.position[0] + const width = opening.width + const height = opening.height + const rawCenterY = opening.position[1] + const datumOffset = getOpeningFloorDatum(wall, opening, nodes) - slabElevation + const centerY = rawCenterY + datumOffset + + const guides = computeOpeningGuides({ + moving: { id: opening.id, centerS, width, centerY, height }, + siblings, + wall: { length: wallLength, height: wallHeight }, + includeVertical: opening.type === 'window', + }) + + const out: OpeningGuide3D[] = [] + + if (guides.sillHead) { + if (guides.sillHead.sill > MIN_DIMENSION_M) { + out.push({ + kind: 'dimension', + id: 'sill', + from: toWorld(centerS, 0), + to: toWorld(centerS, guides.sillHead.bottomY), + value: guides.sillHead.sill, + targetNodeId: opening.id, + wallId: wall.id, + role: 'sill', + centerS, + centerY: rawCenterY, + width, + height, + wallLength, + wallHeight, + }) + } + if (guides.sillHead.head > MIN_DIMENSION_M) { + out.push({ + kind: 'dimension', + id: 'head', + from: toWorld(centerS, guides.sillHead.topY), + to: toWorld(centerS, wallHeight), + value: guides.sillHead.head, + targetNodeId: opening.id, + wallId: wall.id, + role: 'head', + centerS, + centerY: rawCenterY, + width, + height, + wallLength, + wallHeight, + }) + } + } + + for (const gap of guides.gaps) { + out.push({ + kind: 'dimension', + id: `gap:${gap.side}`, + from: toWorld(gap.fromS, centerY), + to: toWorld(gap.toS, centerY), + value: gap.distance, + targetNodeId: opening.id, + wallId: wall.id, + role: `gap:${gap.side}`, + gapFromS: gap.fromS, + gapToS: gap.toS, + centerS, + centerY: rawCenterY, + width, + height, + wallLength, + wallHeight, + }) + } + + if (guides.vertical) { + const target = siblings.find((s) => s.id === guides.vertical?.targetId) + if (target) { + const lo = Math.min(centerS - width / 2, target.centerS - target.width / 2) + const hi = Math.max(centerS + width / 2, target.centerS + target.width / 2) + out.push({ + kind: 'align-line', + id: 'vertical', + from: toWorld(lo, guides.vertical.y), + to: toWorld(hi, guides.vertical.y), + }) + } + } + + if (guides.equalSpacing) { + const { gap, segments } = guides.equalSpacing + segments.forEach((seg, i) => { + out.push({ + kind: 'badge', + id: `spacing:${i}`, + at: toWorld((seg.fromS + seg.toS) / 2, centerY), + value: gap, + }) + }) + } + + return out +} + /** * Wall-plane proximity / alignment guides for the 3D editor — the spatial twin * of the floor-plan placement dimensions + equal-spacing badges. Subscribes to * `useOpeningGuides` (published by the door/window move, placement, and resize * interactions each drag tick) and draws sill/head + edge-proximity dimensions, a sill-alignment line, and - * equal-spacing badges. Coordinates are already in the move tool's render frame - * (the producer reuses the cursor's `wallLocalToWorld`, so they share the cursor's - * building-local frame), so this layer mounts beside `Alignment3DGuideLayer` and - * renders them as-is. + * equal-spacing badges. + * + * Additionally, when an opening (window or door) is selected, dimensions are displayed + * and can be clicked to type new values and drive the opening's position or sill height! */ export const OpeningGuides3DLayer = memo(function OpeningGuides3DLayer() { - const guides = useOpeningGuides((s) => s.guides) + const activeGuides = useOpeningGuides((s) => s.guides) + const selectedIds = useViewer((s) => s.selection.selectedIds) + const selectedId = selectedIds.length === 1 ? selectedIds[0] : null + const nodes = useScene((s) => s.nodes) + const selectedNode = selectedId ? nodes[selectedId] : null const unit = useViewer((s) => s.unit) const metricNotation = useViewer((s) => s.metricNotation) + + const guides = useMemo(() => { + if (activeGuides.length > 0) return activeGuides + if (selectedNode && (selectedNode.type === 'window' || selectedNode.type === 'door')) { + return computeOpeningGuidesForSelectedNode(selectedNode, nodes) + } + return [] + }, [activeGuides, selectedNode, nodes]) + if (guides.length === 0) return null return ( <> @@ -73,6 +260,95 @@ function OpeningGuide({ metricNotation: 'meters' | 'millimeters' unit: 'metric' | 'imperial' }) { + const [isEditing, setIsEditing] = useState(false) + const [inputValue, setInputValue] = useState('') + const inputRef = useRef(null) + + const isInteractive = Boolean(guide.kind === 'dimension' && guide.targetNodeId && guide.wallId && guide.role) + + const handleStartEdit = (e: React.MouseEvent) => { + e.stopPropagation() + if (!isInteractive || guide.kind !== 'dimension') return + setIsEditing(true) + setInputValue(formatMeasurement(guide.value, unit, metricNotation)) + } + + useEffect(() => { + if (isEditing && inputRef.current) { + inputRef.current.focus() + inputRef.current.select() + } + }, [isEditing]) + + const handleCommit = () => { + setIsEditing(false) + if (guide.kind !== 'dimension' || !guide.targetNodeId || !guide.role) return + const parsed = parseDimensionInput(inputValue, unit) + if (parsed === null || parsed <= 0) return + + const store = useScene.getState() + const node = store.nodes[guide.targetNodeId as AnyNodeId] + if (!node || !node.position) return + + const currentPos = node.position as readonly [number, number, number] + const width = guide.width ?? (node as { width?: number }).width ?? 1.5 + const height = guide.height ?? (node as { height?: number }).height ?? 1.5 + const wallLength = guide.wallLength ?? 100 + const wallHeight = guide.wallHeight ?? 3 + + let newCenterS = currentPos[0] + let newCenterY = currentPos[1] + + if (guide.role === 'gap:left' || guide.role === 'gap:before') { + const leftAnchor = guide.gapToS ?? 0 + newCenterS = leftAnchor + parsed + width / 2 + newCenterS = Math.max(width / 2, Math.min(wallLength - width / 2, newCenterS)) + } else if (guide.role === 'gap:right' || guide.role === 'gap:after') { + const rightAnchor = guide.gapToS ?? wallLength + newCenterS = rightAnchor - parsed - width / 2 + newCenterS = Math.max(width / 2, Math.min(wallLength - width / 2, newCenterS)) + } else if (guide.role === 'sill') { + newCenterY = parsed + height / 2 + newCenterY = Math.max(height / 2, Math.min(wallHeight - height / 2, newCenterY)) + } else if (guide.role === 'head') { + newCenterY = wallHeight - parsed - height / 2 + newCenterY = Math.max(height / 2, Math.min(wallHeight - height / 2, newCenterY)) + } + + if (newCenterS !== currentPos[0] || newCenterY !== currentPos[1]) { + const changes = [ + { + id: guide.targetNodeId as AnyNodeId, + data: { position: [newCenterS, newCenterY, currentPos[2]] }, + }, + ] + if (store.applyNodeChanges) { + store.applyNodeChanges({ update: changes }) + } else { + store.updateNode(guide.targetNodeId as AnyNodeId, { + position: [newCenterS, newCenterY, currentPos[2]], + }) + } + if (guide.wallId) { + store.dirtyNodes.add(guide.wallId as AnyNodeId) + } + store.dirtyNodes.add(guide.targetNodeId as AnyNodeId) + } + } + + const handleCancel = () => { + setIsEditing(false) + } + + const handleKeyDown = (e: React.KeyboardEvent) => { + e.stopPropagation() + if (e.key === 'Enter') { + handleCommit() + } else if (e.key === 'Escape') { + handleCancel() + } + } + if (guide.kind === 'badge') { return ( -
- {formatMeasurement(guide.value, unit, metricNotation)} -
+ {isEditing ? ( + setInputValue(e.target.value)} + onKeyDown={handleKeyDown} + onBlur={handleCommit} + onClick={(e) => e.stopPropagation()} + onPointerDown={(e) => e.stopPropagation()} + className="w-16 rounded-[3px] border border-indigo-400 bg-slate-900 px-1 py-0.5 text-center font-mono font-semibold text-[11px] text-white shadow-lg outline-none ring-2 ring-indigo-500/60" + /> + ) : ( +
e.stopPropagation() : undefined} + className={`whitespace-nowrap rounded-[3px] px-[5px] py-[2px] font-medium font-sans text-[11px] text-white select-none ${ + isInteractive + ? 'cursor-pointer transition-all hover:bg-indigo-600 hover:ring-2 hover:ring-white/40 active:scale-95 shadow-sm' + : '' + }`} + style={{ backgroundColor: DIMENSION_PILL }} + title={isInteractive ? 'Click to edit dimension' : undefined} + > + {formatMeasurement(guide.value, unit, metricNotation)} +
+ )} ) : null} @@ -123,12 +420,6 @@ function GuideSegment({ to: OpeningGuideVec3 material: LineBasicNodeMaterial }) { - // Build the THREE.Line once with a preallocated 2-point position buffer and - // mount it via (the intrinsic JSX element collides with - // React's SVG ). `material` is a module-level constant, so this memo - // runs exactly once per mounted slot; subsequent drag ticks mutate the - // existing buffer in place via the layout effect below rather than rebuilding - // the geometry, line, and GPU buffer every frame. const { line, position } = useMemo(() => { const position = new Float32BufferAttribute(new Float32Array(6), 3) const geometry = new BufferGeometry() diff --git a/packages/editor/src/lib/floorplan/dimension-drive.test.ts b/packages/editor/src/lib/floorplan/dimension-drive.test.ts index c1b8a74699..e7a7d8e691 100644 --- a/packages/editor/src/lib/floorplan/dimension-drive.test.ts +++ b/packages/editor/src/lib/floorplan/dimension-drive.test.ts @@ -238,6 +238,25 @@ describe('driving an opening along its wall', () => { expect(resolution).toMatchObject({ drivable: true, target: { kind: 'opening', sign: 1 } }) }) + test('a contextual dimension measuring from opening to wall end pushes the opening away', () => { + const nodes = sceneWithDoor() + const resolution = resolveDimensionDrive({ + nodes, + ownerNodeId: 'door_1' as AnyNodeId, + start: [1.65, 0], + end: [3, 0], + }) + expect(resolution).toMatchObject({ drivable: true, target: { kind: 'opening', sign: -1 } }) + if (!resolution.drivable) return + const plan = planDimensionDrive({ + nodes, + target: resolution.target, + currentLength: 1.35, + nextLength: 1.55, + }) + expect(plan?.updates[0]?.data).toEqual({ position: [1.0, 1.05, 0] }) + }) + test('the door stays inside its wall', () => { const nodes = sceneWithDoor() const resolution = resolveDimensionDrive({ diff --git a/packages/editor/src/lib/floorplan/dimension-drive.ts b/packages/editor/src/lib/floorplan/dimension-drive.ts index 29e6b6682d..5af58ac56b 100644 --- a/packages/editor/src/lib/floorplan/dimension-drive.ts +++ b/packages/editor/src/lib/floorplan/dimension-drive.ts @@ -206,6 +206,18 @@ function resolveWallDrive( }, } } + const startOpening = nearestOpening(openings, wall, wallDirection, query.start) + if (startOpening) { + return { + drivable: true, + target: { + kind: 'opening', + openingId: startOpening.id as AnyNodeId, + wallId: wall.id as AnyNodeId, + sign: dot(wallDirection, dimDirection) >= 0 ? -1 : 1, + }, + } + } // Otherwise the wall's own length: the endpoint the dimension runs TOWARD // moves, the one it starts from is the datum. @@ -294,13 +306,20 @@ function resolveOpeningDrive( }, } } + const origin = wall.start as DimensionPlanPoint + const startAlong = dot(subtract(query.start, origin), wallDirection) + const endAlong = dot(subtract(query.end, origin), wallDirection) + const distStart = Math.abs(startAlong - opening.position[0]) + const distEnd = Math.abs(endAlong - opening.position[0]) + const isAtStart = distStart < distEnd + const sign = ((isAtStart ? -1 : 1) * (dot(wallDirection, dimDirection) >= 0 ? 1 : -1)) as 1 | -1 return { drivable: true, target: { kind: 'opening', openingId: opening.id as AnyNodeId, wallId: wall.id as AnyNodeId, - sign: dot(wallDirection, dimDirection) >= 0 ? 1 : -1, + sign, }, } } diff --git a/packages/editor/src/store/use-opening-guides.ts b/packages/editor/src/store/use-opening-guides.ts index 6b9cf2c870..9b7831a0f1 100644 --- a/packages/editor/src/store/use-opening-guides.ts +++ b/packages/editor/src/store/use-opening-guides.ts @@ -17,7 +17,24 @@ export type OpeningGuideVec3 = [number, number, number] export type OpeningGuide3D = // A measured line + distance pill: sill (floor → bottom edge), head (top edge // → wall top), or along-wall edge-to-edge proximity. - | { kind: 'dimension'; id: string; from: OpeningGuideVec3; to: OpeningGuideVec3; value: number } + | { + kind: 'dimension' + id: string + from: OpeningGuideVec3 + to: OpeningGuideVec3 + value: number + targetNodeId?: string + wallId?: string + role?: 'gap:left' | 'gap:right' | 'gap:before' | 'gap:after' | 'sill' | 'head' | string + gapFromS?: number + gapToS?: number + centerS?: number + centerY?: number + width?: number + height?: number + wallLength?: number + wallHeight?: number + } // A dashed line connecting two openings that share a sill / centre / top. | { kind: 'align-line'; id: string; from: OpeningGuideVec3; to: OpeningGuideVec3 } // A Figma-style "=" badge marking one gap in an equal-spacing run. diff --git a/packages/nodes/src/door/contextual-dimensions.ts b/packages/nodes/src/door/contextual-dimensions.ts index 2db2cc1794..e45fef8c55 100644 --- a/packages/nodes/src/door/contextual-dimensions.ts +++ b/packages/nodes/src/door/contextual-dimensions.ts @@ -6,7 +6,7 @@ export function buildDoorContextualDimensions( ctx: GeometryContext, ): FloorplanGeometry | null { return buildWallHostedOpeningContextualDimensions(node, ctx, { - showClearancesWhileMoving: false, - useExteriorNormal: false, + showClearancesWhileMoving: true, + useExteriorNormal: true, }) } diff --git a/packages/nodes/src/shared/opening-guides-runtime.ts b/packages/nodes/src/shared/opening-guides-runtime.ts index 586aabc54b..a56955a1db 100644 --- a/packages/nodes/src/shared/opening-guides-runtime.ts +++ b/packages/nodes/src/shared/opening-guides-runtime.ts @@ -137,6 +137,15 @@ export function publishOpeningGuides3D(args: { from: toWorld(centerS, 0), to: toWorld(centerS, guides.sillHead.bottomY), value: guides.sillHead.sill, + targetNodeId: args.movingId, + wallId: wall.id, + role: 'sill', + centerS, + centerY: args.centerY, + width, + height: args.height, + wallLength, + wallHeight, }) } if (guides.sillHead.head > MIN_DIMENSION_M) { @@ -146,6 +155,15 @@ export function publishOpeningGuides3D(args: { from: toWorld(centerS, guides.sillHead.topY), to: toWorld(centerS, wallHeight), value: guides.sillHead.head, + targetNodeId: args.movingId, + wallId: wall.id, + role: 'head', + centerS, + centerY: args.centerY, + width, + height: args.height, + wallLength, + wallHeight, }) } } @@ -157,6 +175,17 @@ export function publishOpeningGuides3D(args: { from: toWorld(gap.fromS, centerY), to: toWorld(gap.toS, centerY), value: gap.distance, + targetNodeId: args.movingId, + wallId: wall.id, + role: `gap:${gap.side}`, + gapFromS: gap.fromS, + gapToS: gap.toS, + centerS, + centerY: args.centerY, + width, + height: args.height, + wallLength, + wallHeight, }) } diff --git a/packages/nodes/src/wall/contextual-dimensions.ts b/packages/nodes/src/wall/contextual-dimensions.ts index 3d253a2671..8adf3dd70b 100644 --- a/packages/nodes/src/wall/contextual-dimensions.ts +++ b/packages/nodes/src/wall/contextual-dimensions.ts @@ -340,7 +340,9 @@ export function buildWallHostedOpeningContextualDimensions( } const offsetNormal = contextualWallDimensionNormal(wall, [-dirY, dirX], ctx.siblings) - if (!(options.showClearancesWhileMoving && ctx.viewState?.moving)) { + const showClearances = + options.showClearancesWhileMoving && (ctx.viewState?.moving || ctx.viewState?.selected) + if (!showClearances) { return { kind: 'dimension', start: openingStart, From 29f509a3d92b297c32c190167d8dc4f4b61bdfba Mon Sep 17 00:00:00 2001 From: saadmooh Date: Tue, 3 Nov 2026 20:40:10 +0100 Subject: [PATCH 4/8] fix(drafting): resolve Bugbot review issues on continuous chaining and dimension input --- .../src/components/editor/floorplan-panel.tsx | 15 ++++-- .../src/components/editor/localized-html.tsx | 3 ++ .../use-floorplan-background-placement.ts | 10 ---- .../editor/wall-snap-beacon-layer.tsx | 2 +- packages/editor/src/hooks/use-keyboard.ts | 28 +++++++---- packages/nodes/src/ceiling/tool.tsx | 44 ++++++++++++++---- packages/nodes/src/fence/tool.tsx | 7 +-- packages/nodes/src/slab/tool.tsx | 7 +-- packages/nodes/src/wall/tool.tsx | 46 +++++-------------- 9 files changed, 89 insertions(+), 73 deletions(-) diff --git a/packages/editor/src/components/editor/floorplan-panel.tsx b/packages/editor/src/components/editor/floorplan-panel.tsx index c3a44006ec..2a47aa07a8 100644 --- a/packages/editor/src/components/editor/floorplan-panel.tsx +++ b/packages/editor/src/components/editor/floorplan-panel.tsx @@ -47,6 +47,7 @@ import { SlabNode as SlabNodeSchema, type StairNode, StairNode as StairNodeSchema, + parseDimension, sampleWallCenterline, sceneRegistry, snapPointAlongAngleRay, @@ -9681,13 +9682,13 @@ export function FloorplanPanel({ setDraftEnd((previousEnd) => { if ( !previousEnd || - previousEnd[0] !== snappedPoint[0] || - previousEnd[1] !== snappedPoint[1] + previousEnd[0] !== finalMovePoint[0] || + previousEnd[1] !== finalMovePoint[1] ) { sfxEmitter.emit('sfx:grid-snap') } - return snappedPoint + return finalMovePoint }) }, [ @@ -11995,6 +11996,7 @@ export function FloorplanPanel({ } onCommitPoint={(pt) => { if (isWallBuildActive) { + emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) handleWallPlacementPoint(pt) } else if (isFenceBuildActive) { emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) @@ -12011,7 +12013,10 @@ export function FloorplanPanel({ onCancel={() => { if (isWallBuildActive) clearWallPlacementDraft() else if (isFenceBuildActive) clearFencePlacementDraft() - else useDimensionDraftStore.getState().reset() + else if (isCeilingBuildActive) clearCeilingPlacementDraft() + else if (isZoneBuildActive) clearZonePlacementDraft() + else clearSlabPlacementDraft() + useDimensionDraftStore.getState().reset() }} /> )} @@ -12112,7 +12117,7 @@ function FloorplanDimensionInputOverlay({ const length = currentDim.lockedLength ?? - (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + (currentDim.lengthValue ? parseDimension(currentDim.lengthValue) : null) if (length === null || Number.isNaN(length) || length <= 0) return let angle = currentDim.lockedAngle diff --git a/packages/editor/src/components/editor/localized-html.tsx b/packages/editor/src/components/editor/localized-html.tsx index 6f62a68c8f..8d3b5d8114 100644 --- a/packages/editor/src/components/editor/localized-html.tsx +++ b/packages/editor/src/components/editor/localized-html.tsx @@ -12,6 +12,9 @@ import { type ComponentProps, forwardRef } from 'react' */ export const Html = forwardRef, 'ref'>>( function Html({ children, ...props }, ref) { + if (typeof document === 'undefined' || typeof document.createElement !== 'function') { + return null + } const i18n = usePascalI18n() return ( diff --git a/packages/editor/src/components/editor/use-floorplan-background-placement.ts b/packages/editor/src/components/editor/use-floorplan-background-placement.ts index 5877529517..1089d60388 100644 --- a/packages/editor/src/components/editor/use-floorplan-background-placement.ts +++ b/packages/editor/src/components/editor/use-floorplan-background-placement.ts @@ -479,16 +479,6 @@ export function useFloorplanBackgroundPlacement({ return true } - useDimensionDraftStore.setState({ - points: [...dimState.points, finalPoint], - previewPoint: null, - lengthValue: '', - angleValue: '', - lockedLength: null, - lockedAngle: null, - fieldType: 'length', - }) - handleWallPlacementPoint(finalPoint) return true } diff --git a/packages/editor/src/components/editor/wall-snap-beacon-layer.tsx b/packages/editor/src/components/editor/wall-snap-beacon-layer.tsx index 25ee75f111..7b4373bff5 100644 --- a/packages/editor/src/components/editor/wall-snap-beacon-layer.tsx +++ b/packages/editor/src/components/editor/wall-snap-beacon-layer.tsx @@ -16,7 +16,7 @@ import { } from '@pascal-app/core' import { useWallSnapIndicator, type WallSnapKind } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' -import { Html } from '@react-three/drei' +import { Html } from './localized-html' import { useFrame } from '@react-three/fiber' import { memo, useMemo, useRef } from 'react' import { BoxGeometry, CircleGeometry, CylinderGeometry, type Group } from 'three' diff --git a/packages/editor/src/hooks/use-keyboard.ts b/packages/editor/src/hooks/use-keyboard.ts index 7e8f25bb42..f9512ac49a 100644 --- a/packages/editor/src/hooks/use-keyboard.ts +++ b/packages/editor/src/hooks/use-keyboard.ts @@ -38,6 +38,7 @@ import { cycleSelectionAtPointer, trackSelectionCyclePointer } from '../lib/sele import { sfxEmitter } from '../lib/sfx-bus' import { openSidebarPanel } from '../lib/sidebar-panel' import { activeSiteNode, clampBrushRadius } from '../lib/terrain-sculpt' +import { useDimensionDraftStore } from '../lib/dimension-draft-store' import { armToolShortcut, toolShortcutForKey } from '../lib/tool-shortcuts' import { isTypingTarget } from '../lib/typing-target' import { leaveUnitFocus } from '../lib/units' @@ -492,7 +493,14 @@ export const useKeyboard = ({ return } - // D/A shortcuts to focus dimension input fields during wall drafting + // Dimension input shortcuts during active drafting (wall, fence, slab, ceiling) + const dimStoreState = useDimensionDraftStore.getState() + const currentTool = useEditor.getState().tool + const isDraftingWithDim = + dimStoreState.points.length > 0 && + (currentTool === 'wall' || currentTool === 'fence' || currentTool === 'slab' || currentTool === 'ceiling') + + // D/A shortcuts to focus dimension input fields during drafting (only when active so WASD panning is not stolen) if ( (e.key === 'd' || e.key === 'D' || e.key === 'a' || e.key === 'A') && !e.repeat && @@ -500,25 +508,29 @@ export const useKeyboard = ({ !e.ctrlKey && !e.shiftKey && !e.altKey && - useEditor.getState().tool === 'wall' + isDraftingWithDim ) { e.preventDefault() - emitter.emit( - 'dimension:focus', - e.key === 'd' || e.key === 'D' ? 'length' : 'angle', - ) + const targetField = e.key === 'd' || e.key === 'D' ? 'length' : 'angle' + dimStoreState.setFieldType(targetField) + emitter.emit('dimension:focus', targetField) return } - // Numeric keys automatically focus length input during wall drafting + // Numeric keys automatically focus length input during drafting and seed the character if ( /^[0-9.]$/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey && - useEditor.getState().tool === 'wall' + isDraftingWithDim ) { + e.preventDefault() + const nextLength = (dimStoreState.lengthValue ?? '') + e.key + dimStoreState.setValues(nextLength, dimStoreState.angleValue) + dimStoreState.setFieldType('length') emitter.emit('dimension:focus', 'length') + return } if (e.key === 'Escape') { diff --git a/packages/nodes/src/ceiling/tool.tsx b/packages/nodes/src/ceiling/tool.tsx index b5f2f55ea3..f4a75feeec 100644 --- a/packages/nodes/src/ceiling/tool.tsx +++ b/packages/nodes/src/ceiling/tool.tsx @@ -3,6 +3,7 @@ import { DEFAULT_ANGLE_STEP, emitter, + parseDimension, type GridEvent, type LevelNode, snapPointAlongAngleRay, @@ -13,6 +14,7 @@ import { CursorSphere, clearCeilingSnapFeedback, DimensionInput, + LocalizedHtml as Html, type DimensionInputState, EDITOR_LAYER, isAngleSnapActive, @@ -26,7 +28,6 @@ import { visibleScene, } from '@pascal-app/editor' import { useViewer } from '@pascal-app/viewer' -import { Html } from '@react-three/drei' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { BufferGeometry, DoubleSide, type Group, type Line, Shape, Vector3 } from 'three' import { mix, positionLocal } from 'three/tsl' @@ -105,6 +106,36 @@ export const CeilingTool: React.FC = () => { [], ) + // The plan keeps its own copy of the corners, started empty on every view change, and finishes a + // polygon in 2D-only view without this tool. Corners kept here once the plan shows (from split + // or 3D-only view) would close a different polygon than the one the plan draws. + useEffect(() => { + let shownScene = visibleScene(useEditor.getState()) + return useEditor.subscribe((state) => { + const nextScene = visibleScene(state) + if (nextScene === shownScene) return + shownScene = nextScene + if (nextScene === '3d') return + setPoints([]) + clearCeilingSnapFeedback() + }) + }, []) + + const verticalGeo = useMemo( + () => + new BufferGeometry().setFromPoints([ + new Vector3(0, 0, 0), + new Vector3(0, CEILING_HEIGHT - GRID_OFFSET, 0), + ]), + [], + ) + + useEffect(() => { + return () => { + verticalGeo.dispose() + } + }, [verticalGeo]) + const handleDimChange = useCallback((state: DimensionInputState) => { useDimensionDraftStore.getState().setValues(state.lengthValue, state.angleValue) }, []) @@ -120,7 +151,7 @@ export const CeilingTool: React.FC = () => { const length = currentDim.lockedLength ?? - (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + (currentDim.lengthValue ? parseDimension(currentDim.lengthValue) : null) if (length === null || Number.isNaN(length) || length <= 0) return let angle = currentDim.lockedAngle @@ -377,12 +408,7 @@ export const CeilingTool: React.FC = () => { {/* @ts-ignore */} { ))} {/* Floating Dimension Input for Ceiling */} - {dimStore.points.length > 0 && points.length > 0 && points[points.length - 1] && ( + {typeof document !== 'undefined' && typeof document.createElement === 'function' && dimStore.points.length > 0 && points.length > 0 && points[points.length - 1] && ( { const length = currentDim.lockedLength ?? - (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + (currentDim.lengthValue ? parseDimension(currentDim.lengthValue) : null) if (length === null || Number.isNaN(length) || length <= 0) return let angle = currentDim.lockedAngle @@ -1107,7 +1108,7 @@ const StraightFenceTool: React.FC = () => { )} {/* Floating Dimension Input for Fence */} - {dimStore.points.length > 0 && buildingState.current === 1 && ( + {typeof document !== 'undefined' && typeof document.createElement === 'function' && dimStore.points.length > 0 && buildingState.current === 1 && ( { const length = currentDim.lockedLength ?? - (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + (currentDim.lengthValue ? parseDimension(currentDim.lengthValue) : null) if (length === null || Number.isNaN(length) || length <= 0) return let angle = currentDim.lockedAngle @@ -485,7 +486,7 @@ export const SlabTool: React.FC = () => { ))} {/* Floating Dimension Input for Slab */} - {dimStore.points.length > 0 && points.length > 0 && points[points.length - 1] && ( + {typeof document !== 'undefined' && typeof document.createElement === 'function' && dimStore.points.length > 0 && points.length > 0 && points[points.length - 1] && ( { const onGridClick = (event: GridEvent) => { if (!wallPreviewRef.current || planOwnsInput()) return - const now = event.nativeEvent?.timeStamp ?? Date.now() if ( buildingState.current === 1 && - (event.nativeEvent.detail >= 2 || (lastClickTime.current > 0 && now - lastClickTime.current < 400)) + event.nativeEvent?.detail >= 2 ) { // A double-click finishes the chain and keeps an open Polygon room. commitWallPolygonDraft() stopDrafting() - lastClickTime.current = 0 return } - lastClickTime.current = now const { walls, snapWalls, bodyWalls } = getWallDraftSnapWalls() const pointed = buildingState.current === 0 ? pointedSurfaceFor(event) : null @@ -994,6 +991,7 @@ const LineWallTool: React.FC = () => { { applySnap: !angleLocked }, ) } + const commitWallPlacementPoint = (snappedEnd: WallPlanPoint, event?: GridEvent) => { const dx = snappedEnd[0] - startingPoint.current.x const dz = snappedEnd[1] - startingPoint.current.z if (dx * dx + dz * dz < 0.01 * 0.01) return @@ -1021,7 +1019,7 @@ const LineWallTool: React.FC = () => { } else { const draftPlane = constructionPlane.current const commitPointed = - draftPlane?.supportSlabId === GROUND_SUPPORT_ID ? null : pointedSurfaceFor(event) + draftPlane?.supportSlabId === GROUND_SUPPORT_ID ? null : (event ? pointedSurfaceFor(event) : null) // Both start and end are building-local ✓ // The Walls variant's Invisible draws room separators, not walls. const createdWall = @@ -1079,6 +1077,7 @@ const LineWallTool: React.FC = () => { return } nextStart = createdWall.end + const currentDim = useDimensionDraftStore.getState() useDimensionDraftStore.setState({ points: [...currentDim.points, nextStart], previewPoint: null, @@ -1093,7 +1092,7 @@ const LineWallTool: React.FC = () => { // chains its next segment from the same point (its own snap // pipeline can resolve a slightly different endpoint). useSegmentDraftChain.getState().setChainStart('wall', [nextStart[0], nextStart[1]]) - const draftY = constructionPlane.current?.localY ?? event.localPosition[1] + const draftY = constructionPlane.current?.localY ?? event?.localPosition[1] ?? startingPoint.current.y startingPoint.current.set(nextStart[0], draftY, nextStart[1]) endingPoint.current.copy(startingPoint.current) const draftPreview = useFloorplanDraftPreview.getState() @@ -1115,6 +1114,9 @@ const LineWallTool: React.FC = () => { wallPreviewRef.current.visible = false } setDraftMeasurement(null) + } + commitWallPointRef.current = commitWallPlacementPoint + commitWallPlacementPoint(snappedEnd, event) } } @@ -1170,7 +1172,7 @@ const LineWallTool: React.FC = () => { const length = currentDim.lockedLength ?? - (currentDim.lengthValue ? parseFloat(currentDim.lengthValue) : null) + (currentDim.lengthValue ? parseDimension(currentDim.lengthValue) : null) if (length === null || Number.isNaN(length) || length <= 0) return let angle = currentDim.lockedAngle @@ -1186,31 +1188,7 @@ const LineWallTool: React.FC = () => { lastPt[1] + Math.sin(rad) * length, ] - createWallOnCurrentLevel(lastPt, nextPoint, { - constructionHeight: previewHeightRef.current, - }) - - useDimensionDraftStore.setState({ - points: [...currentDim.points, nextPoint], - previewPoint: null, - lengthValue: '', - angleValue: '', - lockedLength: null, - lockedAngle: null, - fieldType: 'length', - }) - - useSegmentDraftChain.getState().setChainStart('wall', [nextPoint[0], nextPoint[1]]) - startingPoint.current.set(nextPoint[0], startingPoint.current.y, nextPoint[1]) - endingPoint.current.copy(startingPoint.current) - cursorRef.current?.position.copy(startingPoint.current) - setAxisGuide({ - origin: nextPoint, - endOrigin: null, - y: startingPoint.current.y, - angleLabel: null, - }) - setDraftMeasurement(null) + commitWallPointRef.current(nextPoint) triggerSFX('sfx:structure-build-start') }, []) @@ -1256,7 +1234,7 @@ const LineWallTool: React.FC = () => { )} {/* Dimension input HUD */} - {dimStore.points.length > 0 && ( + {typeof document !== 'undefined' && typeof document.createElement === 'function' && dimStore.points.length > 0 && ( Date: Tue, 3 Nov 2026 22:17:23 +0100 Subject: [PATCH 5/8] fix(editor): defer drei Html unmount and avoid unmounting room label anchors in React 19 --- .../src/components/editor/localized-html.tsx | 33 +++++++++++++++++++ .../src/components/editor/room-labels.tsx | 4 +-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/packages/editor/src/components/editor/localized-html.tsx b/packages/editor/src/components/editor/localized-html.tsx index 8d3b5d8114..56271f2812 100644 --- a/packages/editor/src/components/editor/localized-html.tsx +++ b/packages/editor/src/components/editor/localized-html.tsx @@ -2,8 +2,41 @@ import { PascalI18nProvider, usePascalI18n } from '@pascal-app/core' import { Html as DreiHtml } from '@react-three/drei' +import * as ReactDOMClient from 'react-dom/client' import { type ComponentProps, forwardRef } from 'react' +// React 19 / Drei Html compatibility: +// @react-three/drei's Html unmounts its root synchronously inside useLayoutEffect cleanup. +// In React 19, calling root.unmount() synchronously while React is rendering triggers: +// "Attempted to synchronously unmount a root while React was already rendering". +// Deferring root.unmount() via setTimeout(() => ..., 0) completely avoids this race condition. +if (typeof window !== 'undefined') { + try { + const rdc = ReactDOMClient as any + const originalCreateRoot = rdc.createRoot + if (typeof originalCreateRoot === 'function' && !originalCreateRoot.__react19Patched) { + const patchedCreateRoot = function (...args: any[]) { + const root = originalCreateRoot.apply(this, args) + const originalUnmount = root.unmount.bind(root) + root.unmount = function () { + setTimeout(() => { + try { + originalUnmount() + } catch { + // Root may already have unmounted + } + }, 0) + } + return root + } + patchedCreateRoot.__react19Patched = true + rdc.createRoot = patchedCreateRoot + } + } catch { + // Read-only or unsupported environment + } +} + /** * drei's `Html`, keeping the editor's i18n scope. `Html` renders its children * in a separate React root, which sees none of the surrounding context, so a diff --git a/packages/editor/src/components/editor/room-labels.tsx b/packages/editor/src/components/editor/room-labels.tsx index 3849ef2ef0..3dda351123 100644 --- a/packages/editor/src/components/editor/room-labels.tsx +++ b/packages/editor/src/components/editor/room-labels.tsx @@ -1708,14 +1708,14 @@ export function RoomLabelAnchor3D({ useEffect(() => { anchors.set(entry.zoneId, position) }, [anchors, entry.zoneId, position]) - if (gone.has(entry.zoneId)) return null + const isGone = gone.has(entry.zoneId) return ( {children} From 282d716ba764a7696a9cca6479a374f13683ea45 Mon Sep 17 00:00:00 2001 From: saadmooh Date: Tue, 10 Nov 2026 00:19:20 +0100 Subject: [PATCH 6/8] feat(wall): collinear wall tracking transit and dimension input refocus --- packages/core/src/index.ts | 1 + .../src/systems/wall/wall-topology.test.ts | 12 +- .../core/src/systems/wall/wall-topology.ts | 2 +- .../src/components/editor/floorplan-panel.tsx | 36 ++++-- .../tools/shared/dimension-input.tsx | 13 +- packages/nodes/src/wall/tool.tsx | 112 +++++++++++------- 6 files changed, 117 insertions(+), 59 deletions(-) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c7f5182433..f4b6aaad7b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1319,6 +1319,7 @@ export { planWallEndRejoins, planWallInsertion, planWallSplitAtPoint, + wallSegmentsCoverSegment, type WallInsertionPlan, type WallJoinResult, type WallTopologyChanges, diff --git a/packages/core/src/systems/wall/wall-topology.test.ts b/packages/core/src/systems/wall/wall-topology.test.ts index 4842f47afa..01442c24f4 100644 --- a/packages/core/src/systems/wall/wall-topology.test.ts +++ b/packages/core/src/systems/wall/wall-topology.test.ts @@ -17,7 +17,7 @@ import { encodeTerrainField } from '../../lib/terrain-codec' import { applyHeightPatch, createTerrainField, flattenPatch } from '../../lib/terrain-field' import { type AnyNode, type AnyNodeId, DoorNode, WallNode, ZoneNode } from '../../schema' import { getWallArcData, getWallCurveFrameAt } from './wall-curve' -import { planWallInsertion, planWallSplitAtPoint } from './wall-topology' +import { planWallInsertion, planWallSplitAtPoint, wallSegmentsCoverSegment } from './wall-topology' const LEVEL_ID = 'level_topology' as AnyNodeId @@ -1076,4 +1076,12 @@ describe('a wall started in a corner block', () => { expect(result.plan.resolvedStart).toEqual([-0.5, 0]) expect(result.plan.changes.delete).toEqual(['wall_across']) }) -}) + test('wallSegmentsCoverSegment identifies collinear segments covered by host wall for tracking transit', () => { + // across runs from [-3, 0] to [0, 0] + expect(wallSegmentsCoverSegment([-2, 0], [-1, 0], [across])).toBe(true) + expect(wallSegmentsCoverSegment([-3, 0], [-1.5, 0], [across])).toBe(true) + // perpendicular or outside the host wall + expect(wallSegmentsCoverSegment([-1.5, 0], [-1.5, 2], [across])).toBe(false) + expect(wallSegmentsCoverSegment([-3, 0], [-4, 0], [across])).toBe(false) + }) +}); diff --git a/packages/core/src/systems/wall/wall-topology.ts b/packages/core/src/systems/wall/wall-topology.ts index 90189e49ec..006de7e8d1 100644 --- a/packages/core/src/systems/wall/wall-topology.ts +++ b/packages/core/src/systems/wall/wall-topology.ts @@ -118,7 +118,7 @@ function collinearWallIntervals( return { intervals, length } } -function wallSegmentsCoverSegment(start: WallPlanPoint, end: WallPlanPoint, walls: WallNode[]) { +export function wallSegmentsCoverSegment(start: WallPlanPoint, end: WallPlanPoint, walls: WallNode[]): boolean { const collinear = collinearWallIntervals(start, end, walls) if (!collinear) return false const parameterTolerance = WALL_INTERSECTION_EPSILON / collinear.length diff --git a/packages/editor/src/components/editor/floorplan-panel.tsx b/packages/editor/src/components/editor/floorplan-panel.tsx index 2a47aa07a8..f73be61265 100644 --- a/packages/editor/src/components/editor/floorplan-panel.tsx +++ b/packages/editor/src/components/editor/floorplan-panel.tsx @@ -64,6 +64,7 @@ import { WindowNode as WindowNodeSchema, wallClosesRoom, wallRectangleCorners, + wallSegmentsCoverSegment, } from '@pascal-app/core' import { useSegmentDraftChain, useWallSnapIndicator } from '@pascal-app/editor' import { getSceneTheme, useViewer } from '@pascal-app/viewer' @@ -10018,14 +10019,22 @@ export function FloorplanPanel({ setCursorPoint(null) return } - } else if (!(viewIs2DOnly || publishedNextStart)) { - // Split view: the 3D tool owns both the commit and the continuation - // decision, and it clears the published chain start whenever it stops - // drafting (room close, T-junction, single). Mirror that here instead - // of chaining the 2D draft from a dead point. - clearWallPlacementDraft() - setCursorPoint(null) - return + } else { + const levelWalls = Object.values(useScene.getState().nodes).filter( + (node): node is WallNode => node?.type === 'wall' && node.parentId === levelId, + ) + const isTransit = draftStart && wallSegmentsCoverSegment(draftStart, point, levelWalls) + if (isTransit) { + // Collinear tracking: start point advances along host wall without creating redundant wall + } else if (!(viewIs2DOnly || publishedNextStart)) { + // Split view: the 3D tool owns both the commit and the continuation + // decision, and it clears the published chain start whenever it stops + // drafting (room close, T-junction, single). Mirror that here instead + // of chaining the 2D draft from a dead point. + clearWallPlacementDraft() + setCursorPoint(null) + return + } } wallRunReferenceRef.current = placedDirection @@ -12001,6 +12010,7 @@ export function FloorplanPanel({ } else if (isFenceBuildActive) { emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) } else if (isPolygonDraftBuildActive) { + emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) if (isZoneBuildActive) { handleZonePlacementPoint(pt) } else if (isCeilingBuildActive) { @@ -12135,7 +12145,13 @@ function FloorplanDimensionInputOverlay({ ] useDimensionDraftStore.setState({ - points: [...currentDim.points, nextPoint], + lockedLength: length, + lockedAngle: angle, + }) + + onCommitPoint(nextPoint) + + useDimensionDraftStore.setState({ previewPoint: null, lengthValue: '', angleValue: '', @@ -12143,8 +12159,6 @@ function FloorplanDimensionInputOverlay({ lockedAngle: null, fieldType: 'length', }) - - onCommitPoint(nextPoint) }, [cursorPoint, draftStart, onCommitPoint]) // Resolve screen position: prefer live cursorPosition, fall back to lastPosition, diff --git a/packages/editor/src/components/tools/shared/dimension-input.tsx b/packages/editor/src/components/tools/shared/dimension-input.tsx index 80833df5e4..42d2086ce5 100644 --- a/packages/editor/src/components/tools/shared/dimension-input.tsx +++ b/packages/editor/src/components/tools/shared/dimension-input.tsx @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef } from 'react' -import { parseAngle, parseDimension } from '@pascal-app/core' +import { emitter, parseAngle, parseDimension } from '@pascal-app/core' export interface DimensionInputState { active: boolean @@ -65,6 +65,17 @@ export function DimensionInput({ } }, [state.active, state.fieldType]) + // Refocus input whenever dimension:focus is emitted (e.g. on digit shortcut entry) + useEffect(() => { + const handleFocus = (field: 'length' | 'angle') => { + focusField(field) + } + emitter.on('dimension:focus', handleFocus) + return () => { + emitter.off('dimension:focus', handleFocus) + } + }, [focusField]) + const commitValues = useCallback(() => { const length = parseDimension(state.lengthValue) const angle = parseAngle(state.angleValue) diff --git a/packages/nodes/src/wall/tool.tsx b/packages/nodes/src/wall/tool.tsx index 575b38e158..45688c3c1d 100644 --- a/packages/nodes/src/wall/tool.tsx +++ b/packages/nodes/src/wall/tool.tsx @@ -17,6 +17,7 @@ import { type WallMiterData, type WallNode, wallClosesRoom, + wallSegmentsCoverSegment, } from '@pascal-app/core' import { addWallPolygonDraftCorner, @@ -1042,51 +1043,74 @@ const LineWallTool: React.FC = () => { flatConstructionBase: flatConstructionBase.current, }, ) - if (!createdWall) return - chainWallIds.current.push(createdWall.id) - // The run's next wall holds square to this one. - runReference = wallRunDirection(createdWall.start, createdWall.end) - - // The new segment is now a real node — make it an alignment target - // for the next segment, and drop the just-shown guide. - refreshAlignmentCandidates() - useAlignmentGuides.getState().clear() - useWallSnapIndicator.getState().clear() - - // Multi-point wall drafting: continue drawing the next segment from the created wall's end point - - const closedToChainStart = - chainFirstVertex.current && - isWithinWallJoinSnapRadius(createdWall.end, chainFirstVertex.current) - - // Auto-close also fires when the segment seals a room against the - // existing wall network (e.g. a bay closed onto the middle of another - // wall), not just when the chain loops back to its own start. Shares the - // room graph with auto slab/ceiling detection so the two never disagree. - // A resolved end that tees into wall geometry outside the chain also - // terminates even without an enclosed room — nobody continues drawing - // from a T-junction into an existing wall; a dead end in free space - // keeps the chain going. - const levelWalls = getCurrentLevelWalls() - if ( - closedToChainStart || - chainEndJoinsExistingWall(createdWall.end, levelWalls, chainWallIds.current) || - (createdWall.type === 'wall' && wallClosesRoom(levelWalls, createdWall)) - ) { - stopDrafting() - return + let nextStart: WallPlanPoint + if (!createdWall) { + const levelWalls = getCurrentLevelWalls() + const startPt: WallPlanPoint = [startingPoint.current.x, startingPoint.current.z] + const isCollinearTransit = wallSegmentsCoverSegment(startPt, snappedEnd, levelWalls) + if (isCollinearTransit) { + nextStart = snappedEnd + runReference = wallRunDirection(startPt, snappedEnd) + triggerSFX('sfx:grid-snap') + const currentDim = useDimensionDraftStore.getState() + useDimensionDraftStore.setState({ + points: [...currentDim.points, nextStart], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + }) + } else { + return + } + } else { + chainWallIds.current.push(createdWall.id) + // The run's next wall holds square to this one. + runReference = wallRunDirection(createdWall.start, createdWall.end) + + // The new segment is now a real node — make it an alignment target + // for the next segment, and drop the just-shown guide. + refreshAlignmentCandidates() + useAlignmentGuides.getState().clear() + useWallSnapIndicator.getState().clear() + + // Multi-point wall drafting: continue drawing the next segment from the created wall's end point + + const closedToChainStart = + chainFirstVertex.current && + isWithinWallJoinSnapRadius(createdWall.end, chainFirstVertex.current) + + // Auto-close also fires when the segment seals a room against the + // existing wall network (e.g. a bay closed onto the middle of another + // wall), not just when the chain loops back to its own start. Shares the + // room graph with auto slab/ceiling detection so the two never disagree. + // A resolved end that tees into wall geometry outside the chain also + // terminates even without an enclosed room — nobody continues drawing + // from a T-junction into an existing wall; a dead end in free space + // keeps the chain going. + const levelWalls = getCurrentLevelWalls() + if ( + closedToChainStart || + chainEndJoinsExistingWall(createdWall.end, levelWalls, chainWallIds.current) || + (createdWall.type === 'wall' && wallClosesRoom(levelWalls, createdWall)) + ) { + stopDrafting() + return + } + nextStart = createdWall.end + const currentDim = useDimensionDraftStore.getState() + useDimensionDraftStore.setState({ + points: [...currentDim.points, nextStart], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + }) } - nextStart = createdWall.end - const currentDim = useDimensionDraftStore.getState() - useDimensionDraftStore.setState({ - points: [...currentDim.points, nextStart], - previewPoint: null, - lengthValue: '', - angleValue: '', - lockedLength: null, - lockedAngle: null, - fieldType: 'length', - }) } // Publish the resolved chain start so the 2D floor-plan draft // chains its next segment from the same point (its own snap From 044b382e982286b82944b0c122d94a274695389f Mon Sep 17 00:00:00 2001 From: saadmooh Date: Tue, 10 Nov 2026 16:52:39 +0100 Subject: [PATCH 7/8] fix(drafting): resolve Bugbot review issues on focus TDZ, wall nextStart shadowing, 2D vertex measurement, and fence confirm --- .../src/components/editor/floorplan-panel.tsx | 16 ++++++++++++++-- .../components/tools/shared/dimension-input.tsx | 16 +++++++++------- packages/nodes/src/wall/tool.tsx | 1 - 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/packages/editor/src/components/editor/floorplan-panel.tsx b/packages/editor/src/components/editor/floorplan-panel.tsx index b2ea94c296..4ec4ce9b47 100644 --- a/packages/editor/src/components/editor/floorplan-panel.tsx +++ b/packages/editor/src/components/editor/floorplan-panel.tsx @@ -10177,6 +10177,16 @@ export function FloorplanPanel({ setCursorPoint(nextStart) // What was typed belongs to this segment; the next starts afresh. usePlacementTyping.getState().clear() + const dim = useDimensionDraftStore.getState() + useDimensionDraftStore.setState({ + points: [...dim.points, nextStart], + previewPoint: null, + lengthValue: '', + angleValue: '', + lockedLength: null, + lockedAngle: null, + fieldType: 'length', + }) }, [ clearWallPlacementDraft, @@ -12137,6 +12147,7 @@ export function FloorplanPanel({ handleWallPlacementPoint(pt) } else if (isFenceBuildActive) { emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) + handleBackgroundPlacementClick(pt, new MouseEvent('click') as any) } else if (isPolygonDraftBuildActive) { emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) if (isZoneBuildActive) { @@ -12248,9 +12259,10 @@ function FloorplanDimensionInputOverlay({ const handleConfirm = useCallback(() => { const currentDim = useDimensionDraftStore.getState() const lastPt = - currentDim.points.length > 0 + draftStart ?? + (currentDim.points.length > 0 ? currentDim.points[currentDim.points.length - 1]! - : (draftStart ?? cursorPoint) + : cursorPoint) if (!lastPt) return const length = diff --git a/packages/editor/src/components/tools/shared/dimension-input.tsx b/packages/editor/src/components/tools/shared/dimension-input.tsx index 42d2086ce5..a35016d1c4 100644 --- a/packages/editor/src/components/tools/shared/dimension-input.tsx +++ b/packages/editor/src/components/tools/shared/dimension-input.tsx @@ -55,6 +55,14 @@ export function DimensionInput({ fieldTypeRef.current = state.fieldType }, [state.fieldType]) + const focusField = useCallback((field: 'length' | 'angle') => { + const target = field === 'length' ? lengthRef.current : angleRef.current + if (target) { + target.focus() + target.select() + } + }, []) + // Focus the correct input when fieldType changes useEffect(() => { if (!state.active) return @@ -88,13 +96,7 @@ export function DimensionInput({ } }, [state, onChange]) - const focusField = useCallback((field: 'length' | 'angle') => { - const target = field === 'length' ? lengthRef.current : angleRef.current - if (target) { - target.focus() - target.select() - } - }, []) + const handleLengthKeyDown = useCallback( (e: React.KeyboardEvent) => { diff --git a/packages/nodes/src/wall/tool.tsx b/packages/nodes/src/wall/tool.tsx index faf3781a4a..c2547ba804 100644 --- a/packages/nodes/src/wall/tool.tsx +++ b/packages/nodes/src/wall/tool.tsx @@ -1070,7 +1070,6 @@ const LineWallTool: React.FC = () => { flatConstructionBase: flatConstructionBase.current, }, ) - let nextStart: WallPlanPoint if (!createdWall) { const levelWalls = getCurrentLevelWalls() const startPt: WallPlanPoint = [startingPoint.current.x, startingPoint.current.z] From 1a9ed75bfcc4dd9e97a265ccaaa53a7007f85d00 Mon Sep 17 00:00:00 2001 From: saadmooh Date: Tue, 10 Nov 2026 17:12:43 +0100 Subject: [PATCH 8/8] fix(editor): avoid fence double-click emit and prevent opening commit on escape --- packages/editor/src/components/editor/floorplan-panel.tsx | 1 - .../src/components/editor/opening-guides-3d-layer.tsx | 6 ++++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/editor/src/components/editor/floorplan-panel.tsx b/packages/editor/src/components/editor/floorplan-panel.tsx index 4ec4ce9b47..0fa8ab7c61 100644 --- a/packages/editor/src/components/editor/floorplan-panel.tsx +++ b/packages/editor/src/components/editor/floorplan-panel.tsx @@ -12146,7 +12146,6 @@ export function FloorplanPanel({ emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) handleWallPlacementPoint(pt) } else if (isFenceBuildActive) { - emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) handleBackgroundPlacementClick(pt, new MouseEvent('click') as any) } else if (isPolygonDraftBuildActive) { emitFloorplanGridEvent('click', pt, new MouseEvent('click') as any) diff --git a/packages/editor/src/components/editor/opening-guides-3d-layer.tsx b/packages/editor/src/components/editor/opening-guides-3d-layer.tsx index 31f7494407..19d616f8c1 100644 --- a/packages/editor/src/components/editor/opening-guides-3d-layer.tsx +++ b/packages/editor/src/components/editor/opening-guides-3d-layer.tsx @@ -263,12 +263,14 @@ function OpeningGuide({ const [isEditing, setIsEditing] = useState(false) const [inputValue, setInputValue] = useState('') const inputRef = useRef(null) + const isCancelledRef = useRef(false) const isInteractive = Boolean(guide.kind === 'dimension' && guide.targetNodeId && guide.wallId && guide.role) const handleStartEdit = (e: React.MouseEvent) => { e.stopPropagation() if (!isInteractive || guide.kind !== 'dimension') return + isCancelledRef.current = false setIsEditing(true) setInputValue(formatMeasurement(guide.value, unit, metricNotation)) } @@ -281,6 +283,8 @@ function OpeningGuide({ }, [isEditing]) const handleCommit = () => { + if (isCancelledRef.current) return + isCancelledRef.current = true setIsEditing(false) if (guide.kind !== 'dimension' || !guide.targetNodeId || !guide.role) return const parsed = parseDimensionInput(inputValue, unit) @@ -337,12 +341,14 @@ function OpeningGuide({ } const handleCancel = () => { + isCancelledRef.current = true setIsEditing(false) } const handleKeyDown = (e: React.KeyboardEvent) => { e.stopPropagation() if (e.key === 'Enter') { + isCancelledRef.current = false handleCommit() } else if (e.key === 'Escape') { handleCancel()