@floless/app 0.133.2 → 0.134.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,7 +20,7 @@ import { RoomEnvironment } from 'three/addons/RoomEnvironment.js';
20
20
  import { surfaceTextures, applyTriplanar, TILE_MM, DIRECTIONAL } from './steel-materials.js';
21
21
  import { canvasToolGuidanceState } from './steel-canvas-guidance.js';
22
22
  import { Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg';
23
- import { snapPoint, planPointToWp, memberGeometry, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel, selectedLengthLabelAnchors, sectionKindOf, sectionTopology, memberMeshAxes, POSITION_BASIS_CAPABILITY_VERSION } from './steel-3d-core.js';
23
+ import { snapPoint, planPointToWp, memberGeometry, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel, selectedLengthLabelAnchors, sectionKindOf, sectionTopology, memberMeshAxes, positionSwingDelta, snapToStep, rollCommitNorm, unwrapAngleStep, slideEndpoints, swingBasis, swingEndpoint, swingBarriers, clampSwingTheta, POSITION_SWING_MARGIN_RAD, POSITION_OFFSET_SNAP_MM, POSITION_ROT_SNAP_DEG, POSITION_BASIS_CAPABILITY_VERSION } from './steel-3d-core.js';
24
24
  // `gridGeometry`, `gridCandidates3d` and `mmPerPx` live behind the host's model read boundary because
25
25
  // their display-scale argument is meaningless on a world-mm model grid.
26
26
  import { visibleGridLevels, gridTransientScopeSignature, reconcileGridTransientState, objectSelectionStatus } from './grid-core.js';
@@ -427,6 +427,7 @@ function loop() {
427
427
  sizeEndpoints();
428
428
  sizeClipHandles();
429
429
  sizeFrameHandle();
430
+ sizePositionGizmo();
430
431
  sizeGridLabels();
431
432
  positionDimLabels();
432
433
  positionOverlayLabels();
@@ -998,6 +999,7 @@ function buildFromScene(sc) {
998
999
  // (computeOverlayDims scopes the plate path to group 'shear-plate' — base/washer plates are skipped there.)
999
1000
  dimParts = (sc.elements || []).filter((el) => el && (el.kind === 'plate' || el.kind === 'cut'));
1000
1001
  renderClipGizmo(); // re-anchor the selected clip's gizmo to the (possibly new) sceneBox after a rebuild
1002
+ syncGizmoVisibility(); // re-anchor the Profile Position gizmo (the rebuild replaced its member's mesh); (un)hide the frame gizmo if availability changed
1001
1003
  buildGrid(box);
1002
1004
  // Reconcile mesh visibility BEFORE the structural grid: mixed member+grid isolation needs the
1003
1005
  // grid reconciler to see the surviving mesh count, otherwise deleting the last isolated member
@@ -4366,6 +4368,16 @@ function onKey(e) {
4366
4368
  if (framePicking() && e.key === 'Escape') { e.preventDefault(); if (frame3d) { cancelFramePick(); fireFrameChange(); } else armFrame3d(false); return; } // Esc cancels the whole 3-click pick (discards partial clicks); no prior frame → also exit the tool
4367
4369
  if (pending && pending.frameDrag && e.key === 'Escape') { e.preventDefault(); if (frame3d && pending.preFrame) frame3d = cloneFrame(pending.preFrame); pending = dragging = null; if (controls) controls.enabled = true; if (readout) readout.style.display = 'none'; fireFrameChange(); return; } // Esc mid-drag → revert the frame to its pre-drag basis
4368
4370
  if (frameMode && e.key === 'Escape' && !pending) { e.preventDefault(); disarmFrame3d(); return; } // armed but idle (frame set, gizmo grabbable for refine) → Esc exits the "Set local axes" tool (the frame stays; it just stops being editable). `!pending` so a mid-gesture Esc (member move / endpoint stretch, reachable while the tool is armed) still falls through to the cancel-and-revert below instead of silently committing (code-review) (frame set, gizmo grabbable for refine) → Esc exits the "Set local axes" tool (the frame stays; it just stops being editable). `!pending` so a mid-gesture Esc (member move / endpoint stretch, reachable while the tool is armed) still falls through to the cancel-and-revert below instead of silently committing (code-review)
4371
+ if (pending && pending.posGizmo && e.key === 'Escape') { // Esc mid-drag → cancel a Profile Position edit; put the live-previewed steel back, no commit
4372
+ e.preventDefault();
4373
+ restorePositionGizmoMesh(pending.posGizmo);
4374
+ pending = dragging = null;
4375
+ posInteraction = 'idle'; hidePositionLeader();
4376
+ if (controls) controls.enabled = true;
4377
+ if (readout) readout.style.display = 'none';
4378
+ renderPositionGizmo();
4379
+ return;
4380
+ }
4369
4381
  if (pending && e.key === 'Escape' && (pending.epDrag || pending.origMm)) { // Esc mid-drag → cancel a member move / endpoint stretch and revert to the pre-drag state (no commit)
4370
4382
  e.preventDefault();
4371
4383
  if (pending.mesh && pending.meshPos0) pending.mesh.position.copy(pending.meshPos0); // put a live-moved (or Alt-vertical) member mesh back
@@ -4648,6 +4660,25 @@ function reflectDimAxisBar() {
4648
4660
  // teleport the camera). Replaces the old set-orbit-pivot — zoom-to sets the pivot anyway, and
4649
4661
  // zoomToCursor already lets the wheel zoom toward the cursor.
4650
4662
  function onDblClick(e) {
4663
+ // Double-click a position handle → open the docked numeric HUD to type an exact value (spec §3.1); the two
4664
+ // mousedowns each start a zero-movement grab that onUp restores as a no-op (no undo entry), and cancelling any
4665
+ // lingering `pending` here upholds the one-editable-gizmo invariant before the HUD opens. This wins over the
4666
+ // zoom-to-part below, which only runs past this guard.
4667
+ if (positionGizmoVisible && posGizmoState && !frameMode) {
4668
+ let ph = null; try { ph = pickPositionGizmoHandle(e.clientX, e.clientY); } catch (err) { console.error('steel-3d: position-gizmo dblclick hit-test failed', err); ph = null; } // mirror onDown's logging — a swallowed exception here would silently fall through to zoom-to-part
4669
+ if (ph && ph !== 'anchor') {
4670
+ e.preventDefault(); e.stopPropagation();
4671
+ if (pending && pending.posGizmo) restorePositionGizmoMesh(pending.posGizmo);
4672
+ pending = dragging = null; posInteraction = 'idle'; hidePositionLeader();
4673
+ if (controls) controls.enabled = true; // defensive: normal dblclick sequencing already re-enabled controls via onUp, but if this branch is reached abnormally and the HUD does NOT open below, never strand the camera disabled (openPositionHud → setPositionTyping(true) re-freezes it when it does open)
4674
+ const scr = positionGizmoHandlesScreen();
4675
+ const p = scr && (ph === 'depth' ? scr.depthTip : ph === 'width' ? scr.widthTip
4676
+ : ph === 'slide' ? scr.slideTip : ph === 'swingPlan' ? scr.swingPlanHandle
4677
+ : ph === 'swingElev' ? scr.swingElevHandle : scr.rotHandle);
4678
+ if (p && api && api.openPositionHud) api.openPositionHud([...selIds][0], ph, [p.x, p.y]);
4679
+ return;
4680
+ }
4681
+ }
4651
4682
  camera.updateMatrixWorld(); root.updateMatrixWorld(true);
4652
4683
  const rect = canvasEl.getBoundingClientRect();
4653
4684
  const ndc = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
@@ -4694,6 +4725,7 @@ function setSelection(ids) {
4694
4725
  let reglow = false; for (const g of hoverGlowIds) if (!set.has(g)) { setHoverGlow(g, true, false); reglow = true; } // still-hovered, now-unselected parts keep their glow (the material swap above cleared it)
4695
4726
  if (reglow) applyDisplayMode(); // one re-sync after re-lighting the whole set, not one per part
4696
4727
  updateStatusChip();
4728
+ syncGizmoVisibility(); // the Profile Position gizmo follows the selection (single member only); (un)hides the frame gizmo to match
4697
4729
  }
4698
4730
  let selIds = new Set();
4699
4731
  // Material.clone() copies parameters but NOT instance-assigned callbacks, so a cloned highlight
@@ -5535,13 +5567,14 @@ function pointEntryCommit() { pointEntryTok = null; bumpPointEntryGen(); }
5535
5567
  // base/start so a stale anchor can't revalidate; soft (frame/workplane drift) keeps the world base.
5536
5568
  function invalidatePointEntry(reason) {
5537
5569
  const hadLive = !!pointEntryTok, hadStaged = !!(tfDraft && tfDraft.vA);
5570
+ const hadPosHud = posInteraction === 'typing'; // the position typed-HUD carries NO pointEntryTok, so it needs its own close/toast trigger (Codex): a rebuild/frame-change/hide must not leave it open committing against changed state with the camera frozen
5538
5571
  bumpPointEntryGen(); pointEntryTok = null;
5539
5572
  tfLast = null; tfLastClient = null; // drop the captured aim so a reopened {dist} demands a fresh hover under the new frame (Codex R5 #1)
5540
5573
  const hard = reason === 'rebuild' || reason === 'undo' || reason === 'view' || reason === 'hide';
5541
5574
  if (hard) { cmClear3d(); drClear3d(); }
5542
5575
  else if (tfDraft && tfDraft.vA) { tfDraft.vA = null; tfPreviewClear(); } // soft drift: drop staged direction A, keep the base (geometry didn't move)
5543
- if (hadLive && api && api.closeCmHud) api.closeCmHud(); // close an open typed-entry HUD
5544
- if (reason === 'drift' && (hadLive || hadStaged) && api && api.toast) api.toast('Frame changed — re-enter the value');
5576
+ if ((hadLive || hadPosHud) && api && api.closeCmHud) api.closeCmHud(); // close an open typed-entry HUD (movecopy/add token OR the tokenless position HUD → its close unfreezes the camera)
5577
+ if (reason === 'drift' && (hadLive || hadStaged || hadPosHud) && api && api.toast) api.toast('Frame changed — re-enter the value');
5545
5578
  }
5546
5579
  // A pointer base/start pick invalidates any open typed-entry token (silent — no toast): the anchor changed,
5547
5580
  // so a stale HUD from a prior phase/operation must not commit against the new draft.
@@ -5559,7 +5592,7 @@ function frameInfo() {
5559
5592
  }
5560
5593
  return { mode: 'global' };
5561
5594
  }
5562
- function fireFrameChange() { invalidatePointEntry('drift'); if (!(pending && pending.frameDrag)) { tfCandidates = null; dimCandidates3d = null; } renderWorkPlane(); reflectDimAxisBar(); updateStatusChip(); } // re-draws the gizmo + reference plane + fires the Axes chip; relabels the dim-axis bar (X′/Y′/Elev follows the frame); invalidates the typed HUD (drift) + the snap caches so the UCS-origin snap follows the frame — but NOT during a live origin drag (the drag's own snap cache, which excludes the origin, stays efficient)
5595
+ function fireFrameChange() { invalidatePointEntry('drift'); if (!(pending && pending.frameDrag)) { tfCandidates = null; dimCandidates3d = null; } renderWorkPlane(); reflectDimAxisBar(); updateStatusChip(); } // re-draws the gizmo + reference plane + fires the Axes chip; relabels the dim-axis bar (X′/Y′/Elev follows the frame); invalidates the typed HUD (drift) + the snap caches so the UCS-origin snap follows the frame — but NOT during a live origin drag (the drag's own snap cache, which excludes the origin, stays efficient). renderWorkPlane now re-syncs BOTH gizmos (arming/disarming the frame flips the position gizmo's visibility; the position gizmo hides the frame gizmo), so both react in one tick.
5563
5596
  // Set a HORIZONTAL frame at origin (numeric entry + gizmo materialize). origin defaults its Z to the active level.
5564
5597
  function setFrame3d(originMm, angleDeg) {
5565
5598
  const z = (originMm && originMm.length > 2) ? originMm[2] : frameZ();
@@ -5596,9 +5629,19 @@ function disarmFrame3d() { if (frameMode || framePicking()) { cancelFramePick();
5596
5629
  // overlayScene (2nd unclipped pass) so a section plane never cuts it. A set ◇ Plane shadows it (its own patch shows).
5597
5630
  let frameGizmo = null;
5598
5631
  function disposeFrameGizmo() { if (!frameGizmo) return; if (overlayScene) overlayScene.remove(frameGizmo); frameGizmo.traverse((o) => { if (o.geometry) o.geometry.dispose(); if (o.material) o.material.dispose(); }); frameGizmo = null; }
5632
+ // The two overlay gizmos never coexist as editables: the position handle sits ON the member and its blue depth /
5633
+ // green width read as the frame's blue/green axes, and a passive frame handle that still picks would steal a
5634
+ // position drag (a failure this codebase has shipped before). So each HIDES the other — draws nothing AND is not
5635
+ // hit-tested (structural, never opacity-0-but-still-picking). `currentPositionGizmoState()` already folds in the
5636
+ // toggle, single-selection, workPlane, availability and frameMode gates, so this is the single source of truth.
5637
+ function positionGizmoShowing() { return !!currentPositionGizmoState(); }
5638
+ // Re-render BOTH so a change to one (arm the frame, toggle the handle, change the selection) flips the other's
5639
+ // visibility in the same tick. Position first: it refreshes the `posGizmoState` cache the frame paths read.
5640
+ function syncGizmoVisibility() { renderPositionGizmo(); renderFrameGizmo(); }
5599
5641
  function renderFrameGizmo() {
5600
5642
  disposeFrameGizmo();
5601
5643
  if (!overlayScene) return; // ALWAYS draw the gizmo (matches the reference plane); a ◇ Plane no longer removes it
5644
+ if (positionGizmoShowing()) return; // position gizmo is the active editable → hide the frame gizmo entirely (no draw, nothing to pick)
5602
5645
  const on = frameMode && !workPlane; // grabbable/armed only when the LOCAL frame is the active basis (a ◇ Plane is picked, not gizmo-dragged)
5603
5646
  const { O, u: ux, v: uy, n: uz } = refPlaneBasis(); // effective basis the tools follow: ◇ Plane > local frame > global
5604
5647
  const u = new THREE.Vector3(...ux), v = new THREE.Vector3(...uy), n = new THREE.Vector3(...uz);
@@ -5626,11 +5669,493 @@ function sizeFrameHandle() {
5626
5669
  const O = frameGizmoOrigin(), wp = new THREE.Vector3(O[0], O[1], O[2]), r = pxToWorldAt(frameMode ? 7 : 5.5, wp);
5627
5670
  for (const h of frameGizmo.children) if (h.userData && h.userData.frameHandle === 'origin') h.scale.setScalar(r);
5628
5671
  }
5672
+
5673
+ // ---- Profile Position gizmo (slice 3a) -----------------------------------------------------------
5674
+ // A Tekla-shaped handle anchored to the SELECTED member's start work point: a blue depth arrow and a
5675
+ // green width arrow drive the numeric offsets, a red arc about the member axis drives the roll. The
5676
+ // editor owns the semantics (`api.positionGizmoState` / `api.commitMemberPosition`); the view only
5677
+ // draws the arrows and, on a drag, reports an ABSOLUTE new value back. Lives in `overlayScene` (2nd
5678
+ // unclipped pass, `depthTest:false`) so a section plane never cuts it, and the whole group is scaled
5679
+ // screen-constant like the frame/clip handles — grabbable on a 6" stub and a 40' girder alike.
5680
+ let positionGizmo = null; // THREE.Group, built in LOCAL space around the anchor, positioned + scaled per frame
5681
+ let positionGizmoVisible = false; // the ⋯ Display-menu toggle, pushed in from the editor
5682
+ let posGizmoState = null; // last api.positionGizmoState() snapshot for the single selection (anchor, axes, offsets)
5683
+ // Explicit interaction state consulted by every position-gizmo handler (drag/dblclick/keydown), instead of
5684
+ // trusting focus + stopPropagation (Fable 5 review): 'idle' | 'dragging' | 'typing'. 'typing' = the docked
5685
+ // numeric HUD is open (camera frozen); handlers that must not fire while typing check this and bail.
5686
+ let posInteraction = 'idle';
5687
+ let posHovered = false; // a position handle is under the cursor (drives the shared-#tooltip hide on leave)
5688
+ let positionLeader = null; // cyan #22d3ee rubber-band line: amber anchor → live drag point, shown for a whole drag
5689
+ const POS_GIZMO_REACH_PX = 132; // screen-constant arrow reach (spec §3)
5690
+ // Per-handle hover copy — leads with the consequence (spec §3) + the double-click-to-type hint (3b.3). Shown
5691
+ // through the shared themed #tooltip (api.showHandleTip), never a native title=.
5692
+ const POS_HANDLE_TIP = {
5693
+ depth: 'Slides the section along its depth axis. Drag, or double-click to type an exact value — ¼" snap; hold Shift for no snap.',
5694
+ width: 'Slides the section along its width axis. Drag, or double-click to type an exact value — ¼" snap; hold Shift for no snap.',
5695
+ rot: 'Rolls the section about the reference line. Drag, or double-click to type an exact angle — 5° snap; hold Shift for no snap.',
5696
+ // Slice 3b.1 — the three that move the reference LINE (and so the member itself), not the profile on it.
5697
+ // Each leads with that consequence, because it is the difference a detailer must not have to guess.
5698
+ slide: 'Slides the member along its own axis — both work points move together, length unchanged. Drag, or double-click to type an exact value — ¼" snap; hold Shift for no snap.',
5699
+ swingPlan: 'Swings the member in plan about its start point — the far end moves, the slope is kept. Drag, or double-click to type an exact angle — 5° snap; hold Shift for no snap.',
5700
+ swingElev: 'Tilts the member up or down about its start point — the far end moves, its plan direction is kept. Drag, or double-click to type an exact angle — 5° snap; hold Shift for no snap.',
5701
+ // Was unreachable until 3b.1 (pickPositionGizmoHandle could only answer depth/width/rot), and its old
5702
+ // wording — "This point never moves" — became false the moment the member-axis arrow shipped.
5703
+ anchor: 'Reference-line start — the profile offsets and both swings pivot here. The member-axis arrow slides it along with the far end; the dot itself is not a handle.',
5704
+ };
5705
+ // The reference-line handles' geometry (ui-ux pass). BOTH swing arcs are inherently centred on the member
5706
+ // axis — each rotates x̂ within its own plane — so at ±x̂ two same-radius arcs would COINCIDE and the
5707
+ // screen-space nearest-point pick would be arbitrary. Hence two lobes per arc, flanking +x̂ only, with a
5708
+ // dead zone over the axis itself: nearest arc point to the slide arrow's tip ≈42 px, plan lobe to elevation
5709
+ // lobe ≈55 px, both clear of the 26 px combined pick tolerance. Nothing is lost by not drawing near −x̂
5710
+ // (dragging the member "from behind" is not a real interaction), and the pointer may still be dragged past
5711
+ // the drawn lobe — the arc is the affordance, not the limit.
5712
+ const POS_SWING_R = 1.15; // both swing arcs, outside the 1.0 arrows and the 0.72 roll arc
5713
+ const POS_LOBE_START = 1 / 12; // 15° off the member axis, in PI units
5714
+ const POS_LOBE_SWEEP = 1 / 3; // ...through to 75°
5715
+ const POS_SWING_MARGIN_RAD = POSITION_SWING_MARGIN_RAD; // shared with the typed path — see steel-3d-core; if the two drift, a number the drag allows gets refused when typed
5716
+ function disposePositionGizmo() {
5717
+ hidePositionLeader(); // the transient drag leader never outlives a gizmo rebuild
5718
+ if (!positionGizmo) return;
5719
+ if (overlayScene) overlayScene.remove(positionGizmo);
5720
+ positionGizmo.traverse((o) => { if (o.geometry) o.geometry.dispose(); if (o.material) o.material.dispose(); });
5721
+ positionGizmo = null;
5722
+ }
5723
+ // The gizmo shows only when the toggle is on, exactly one member is selected, we are not in a work-plane
5724
+ // pick, and the editor reports the member as available (resolvable frame + offsets). Otherwise → null.
5725
+ function currentPositionGizmoState() {
5726
+ // frameMode hides the position gizmo: while the user is editing the coordinate system, the position handles
5727
+ // (and their per-frame-mutating roll digits) are noise and another hit-steal target — one editable gizmo at a
5728
+ // time (Fable 5). The reverse (position gizmo hides the frame gizmo) is enforced in renderFrameGizmo.
5729
+ if (!positionGizmoVisible || !api || !api.positionGizmoState || !overlayScene || workPlane || frameMode) return null;
5730
+ if (selIds.size !== 1) return null;
5731
+ const st = api.positionGizmoState([...selIds][0]);
5732
+ if (st && st.available) return st;
5733
+ // The editor computed a specific reason (incomplete work points, unresolvable basis, no frame). The
5734
+ // handle is deliberately not drawn, but log the reason so a "handle won't show" report is diagnosable
5735
+ // rather than an inert toggle with no tell. code-review: silent-failure #2.
5736
+ if (st && st.reason) console.debug('steel-3d: Profile Position handle hidden —', st.reason);
5737
+ return null;
5738
+ }
5739
+ function renderPositionGizmo() {
5740
+ disposePositionGizmo();
5741
+ const st = currentPositionGizmoState(); posGizmoState = st;
5742
+ if (!st) return;
5743
+ const g = new THREE.Group();
5744
+ const V = (a) => new THREE.Vector3(a[0], a[1], a[2]);
5745
+ const yv = V(st.yAxis), zv = V(st.zAxis);
5746
+ // Built in LOCAL space with the anchor at (0,0,0): the group carries no rotation, so local coords ARE
5747
+ // world offsets from the anchor, and scaling the whole group keeps every part screen-constant.
5748
+ const arrow = (dirArr, col, tag) => {
5749
+ const d = V(dirArr).normalize();
5750
+ const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), d.clone().multiplyScalar(1)]),
5751
+ new THREE.LineBasicMaterial({ color: col }));
5752
+ line.material.depthTest = false; line.renderOrder = 997; line.userData = { posHandle: tag, stem: true }; g.add(line);
5753
+ const cone = new THREE.Mesh(new THREE.ConeGeometry(0.13, 0.36, 16), new THREE.MeshBasicMaterial({ color: col }));
5754
+ cone.material.depthTest = false; cone.renderOrder = 998; cone.quaternion.setFromUnitVectors(_YA, d);
5755
+ cone.position.copy(d.clone().multiplyScalar(1)); cone.userData = { posHandle: tag, arrow: true }; g.add(cone);
5756
+ };
5757
+ // BY DESIGN the arrows point along the UNROTATED part axes (st.zAxis/st.yAxis), because a Profile
5758
+ // Position offset is defined on the unrotated profile (§1.3). For a rolled member (rot ≠ 0) the steel
5759
+ // therefore travels along the roll-swung direction, not along the arrow — the gizmo stays internally
5760
+ // consistent (grab arrow → offset changes by the amount dragged along it) and preview↔commit agree, but
5761
+ // arrow and motion diverge. Re-expressing the roll so they coincide is slice 3b; do not "fix" one half.
5762
+ arrow(st.zAxis, 0x3b82f6, 'depth'); // blue = depth (positionOffset)
5763
+ arrow(st.yAxis, 0x22c55e, 'width'); // green = width (positionHOffset)
5764
+ // Rotation arc (red) about the member axis, drawn in the width–depth plane over a 270° sweep so both
5765
+ // ends stay clear of the two arrows.
5766
+ const R = 0.72, pts = [];
5767
+ for (let i = 0; i <= 36; i++) { const p = (-0.75 + (i / 36) * 1.5) * Math.PI;
5768
+ pts.push(yv.clone().multiplyScalar(Math.cos(p) * R).add(zv.clone().multiplyScalar(Math.sin(p) * R))); }
5769
+ const arc = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineBasicMaterial({ color: 0xef4444 }));
5770
+ arc.material.depthTest = false; arc.renderOrder = 997; arc.userData = { posHandle: 'rot', arc: true }; g.add(arc);
5771
+ // --- Reference-line handles (slice 3b.1) ---------------------------------------------------------
5772
+ // These move the member's WORK POINTS; the three above move the profile within a fixed reference line.
5773
+ // COLOUR IS BY AXIS, not by that family split: the shipped mapping is already blue=Z(depth),
5774
+ // green=Y(width), red=X (the roll arc rotates ABOUT x), each axis carrying only one of its two degrees
5775
+ // of freedom. These complete the pairs — red for the X translate (pairing with the red X roll arc, told
5776
+ // apart by shape exactly as the blue/green arrows already are), green for the rotation about Y, blue for
5777
+ // the plan swing. The last is a LABELLED approximation: it rotates about basis-up, which equals the local
5778
+ // zAxis only for a level unrolled member — which is why its copy says "in plan" and never "depth axis".
5779
+ // The palette is locked; this adds no hue.
5780
+ if (st.handles && st.handles.slide && st.handles.slide.available) arrow(st.xAxis, 0xef4444, 'slide');
5781
+ const swingArc = (axisArr, col, tag) => {
5782
+ const b = axisArr && swingBasis(st.anchor, st.end, axisArr);
5783
+ if (!b) { console.warn('steel-3d: a swing arc the editor reports as available has no swing plane —', tag); return; } // must not vanish silently: the handle would then be un-drawable, un-pickable and un-diagnosable
5784
+ for (const side of [1, -1]) {
5785
+ const pts = [];
5786
+ for (let i = 0; i <= 36; i++) {
5787
+ const p = side * (POS_LOBE_START + (i / 36) * POS_LOBE_SWEEP) * Math.PI, c = Math.cos(p) * POS_SWING_R, s = Math.sin(p) * POS_SWING_R;
5788
+ pts.push(new THREE.Vector3(b.e1[0] * c + b.e2[0] * s, b.e1[1] * c + b.e2[1] * s, b.e1[2] * c + b.e2[2] * s));
5789
+ }
5790
+ const lobe = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineBasicMaterial({ color: col }));
5791
+ lobe.material.depthTest = false; lobe.renderOrder = 997; lobe.userData = { posHandle: tag, arc: true }; g.add(lobe);
5792
+ }
5793
+ };
5794
+ if (st.handles && st.handles.swingPlan && st.handles.swingPlan.available) swingArc(st.up, 0x3b82f6, 'swingPlan');
5795
+ if (st.handles && st.handles.swingElev && st.handles.swingElev.available) swingArc(st.yAxis, 0x22c55e, 'swingElev');
5796
+ // Anchor dot (amber) — the reference-line start the whole gizmo pivots on.
5797
+ const dot = new THREE.Mesh(new THREE.SphereGeometry(0.08, 12, 8), new THREE.MeshBasicMaterial({ color: 0xf59e0b }));
5798
+ dot.material.depthTest = false; dot.renderOrder = 999; dot.userData = { posHandle: 'anchor' }; g.add(dot);
5799
+ g.position.set(st.anchor[0], st.anchor[1], st.anchor[2]);
5800
+ positionGizmo = g; overlayScene.add(g); sizePositionGizmo();
5801
+ }
5802
+ // Cyan #22d3ee rubber-band leader from the amber anchor to the live drag point — the "offsetting from a fixed
5803
+ // point" signal. #22d3ee already ships as the frame-gizmo rotation ring + the cmHud selected-segment accent, so
5804
+ // it is in-palette (blessed by the ui-ux pass). Lives in the overlay scene, depthTest:false, above the arrows.
5805
+ function updatePositionLeader(tipWorld) {
5806
+ if (!overlayScene || !posGizmoState) return;
5807
+ const O = posGizmoState.anchor, pts = [new THREE.Vector3(O[0], O[1], O[2]), new THREE.Vector3(tipWorld[0], tipWorld[1], tipWorld[2])];
5808
+ if (!positionLeader) {
5809
+ positionLeader = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineBasicMaterial({ color: 0x22d3ee, transparent: true, opacity: 0.9 }));
5810
+ positionLeader.material.depthTest = false; positionLeader.renderOrder = 996; overlayScene.add(positionLeader);
5811
+ } else { positionLeader.geometry.setFromPoints(pts); positionLeader.geometry.computeBoundingSphere && positionLeader.geometry.computeBoundingSphere(); }
5812
+ positionLeader.visible = true;
5813
+ }
5814
+ function hidePositionLeader() { if (positionLeader) positionLeader.visible = false; }
5815
+ function disposePositionLeader() {
5816
+ if (!positionLeader) return;
5817
+ if (overlayScene) overlayScene.remove(positionLeader);
5818
+ if (positionLeader.geometry) positionLeader.geometry.dispose(); if (positionLeader.material) positionLeader.material.dispose();
5819
+ positionLeader = null;
5820
+ }
5821
+ // Screen-constant: scale the whole group so a unit-length arrow spans POS_GIZMO_REACH_PX at the anchor.
5822
+ function sizePositionGizmo() {
5823
+ if (!positionGizmo || !posGizmoState) return;
5824
+ const O = posGizmoState.anchor;
5825
+ positionGizmo.scale.setScalar(pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2])));
5826
+ }
5827
+ // The gizmo's grab points in client px, for an E2E to drive precise drags (mirrors frameHandlesScreen).
5828
+ function positionGizmoHandlesScreen() {
5829
+ if (!canvasEl || !posGizmoState) return null;
5830
+ camera.updateMatrixWorld();
5831
+ const rect = canvasEl.getBoundingClientRect(), O = posGizmoState.anchor;
5832
+ const sc = pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2]));
5833
+ const toS = (p) => { const w = new THREE.Vector3(p[0], p[1], p[2]).project(camera);
5834
+ return { x: rect.left + (w.x * 0.5 + 0.5) * rect.width, y: rect.top + (-w.y * 0.5 + 0.5) * rect.height, behind: w.z > 1 }; };
5835
+ const at = (ax, k) => toS([O[0] + ax[0] * sc * k, O[1] + ax[1] * sc * k, O[2] + ax[2] * sc * k]);
5836
+ const rotArr = [posGizmoState.yAxis[0] * 0.51 + posGizmoState.zAxis[0] * 0.51,
5837
+ posGizmoState.yAxis[1] * 0.51 + posGizmoState.zAxis[1] * 0.51,
5838
+ posGizmoState.yAxis[2] * 0.51 + posGizmoState.zAxis[2] * 0.51];
5839
+ // Slice 3b.1 grab points. The swing grabs sit mid-lobe (45° off the member axis) on the +side lobe —
5840
+ // the same point the pick samples nearest, so an E2E drag from here lands on the handle it named.
5841
+ const swingGrab = (axisArr) => {
5842
+ const b = axisArr && posGizmoState.end && swingBasis(posGizmoState.anchor, posGizmoState.end, axisArr);
5843
+ if (!b) return null;
5844
+ const p = (POS_LOBE_START + POS_LOBE_SWEEP / 2) * Math.PI, c = Math.cos(p), s = Math.sin(p);
5845
+ return at([b.e1[0] * c + b.e2[0] * s, b.e1[1] * c + b.e2[1] * s, b.e1[2] * c + b.e2[2] * s], POS_SWING_R);
5846
+ };
5847
+ const h = posGizmoState.handles;
5848
+ return { anchor: toS(O), depthTip: at(posGizmoState.zAxis, 1), widthTip: at(posGizmoState.yAxis, 1), rotHandle: at(rotArr, 1),
5849
+ slideTip: h && h.slide && h.slide.available ? at(posGizmoState.xAxis, 1) : null,
5850
+ swingPlanHandle: h && h.swingPlan && h.swingPlan.available ? swingGrab(posGizmoState.up) : null,
5851
+ swingElevHandle: h && h.swingElev && h.swingElev.available ? swingGrab(posGizmoState.yAxis) : null,
5852
+ handles: h || null, available: true };
5853
+ }
5854
+ function setPositionGizmoVisible(on) { positionGizmoVisible = !!on; syncGizmoVisibility(); } // ⋯ Display toggle → editor pushes the flag (also (un)hides the frame gizmo)
5855
+ // The editor's docked numeric HUD is open on a handle → freeze the camera so orbit/zoom can't drift the anchor
5856
+ // the HUD is pinned to (Fable 5 trap #4), and mark the explicit interaction state so canvas handlers bail.
5857
+ function setPositionTyping(on) {
5858
+ posInteraction = on ? 'typing' : 'idle';
5859
+ if (controls) controls.enabled = !on; // idle default = orbit enabled; typing = frozen
5860
+ if (on) { hidePositionLeader(); posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); }
5861
+ if (canvasEl) canvasEl.style.cursor = on ? 'text' : 'default';
5862
+ }
5863
+ // E2E read-only probe: a member mesh's WORLD transform, so a test can assert a gizmo drag's live preview
5864
+ // equals the committed rebuild (no jump on release) and that "From member" leaves the steel exactly put.
5865
+ function memberWorldTransform(id) {
5866
+ const mesh = meshById.get(id); if (!mesh) return null;
5867
+ mesh.updateWorldMatrix(true, false);
5868
+ const p = new THREE.Vector3(), q = new THREE.Quaternion(), sc = new THREE.Vector3();
5869
+ mesh.matrixWorld.decompose(p, q, sc);
5870
+ return { pos: [p.x, p.y, p.z], quat: [q.x, q.y, q.z, q.w] };
5871
+ }
5872
+ // E2E read-only probes (3b.3): is the cyan drag leader currently shown, and is the UCS frame gizmo currently
5873
+ // drawn? The latter proves the mutual hide (position gizmo showing → frame gizmo null → not pickable).
5874
+ function positionLeaderVisible() { return !!(positionLeader && positionLeader.visible); }
5875
+ function frameGizmoVisible() { return !!frameGizmo; }
5876
+
5877
+ // --- Profile Position gizmo: pick + drag. depth/width arrows drive the numeric offsets; the arc drives
5878
+ // the roll. Every gesture reports an ABSOLUTE new value to the editor on release (one undo entry).
5879
+ const POS_SNAP_MM = POSITION_OFFSET_SNAP_MM; // ¼" offset snap (shared with the bake helpers, in steel-3d-core)
5880
+ const POS_SNAP_DEG = POSITION_ROT_SNAP_DEG; // 5° rotation snap
5881
+ const POS_EDGE_ON_PX = 26; // below this projected axis length a drag is refused (spec §3.1)
5882
+ function posGizmoRay(e) {
5883
+ const rect = canvasEl.getBoundingClientRect();
5884
+ const ndc = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
5885
+ const rc = new THREE.Raycaster(); rc.setFromCamera(ndc, camera); return rc.ray;
5886
+ }
5887
+ // Signed distance (mm) along a unit axis through the anchor to the pointer ray's closest approach.
5888
+ function posGizmoAxisScalar(e, st, axisArr) {
5889
+ const ray = posGizmoRay(e);
5890
+ const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
5891
+ const u = new THREE.Vector3(axisArr[0], axisArr[1], axisArr[2]).normalize(), v = ray.direction;
5892
+ const w0 = new THREE.Vector3().subVectors(O, ray.origin);
5893
+ const b = u.dot(v), denom = 1 - b * b; // a = u·u = 1 (u is unit), c = v·v = 1 (ray dir is unit)
5894
+ if (Math.abs(denom) < 1e-9) return null; // ray parallel to the axis (edge-on)
5895
+ return (b * v.dot(w0) - u.dot(w0)) / denom; // t on the axis line, in mm
5896
+ }
5897
+ // Angle (rad) of the pointer in the member's transverse plane, measured +y → +z.
5898
+ function posGizmoArcAngle(e, st) {
5899
+ const ray = posGizmoRay(e);
5900
+ const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
5901
+ const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(new THREE.Vector3(st.xAxis[0], st.xAxis[1], st.xAxis[2]).normalize(), O);
5902
+ const hit = new THREE.Vector3(); if (!ray.intersectPlane(plane, hit)) return null;
5903
+ const d = new THREE.Vector3().subVectors(hit, O);
5904
+ return Math.atan2(d.dot(new THREE.Vector3(st.zAxis[0], st.zAxis[1], st.zAxis[2])), d.dot(new THREE.Vector3(st.yAxis[0], st.yAxis[1], st.yAxis[2])));
5905
+ }
5906
+ /**
5907
+ * The pointer's angle in a swing's own plane, measured in the FROZEN in-plane basis: `atan2(d·e2, d·e1)`
5908
+ * with `e1 × e2 = axis`. Because the basis is right-handed about the rotation axis, a positive angle is
5909
+ * the same sweep whichever side of the screen the camera is on — which a screen-pixel delta cannot give,
5910
+ * and which is why the arc is drawn in this same basis. null when the ray is parallel to the plane.
5911
+ */
5912
+ function posSwingAngle(e, st, axisArr, basis) {
5913
+ if (!axisArr || !basis) return null;
5914
+ const ray = posGizmoRay(e);
5915
+ const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
5916
+ const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(new THREE.Vector3(axisArr[0], axisArr[1], axisArr[2]).normalize(), O);
5917
+ const hit = new THREE.Vector3(); if (!ray.intersectPlane(plane, hit)) return null;
5918
+ const d = new THREE.Vector3().subVectors(hit, O);
5919
+ return Math.atan2(d.dot(new THREE.Vector3(basis.e2[0], basis.e2[1], basis.e2[2])),
5920
+ d.dot(new THREE.Vector3(basis.e1[0], basis.e1[1], basis.e1[2])));
5921
+ }
5922
+ function pickPositionGizmoHandle(cx, cy) {
5923
+ if (!positionGizmoVisible || !posGizmoState || !canvasEl) return null;
5924
+ const h = positionGizmoHandlesScreen(); if (!h) return null;
5925
+ const hit = (pt) => pt && !pt.behind && Math.hypot(pt.x - cx, pt.y - cy) <= 14;
5926
+ if (hit(h.depthTip)) return 'depth';
5927
+ if (hit(h.widthTip)) return 'width';
5928
+ // Sighting straight down the member axis collapses the slide arrow to a point AND takes both swing arc
5929
+ // planes edge-on at once — a genuinely degenerate view. Refuse those three picks there rather than try to
5930
+ // out-geometry it, exactly as the depth/width arrows already refuse their own edge-on drag.
5931
+ const axisOk = h.anchor && !h.anchor.behind && h.slideTip && !h.slideTip.behind
5932
+ && Math.hypot(h.slideTip.x - h.anchor.x, h.slideTip.y - h.anchor.y) >= POS_EDGE_ON_PX;
5933
+ if (axisOk && hit(h.slideTip)) return 'slide';
5934
+ const O = posGizmoState.anchor, sc = pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2]));
5935
+ const rect = canvasEl.getBoundingClientRect();
5936
+ // Sample an arc in screen space and take the nearest point within tolerance.
5937
+ const nearestOn = (samples) => { let best = 12;
5938
+ for (const w0 of samples) { const w = w0.project(camera);
5939
+ if (w.z > 1) continue; const sx = rect.left + (w.x * 0.5 + 0.5) * rect.width, sy = rect.top + (-w.y * 0.5 + 0.5) * rect.height;
5940
+ const dd = Math.hypot(sx - cx, sy - cy); if (dd < best) best = dd; }
5941
+ return best < 12; };
5942
+ const yv = posGizmoState.yAxis, zv = posGizmoState.zAxis, roll = [];
5943
+ for (let i = 0; i <= 36; i++) { const p = (-0.75 + (i / 36) * 1.5) * Math.PI, c = Math.cos(p) * 0.72, s = Math.sin(p) * 0.72;
5944
+ roll.push(new THREE.Vector3(O[0] + (yv[0] * c + zv[0] * s) * sc, O[1] + (yv[1] * c + zv[1] * s) * sc, O[2] + (yv[2] * c + zv[2] * s) * sc)); }
5945
+ if (nearestOn(roll)) return 'rot';
5946
+ if (!axisOk) return null;
5947
+ const lobeSamples = (axisArr) => {
5948
+ const b = posGizmoState.end && axisArr && swingBasis(posGizmoState.anchor, posGizmoState.end, axisArr);
5949
+ if (!b) return [];
5950
+ const out = [];
5951
+ for (const side of [1, -1]) for (let i = 0; i <= 36; i++) {
5952
+ const p = side * (POS_LOBE_START + (i / 36) * POS_LOBE_SWEEP) * Math.PI, c = Math.cos(p) * POS_SWING_R * sc, s = Math.sin(p) * POS_SWING_R * sc;
5953
+ out.push(new THREE.Vector3(O[0] + b.e1[0] * c + b.e2[0] * s, O[1] + b.e1[1] * c + b.e2[1] * s, O[2] + b.e1[2] * c + b.e2[2] * s));
5954
+ }
5955
+ return out; };
5956
+ if (h.swingPlanHandle && nearestOn(lobeSamples(posGizmoState.up))) return 'swingPlan';
5957
+ if (h.swingElevHandle && nearestOn(lobeSamples(posGizmoState.yAxis))) return 'swingElev';
5958
+ return null;
5959
+ }
5960
+ // The amber anchor dot, hit-tested SEPARATELY and consulted ONLY by the hover/tooltip path. Deliberately
5961
+ // not part of `pickPositionGizmoHandle`: that function's answers arm a drag in onDown, and the dot is not
5962
+ // draggable — a mousedown on it must keep falling through to ordinary click-select, exactly as it always
5963
+ // has. Two independent checks over the same pixels, with different consumers. (Before 3b.1 the anchor's
5964
+ // tooltip copy existed but could never be shown, because nothing ever answered 'anchor'.)
5965
+ function pickPositionAnchorHover(cx, cy) {
5966
+ if (!positionGizmoVisible || !posGizmoState || !canvasEl) return false;
5967
+ const h = positionGizmoHandlesScreen();
5968
+ return !!(h && h.anchor && !h.anchor.behind && Math.hypot(h.anchor.x - cx, h.anchor.y - cy) <= 11);
5969
+ }
5970
+ function startPositionGizmoDrag(kind, e) {
5971
+ const id = [...selIds][0], st = api.positionGizmoState(id);
5972
+ // The handle was picked from the CACHED snapshot, but the base value comes from a FRESH read — if the
5973
+ // frame drifted in between, bail AND re-enable orbit (onDown disabled it before calling us; without this
5974
+ // a fall-through click on empty space would strand the camera). code-review: silent-failure #1.
5975
+ if (!st || !st.available) { pending = null; if (controls) controls.enabled = true; return; }
5976
+ const mesh = meshById.get(id);
5977
+ const mesh0 = { meshPos0: mesh ? mesh.position.clone() : null, meshQuat0: mesh ? mesh.quaternion.clone() : null };
5978
+ // --- Reference-line gestures (slice 3b.1): freeze EVERYTHING the gesture depends on, right here.
5979
+ // The rotation axis, the drag-start far endpoint, the in-plane basis and the plumb barriers are all
5980
+ // constants for the whole gesture, so each tick applies the TOTAL angle to the frozen endpoint rather
5981
+ // than composing per-tick rotations (which drifts, and makes the 5° snap chatter). The barriers in
5982
+ // particular are closed-form and cannot change while the geometry is frozen — computing them once here
5983
+ // instead of per pointer-move keeps the drag path O(1).
5984
+ if (kind === 'slide' || kind === 'swingPlan' || kind === 'swingElev') {
5985
+ const avail = st.handles && st.handles[kind];
5986
+ if (!avail || !avail.available) {
5987
+ // A VISIBLE, hovering, tooltipped handle that does nothing on press is confusing — the handles are
5988
+ // hit-tested from the cached state while this re-reads fresh, so a model change in between can make
5989
+ // one dead. Say so, exactly as openPositionHud already does for the same stale-cache case, instead
5990
+ // of returning into silence. (console.debug alone is invisible at Chrome's default level.)
5991
+ const why = (avail && avail.reason) || 'That handle isn’t available on this member.';
5992
+ console.warn('steel-3d: reference-line handle refused —', why);
5993
+ positionGizmoReadout(e, why, '');
5994
+ pending = null; if (controls) controls.enabled = true; return;
5995
+ }
5996
+ const swingAxis = kind === 'swingPlan' ? st.up : kind === 'swingElev' ? st.yAxis : null;
5997
+ const basis = swingAxis ? swingBasis(st.anchor, st.end, swingAxis) : null;
5998
+ // Only the ELEVATION swing can reach plumb: a plan swing preserves the member's distance from the
5999
+ // degeneracy cone exactly, so it can neither enter nor leave it and needs no barrier at all.
6000
+ const barriers = kind === 'swingElev' ? swingBarriers(st.anchor, st.end, st.yAxis, st.up, POS_SWING_MARGIN_RAD) : null;
6001
+ if (kind !== 'slide' && (!basis || (kind === 'swingElev' && !barriers))) {
6002
+ const why = 'This member can’t be swung from its current direction — set its geometry in the Inspect panel.';
6003
+ console.warn('steel-3d: reference-line swing refused — no usable', basis ? 'plumb barrier' : 'swing plane');
6004
+ positionGizmoReadout(e, why, '');
6005
+ pending = null; if (controls) controls.enabled = true; return;
6006
+ }
6007
+ const startScalar = kind === 'slide' ? posGizmoAxisScalar(e, st, st.xAxis) : posSwingAngle(e, st, swingAxis, basis);
6008
+ pending = { posGizmo: { id, axis: kind, state: st, refline: true, base: 0, startScalar, newVal: 0,
6009
+ swingAxis, basis, barriers, accumRad: 0, prevAng: startScalar, ...mesh0 } };
6010
+ posInteraction = 'dragging';
6011
+ posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip();
6012
+ downXY = [e.clientX, e.clientY];
6013
+ return;
6014
+ }
6015
+ const base = kind === 'depth' ? st.positionOffset : kind === 'width' ? st.positionHOffset : st.rot;
6016
+ const startScalar = kind === 'rot' ? posGizmoArcAngle(e, st) : posGizmoAxisScalar(e, st, kind === 'depth' ? st.zAxis : st.yAxis);
6017
+ pending = { posGizmo: { id, axis: kind, state: st, base, startScalar, newVal: base,
6018
+ accumRad: 0, prevAng: kind === 'rot' ? startScalar : null, // rot: accumulate the arc CONTINUOUSLY (unwrapAngleStep) so a ±180° seam crossing never jumps ~2π
6019
+ ...mesh0 } };
6020
+ posInteraction = 'dragging';
6021
+ posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); // the hover handler is inert during a drag — clear any lingering handle tip so it doesn't sit where the readout will land
6022
+ downXY = [e.clientX, e.clientY];
6023
+ }
6024
+ function positionGizmoReadout(e, txt, type) {
6025
+ if (!readout) return;
6026
+ readout._dist.textContent = txt; readout._type.textContent = type;
6027
+ readout.style.left = (e.clientX + 14) + 'px'; readout.style.top = (e.clientY + 14) + 'px'; readout.style.display = 'block';
6028
+ }
6029
+ function restorePositionGizmoMesh(pg) {
6030
+ const mesh = meshById.get(pg.id); if (!mesh) return;
6031
+ if (pg.meshPos0) mesh.position.copy(pg.meshPos0);
6032
+ if (pg.meshQuat0) mesh.quaternion.copy(pg.meshQuat0);
6033
+ }
6034
+ function onMovePositionGizmo(e) {
6035
+ if (!dragging && Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]) <= DRAG_TOL_PX) return;
6036
+ dragging = pending;
6037
+ const pg = pending.posGizmo, st = pg.state, mesh = meshById.get(pg.id);
6038
+ if (pg.refline) { onMoveRefLineGizmo(e, pg, st, mesh); return; }
6039
+ if (pg.axis === 'rot') {
6040
+ const ang = posGizmoArcAngle(e, st);
6041
+ if (ang == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6042
+ if (pg.startScalar == null) { pg.startScalar = ang; pg.prevAng = ang; return; } // grab was edge-on → set the reference on the first valid hit
6043
+ if (pg.prevAng == null) pg.prevAng = ang;
6044
+ // Accumulate the arc CONTINUOUSLY (shortest-arc step per move) so dragging across the ±180° seam adds a
6045
+ // small increment instead of the ~2π jump a bare (ang − start) makes near the seam. The running total is
6046
+ // the true swept angle, so the value tracks the hand monotonically and renormalizes only on commit.
6047
+ pg.accumRad += unwrapAngleStep(pg.prevAng, ang); pg.prevAng = ang;
6048
+ // Snap the DELTA, not the absolute value: since 3b.2 the resting roll is re-expressed into the current
6049
+ // frame and is generically off-grid (e.g. 33.71°), so snapping the absolute would yank the steel to the
6050
+ // 5° grid on the very first drag tick (a jump at drag-START). Stepping the delta keeps the value at the
6051
+ // member's own roll when Δ=0 and moves in 5° increments from there.
6052
+ const rawDeltaDeg = pg.accumRad * 180 / Math.PI;
6053
+ const deg = pg.base + (e.shiftKey ? rawDeltaDeg : snapToStep(rawDeltaDeg, POS_SNAP_DEG));
6054
+ pg.newVal = deg;
6055
+ if (mesh && pg.meshPos0 && pg.meshQuat0) { // exact live preview: roll about the reference-line anchor
6056
+ const axis = new THREE.Vector3(st.xAxis[0], st.xAxis[1], st.xAxis[2]).normalize();
6057
+ const roll = new THREE.Quaternion().setFromAxisAngle(axis, (deg - pg.base) * Math.PI / 180);
6058
+ const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
6059
+ mesh.position.copy(pg.meshPos0.clone().sub(O).applyQuaternion(roll).add(O));
6060
+ mesh.quaternion.copy(roll.clone().multiply(pg.meshQuat0));
6061
+ }
6062
+ { const O = st.anchor, R = 0.72 * pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2])), c = Math.cos(ang), s2 = Math.sin(ang);
6063
+ updatePositionLeader([O[0] + (st.yAxis[0] * c + st.zAxis[0] * s2) * R, O[1] + (st.yAxis[1] * c + st.zAxis[1] * s2) * R, O[2] + (st.yAxis[2] * c + st.zAxis[2] * s2) * R]); }
6064
+ positionGizmoReadout(e, 'Rotation ' + Math.round(deg) + '°', ''); // label-first, to match the Inspect panel's "Rotation" row
6065
+ return;
6066
+ }
6067
+ // depth / width: refuse an edge-on axis (a foreshortened axis inflates mm-per-pixel without bound).
6068
+ const scr = positionGizmoHandlesScreen();
6069
+ const tip = scr && (pg.axis === 'depth' ? scr.depthTip : scr.widthTip);
6070
+ if (scr && tip && !tip.behind && Math.hypot(tip.x - scr.anchor.x, tip.y - scr.anchor.y) < POS_EDGE_ON_PX) {
6071
+ positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return;
6072
+ }
6073
+ const s = posGizmoAxisScalar(e, st, pg.axis === 'depth' ? st.zAxis : st.yAxis);
6074
+ if (s == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6075
+ if (pg.startScalar == null) { pg.startScalar = s; return; } // grab was edge-on → set the reference on the first valid hit (mirrors the rot arm)
6076
+ // Snap the DELTA, not the absolute (see the rot arm): a base offset need not be grid-aligned — since 3b.2
6077
+ // it commonly is not — so snapping the absolute would jump to the ¼" grid on the first tick. Stepping the
6078
+ // delta holds the value at the member's own offset when Δ=0.
6079
+ const rawDeltaMm = s - pg.startScalar;
6080
+ const val = pg.base + (e.shiftKey ? rawDeltaMm : snapToStep(rawDeltaMm, POS_SNAP_MM));
6081
+ pg.newVal = val;
6082
+ { const O = st.anchor, ax = pg.axis === 'depth' ? st.zAxis : st.yAxis; // leader to the drag point on this axis
6083
+ updatePositionLeader([O[0] + ax[0] * s, O[1] + ax[1] * s, O[2] + ax[2] * s]); }
6084
+ if (mesh && pg.meshPos0) { // exact live preview: the SAME swing the bake uses (positionSwingDelta), so the steel never jumps on release
6085
+ const w = positionSwingDelta({ y: st.yAxis, z: st.zAxis }, pg.axis, val - pg.base, st.rot || 0);
6086
+ mesh.position.set(pg.meshPos0.x + w[0], pg.meshPos0.y + w[1], pg.meshPos0.z + w[2]);
6087
+ }
6088
+ const shownVal = api && api.fmtLen ? api.fmtLen(val) : Math.round(val) + ' mm';
6089
+ positionGizmoReadout(e, (pg.axis === 'depth' ? 'Depth ' : 'Width ') + shownVal, ''); // label-first + panel's own unit (fmtLen), to match the Inspect panel exactly
6090
+ }
6091
+ /*
6092
+ * The reference-line gestures (slice 3b.1). These move the member's WORK POINTS, so the live preview is a
6093
+ * RIGID transform of the existing mesh — a translation for the slide, one rotation about the anchor for a
6094
+ * swing. Nothing is rebuilt mid-drag, which is also why the view never has to freeze the depth face: a
6095
+ * rigid transform cannot re-derive it. The fold is decided once, at commit, in the editor.
6096
+ *
6097
+ * Every gesture reports a DELTA (mm along the axis, or radians about the frozen axis); `onUp` turns that
6098
+ * into absolute world work points through the same pure helpers the tests exercise.
6099
+ */
6100
+ function onMoveRefLineGizmo(e, pg, st, mesh) {
6101
+ // The member axis going edge-on collapses the slide arrow AND both arc planes at once. Refuse rather than
6102
+ // let mm-per-pixel run away, matching the shipped depth/width refusal word for word.
6103
+ const scr = positionGizmoHandlesScreen();
6104
+ if (scr && scr.anchor && scr.slideTip && !scr.slideTip.behind
6105
+ && Math.hypot(scr.slideTip.x - scr.anchor.x, scr.slideTip.y - scr.anchor.y) < POS_EDGE_ON_PX) {
6106
+ positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return;
6107
+ }
6108
+ if (pg.axis === 'slide') {
6109
+ const s = posGizmoAxisScalar(e, st, st.xAxis);
6110
+ if (s == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6111
+ if (pg.startScalar == null) { pg.startScalar = s; return; } // grab was edge-on → set the reference on the first valid hit
6112
+ const raw = s - pg.startScalar;
6113
+ const delta = e.shiftKey ? raw : snapToStep(raw, POS_SNAP_MM);
6114
+ pg.newVal = delta;
6115
+ if (mesh && pg.meshPos0) {
6116
+ mesh.position.set(pg.meshPos0.x + st.xAxis[0] * delta, pg.meshPos0.y + st.xAxis[1] * delta, pg.meshPos0.z + st.xAxis[2] * delta);
6117
+ }
6118
+ updatePositionLeader([st.anchor[0] + st.xAxis[0] * s, st.anchor[1] + st.xAxis[1] * s, st.anchor[2] + st.xAxis[2] * s]);
6119
+ positionGizmoReadout(e, 'Slide ' + (api && api.fmtLen ? api.fmtLen(delta) : Math.round(delta) + ' mm'), '');
6120
+ return;
6121
+ }
6122
+ // --- swing: rotate the member DIRECTION about the frozen axis, moving only the far work point.
6123
+ const ang = posSwingAngle(e, st, pg.swingAxis, pg.basis);
6124
+ if (ang == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6125
+ if (pg.startScalar == null) { pg.startScalar = ang; pg.prevAng = ang; return; }
6126
+ if (pg.prevAng == null) pg.prevAng = ang;
6127
+ // Accumulate CONTINUOUSLY, as the shipped roll arc does, so crossing the ±180° seam adds an increment
6128
+ // rather than ~2π. Then snap the DELTA (the member's own heading is generically off-grid, so snapping an
6129
+ // absolute would yank the steel to the 5° grid on the very first tick).
6130
+ pg.accumRad += unwrapAngleStep(pg.prevAng, ang); pg.prevAng = ang;
6131
+ let theta = e.shiftKey ? pg.accumRad : snapToStep(pg.accumRad * 180 / Math.PI, POS_SNAP_DEG) * Math.PI / 180;
6132
+ if (pg.barriers) {
6133
+ const c = clampSwingTheta(theta, pg.barriers, e.shiftKey ? 'free' : 'snapped', POS_SNAP_DEG * Math.PI / 180);
6134
+ if (!c) { positionGizmoReadout(e, 'That would swing the member through plumb', ''); return; } // reachable since the clamp began refusing a direction with no legal travel, rather than substituting a wrong-signed limit
6135
+ theta = c.theta; pg.clamped = c.clamped;
6136
+ }
6137
+ pg.newVal = theta;
6138
+ if (mesh && pg.meshPos0 && pg.meshQuat0) { // exact rigid preview: one rotation about the anchor
6139
+ const axis = new THREE.Vector3(pg.swingAxis[0], pg.swingAxis[1], pg.swingAxis[2]).normalize();
6140
+ const q = new THREE.Quaternion().setFromAxisAngle(axis, theta);
6141
+ const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
6142
+ mesh.position.copy(pg.meshPos0.clone().sub(O).applyQuaternion(q).add(O));
6143
+ mesh.quaternion.copy(q.clone().multiply(pg.meshQuat0));
6144
+ }
6145
+ const tip = swingEndpoint(st.anchor, st.end, pg.swingAxis, theta);
6146
+ if (tip) updatePositionLeader(tip);
6147
+ const degRaw = theta * 180 / Math.PI;
6148
+ const deg = e.shiftKey ? (Math.abs(degRaw) < 10 ? degRaw.toFixed(1) : Math.round(degRaw)) : Math.round(degRaw); // Shift is the no-snap mode, so rounding the readout to a whole degree would report a value the commit does not use
6149
+ // "Swing" and "Tilt", never "Rotation" — that label belongs to the roll arc, and reusing it would blur
6150
+ // which of the two red-family handles is live mid-drag.
6151
+ positionGizmoReadout(e, (pg.axis === 'swingPlan' ? 'Swing ' : 'Tilt ') + deg + '°' + (pg.clamped ? ' (limit)' : ''), '');
6152
+ }
5629
6153
  // --- frame manipulator: grab + drag the gizmo's origin (translate) or ring (rotate about Z). Armed only. ---
5630
6154
  const FRAME_RING_R = (1524 * 2 / 2) * 0.8; // ring radius (matches renderFrameGizmo's half*0.8, N=2)
5631
6155
  function frameGizmoOrigin() { return frame3d ? frame3d.origin : [0, 0, 0]; } // Global → true global 0,0,0
5632
6156
  function pickFrameHandle(cx, cy, allowPassive) { // → 'origin' | 'ring' | null (screen-space, like pickClipHandle). allowPassive: hit-test the un-armed (passive) gizmo too, for click-to-re-select.
5633
6157
  if ((!frameMode && !allowPassive) || !overlayScene || workPlane || !canvasEl) return null;
6158
+ if (positionGizmoVisible && !frameMode && !workPlane && posGizmoState) return null; // position gizmo is showing (cheap cached check) → the frame gizmo is not drawn and must not pick (belt-and-braces vs hit-steal)
5634
6159
  camera.updateMatrixWorld();
5635
6160
  const rect = canvasEl.getBoundingClientRect(), px = cx - rect.left, py = cy - rect.top;
5636
6161
  const O = frameGizmoOrigin();
@@ -5772,7 +6297,9 @@ function refPlaneBasis() {
5772
6297
  return { O: frameGizmoOrigin(), u: [1, 0, 0], v: [0, 1, 0], n: [0, 0, 1] }; // Global → horizontal at 0,0,0
5773
6298
  }
5774
6299
  function renderWorkPlane() {
5775
- renderFrameGizmo(); // the axes+origin gizmo always draws (matches the plane; never shadowed)
6300
+ renderPositionGizmo(); // a ◇ Plane hides the position gizmo (currentPositionGizmoState guards workPlane): refresh it FIRST here so setting/clearing a work plane disposes the stale handle + clears posGizmoState (else it stays drawn AND pickable — Codex). Every work-plane setter and fireFrameChange routes through here, so this is the one place both gizmos re-sync.
6301
+ renderFrameGizmo(); // the axes+origin gizmo always draws (matches the plane; never shadowed) — reads the fresh posGizmoState above for the mutual hide
6302
+
5776
6303
  if (api && api.onFrame3dChange) api.onFrame3dChange(frameInfo()); // refresh the Axes chip: "Plane" when a plane is set, back to Local/Global when cleared
5777
6304
  if (wpGroup) { scene.remove(wpGroup); wpGroup.traverse((o) => { if (o.geometry) o.geometry.dispose(); if (o.material) o.material.dispose(); }); wpGroup = null; }
5778
6305
  if (!wpVisible || !scene) return; // "Show plane" off → no reference plane (works at Global too now, not only for a ◇ Plane)
@@ -6308,6 +6835,7 @@ function dimAxisDir(axis) {
6308
6835
 
6309
6836
  function onDown(e) {
6310
6837
  if (readout) { readout.style.display = 'none'; if (readout._coord) readout._coord.style.display = 'none'; } // UCS Stage 2: hide the whole readout chip so a drag never shows a lingering coordinate (or an empty coord-only shell); the drag/next hover re-shows it
6838
+ if (posInteraction === 'typing') return; // the docked numeric HUD is open (camera frozen) → consume the click (start no gesture); the input blurs naturally, and its blur handler closes the HUD + toasts if anything was typed (Fable 5: explicit state, not focus)
6311
6839
  if (e.button === 2) { rightDownXY = [e.clientX, e.clientY]; rightMoved = false; } // arm the click-vs-drag test for the snap menu
6312
6840
  if (e.button !== 0) return; // RIGHT/MIDDLE → OrbitControls (orbit/pan)
6313
6841
  if (wpMode === 'face') { e.stopPropagation(); const r = wpFacePick(e.clientX, e.clientY); if (r) { workPlane = r; wpMode = null; invalidatePointEntry('drift'); canvasEl.style.cursor = 'default'; renderWorkPlane(); reflectWpBar(); updateStatusChip(); if (api && api.toast) api.toast('Working plane set on the face'); } return; } // armed: one face click sets the plane
@@ -6396,6 +6924,20 @@ function onDown(e) {
6396
6924
  updateStatusChip(); return;
6397
6925
  }
6398
6926
  downXY = [e.clientX, e.clientY];
6927
+ // Profile Position gizmo (slice 3a): a handle sits ON the selected member, so grab it before the
6928
+ // ordinary member pick/endpoint grab. Only a live handle (visible + single selection) can be hit.
6929
+ if (positionGizmoVisible && posGizmoState) {
6930
+ let pgh = null; try { pgh = pickPositionGizmoHandle(e.clientX, e.clientY); } catch (err) { console.error('steel-3d: position-gizmo hit-test failed', err); pgh = null; } // match the grid/mesh hit-test logging (no silent swallow)
6931
+ if (pgh) { e.stopPropagation(); controls.enabled = false; startPositionGizmoDrag(pgh, e); if (pending) return; }
6932
+ // The amber anchor is not draggable, but a press on it must not COST the user their selection either.
6933
+ // The dot floats half a section depth above the steel, so a click there usually misses the member mesh
6934
+ // and reaches empty space — which clears the selection and takes the whole gizmo with it. That was
6935
+ // survivable while the dot was silent; now that it explains itself on hover, people click it. So
6936
+ // consume the gesture and stay put, exactly as a filtered grid does. A drag past the tolerance still
6937
+ // becomes a marquee (below), so an 11px dot cannot blanket-block box selection.
6938
+ let onAnchorDown = false; try { onAnchorDown = pickPositionAnchorHover(e.clientX, e.clientY); } catch (err) { console.error('steel-3d: position-anchor hit-test failed', err); onAnchorDown = false; }
6939
+ if (onAnchorDown) { e.stopPropagation(); controls.enabled = false; pending = { posAnchor: true }; return; }
6940
+ }
6399
6941
  let id = null; try { id = pickAt(e.clientX, e.clientY); } catch { id = null; }
6400
6942
  // Geometry-edit mode (Trim/Extend or Split armed in the inspector): a click does the edit, no drag.
6401
6943
  if (geoMode() && (geoMode() === 'el' ? selIds.size >= 1 : selIds.size === 1)) { e.stopPropagation(); pending = { geo: geoMode(), selId: [...selIds][0], targetId: id }; return; } // Split: single; Extend/Trim: any selection
@@ -6662,8 +7204,9 @@ function onMove(e) {
6662
7204
  if (boxSel) { onBoxMove(e); return; }
6663
7205
  if (pending && pending.clipDrag) { onMoveClip(e); return; } // dragging a clip handle (plane offset / box face)
6664
7206
  if (pending && pending.frameDrag) { onMoveFrame(e); return; } // dragging the local-frame origin / rotation ring
7207
+ if (pending && pending.posGizmo) { onMovePositionGizmo(e); return; } // dragging a Profile Position handle (depth/width offset or roll)
6665
7208
  if (!pending || pending.geo) return;
6666
- if (pending.gridId||pending.filteredGrid||pending.filteredReference) { const d=Math.hypot(e.clientX-downXY[0],e.clientY-downXY[1]);if(d<=DRAG_TOL_PX)return;pending=null;controls.enabled=true;boxSel={x:downXY[0],y:downXY[1]};onBoxMove(e);return; } // a filtered-reference/grid click stays inert, but once it moves the same press becomes a normal marquee so an overlay cannot blanket-disable box selection
7209
+ if (pending.gridId||pending.filteredGrid||pending.filteredReference||pending.posAnchor) { const d=Math.hypot(e.clientX-downXY[0],e.clientY-downXY[1]);if(d<=DRAG_TOL_PX)return;pending=null;controls.enabled=true;boxSel={x:downXY[0],y:downXY[1]};onBoxMove(e);return; } // a filtered-reference/grid click stays inert, but once it moves the same press becomes a normal marquee so an overlay cannot blanket-disable box selection
6667
7210
  if (pending.epDrag) { onMoveEndpoint(e); return; }
6668
7211
  if (!pending.grab || !pending.origMm) return;
6669
7212
  if (!dragging && Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]) <= DRAG_TOL_PX) return;
@@ -6798,6 +7341,7 @@ function connsInRect(x0, y0, x1, y1, windowMode) {
6798
7341
 
6799
7342
  function onUp(e) {
6800
7343
  if (e.button === 2) rightDownXY = null; // end the click-vs-drag test (rightMoved keeps the verdict for the contextmenu that follows)
7344
+ if (posInteraction === 'typing') return; // the docked numeric HUD is open (camera frozen). onUp unconditionally re-enables OrbitControls below; a pointerup while typing (e.g. clicking into the input) must NOT thaw the freeze — else a wheel would drift the anchor the HUD is pinned to. There is no gesture to finish here (pending is null). Mirrors onDown's typing guard.
6801
7345
  // A live drag-out ends here: released outside our window → send; anywhere inside → silently
6802
7346
  // nothing, which is the escape hatch. A press that never travelled was a click, so it falls
6803
7347
  // through and still toggles the member in the selection, exactly as it always has.
@@ -6846,10 +7390,54 @@ function onUp(e) {
6846
7390
  controls.enabled = true;
6847
7391
  const moved = downXY ? Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]) : Infinity; downXY = null;
6848
7392
  if (!p) return;
6849
- if(p.filteredGrid||p.filteredReference)return;
7393
+ if(p.filteredGrid||p.filteredReference||p.posAnchor)return; // an anchor-dot press is inert BY DESIGN: no drag, and no selection change either
6850
7394
  if(p.gridId){if(moved>DRAG_TOL_PX)return;if(!p.add)resetConnState();if(api&&api.onSelectBatch)api.onSelectBatch({memberIds:[],gridIds:[p.gridId]},p.add);else if(api&&api.onSelectGrid)api.onSelectGrid(p.gridId,p.add);return;}
6851
7395
  if (p.clipDrag) return; // a clip handle drag is applied live during onMoveClip; nothing to commit on up (controls re-enabled above)
6852
7396
  if (p.frameDrag) { if (marker) marker.visible = false; if (readout) readout.style.display = 'none'; tfCandidates = null; dimCandidates3d = null; return; } // local-frame origin/rotation is applied live during onMoveFrame; session-only, nothing to commit — clear the snap marker/readout AND re-null the snap caches (they were rebuilt sans the UCS origin during the drag) so the next Move/Dimension snaps TO the moved origin again (code-review)
7397
+ if (p.posGizmo) { // Profile Position handle → commit the ABSOLUTE new offset/roll through the editor (one undo entry)
7398
+ if (readout) readout.style.display = 'none';
7399
+ hidePositionLeader();
7400
+ posInteraction = 'idle';
7401
+ const pg = p.posGizmo;
7402
+ if (pg.refline) { // slice 3b.1 — the handles that move the WORK POINTS, committed as absolute world mm
7403
+ const st = pg.state;
7404
+ const moved = pg.newVal != null && Math.abs(pg.newVal) > 1e-12;
7405
+ if (wasDragging && moved && api && api.commitMemberEndpoints) {
7406
+ // Rebuild the absolute points from the FROZEN drag-start geometry and the total delta, through the
7407
+ // same pure helpers the unit tests pin — never from whatever the mesh preview happens to show.
7408
+ let spec = null;
7409
+ if (pg.axis === 'slide') {
7410
+ const r = slideEndpoints(st.anchor, st.end, st.xAxis, pg.newVal);
7411
+ if (r) spec = { from: r.from, to: r.to, gesture: 'slide', expect: st.fingerprint };
7412
+ } else {
7413
+ const to = swingEndpoint(st.anchor, st.end, pg.swingAxis, pg.newVal);
7414
+ if (to) spec = { to, gesture: pg.axis, expect: st.fingerprint };
7415
+ }
7416
+ if (!spec) console.warn('steel-3d: a reference-line gesture produced no commit — geometry helper returned null', pg.axis, pg.newVal);
7417
+ // The editor's own refusals toast; a THROW here (a member the world-mm primitive cannot address)
7418
+ // would otherwise escape this pointer handler and strand the moved preview over an unchanged model,
7419
+ // which is precisely the failure the primitive's own comment set out to prevent.
7420
+ let ok = false;
7421
+ try { ok = !!(spec && api.commitMemberEndpoints(pg.id, spec, null)); }
7422
+ catch (err) { console.error('steel-3d: reference-line commit failed', err); ok = false; }
7423
+ if (!ok) { restorePositionGizmoMesh(pg); renderPositionGizmo(); } // refused (stale gesture, unknown elevation, a frame it would break) → put the preview back
7424
+ } else { restorePositionGizmoMesh(pg); renderPositionGizmo(); }
7425
+ return;
7426
+ }
7427
+ // rot is compared by ANGULAR equality (mod 360): a drag that loops the arc back to the member's own roll
7428
+ // (Δ = 360°) reads as no move and must commit nothing / push no undo entry (Fable 5 test 1). depth/width
7429
+ // stay a linear compare.
7430
+ const moved = pg.axis === 'rot'
7431
+ ? Math.abs((((pg.newVal - pg.base) % 360) + 540) % 360 - 180) > 1e-6 // shortest angular distance (deg) from base
7432
+ : Math.abs(pg.newVal - pg.base) > 1e-9;
7433
+ if (wasDragging && pg.newVal != null && moved && api && api.commitMemberPosition) {
7434
+ const key = pg.axis === 'depth' ? 'positionOffset' : pg.axis === 'width' ? 'positionHOffset' : 'rot';
7435
+ const val = pg.axis === 'rot' ? rollCommitNorm(pg.newVal) : pg.newVal; // fold the accumulated/off-grid roll to the panel's stored convention
7436
+ const ok = api.commitMemberPosition(pg.id, { [key]: val }, null); // editor's edit() rebuilds → renderPositionGizmo re-anchors
7437
+ if (!ok) { restorePositionGizmoMesh(pg); renderPositionGizmo(); } // refused (e.g. frame drifted) → snap the live preview back
7438
+ } else { restorePositionGizmoMesh(pg); renderPositionGizmo(); } // no net move or a plain click → restore the preview
7439
+ return;
7440
+ }
6853
7441
  if (p.epDrag) { // end-node drag → write just that endpoint's wp; a click (no drag) just selects the member
6854
7442
  if (wasDragging && p.newPt && api && api.onMoveEndpoint) { if (api.onSelect) api.onSelect(p.id, false); api.onMoveEndpoint(p.id, p.end, planPointToWp(p.newPt, p.ppf)); }
6855
7443
  else if (api && api.onSelect) api.onSelect(p.id, false);
@@ -7018,6 +7606,22 @@ function onHoverMove(e) {
7018
7606
  canvasEl.style.cursor = fh ? 'grab' : 'crosshair';
7019
7607
  return;
7020
7608
  }
7609
+ // Profile Position handle hover (toggle on, single selection, frame not armed): grab cursor + a themed
7610
+ // tooltip. Mirrors onDown precedence (the handle sits ON the member and wins over the passive frame origin).
7611
+ if (positionGizmoVisible && posGizmoState && !frameMode && posInteraction !== 'typing') {
7612
+ let ph = null; try { ph = pickPositionGizmoHandle(lastHoverXY[0], lastHoverXY[1]); } catch { ph = null; }
7613
+ if (ph) { canvasEl.style.cursor = 'grab';
7614
+ if (api && api.showHandleTip) api.showHandleTip(POS_HANDLE_TIP[ph], lastHoverXY[0], lastHoverXY[1]);
7615
+ posHovered = true; return; }
7616
+ // The anchor is hover-only: it explains itself but never arms a drag, so it is checked here and NOT
7617
+ // in pickPositionGizmoHandle. Cursor stays default — a grab cursor would promise a drag that a
7618
+ // mousedown here does not perform (it falls through to click-select, as it always has).
7619
+ let onAnchor = false; try { onAnchor = pickPositionAnchorHover(lastHoverXY[0], lastHoverXY[1]); } catch { onAnchor = false; }
7620
+ if (onAnchor) {
7621
+ if (api && api.showHandleTip) api.showHandleTip(POS_HANDLE_TIP.anchor, lastHoverXY[0], lastHoverXY[1]);
7622
+ posHovered = true; return; }
7623
+ if (posHovered) { posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); }
7624
+ } else if (posHovered) { posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); } // gizmo disappeared while a tip was up
7021
7625
  if (frame3d && !frameMode && !geoMode() && !cmActive() && !addActive() && !dimMode3d && !clipMode && !wpMode && !basePickCol && !insertMode && !refMeasure3d && !selectedClipIds.size) { // hovering the PASSIVE gizmo (nothing armed) → pointer cursor hints "click to edit the local axes again"
7022
7626
  let fh = null; try { fh = pickFrameHandle(lastHoverXY[0], lastHoverXY[1], true); } catch { fh = null; }
7023
7627
  if (fh) { canvasEl.style.cursor = 'pointer'; return; }
@@ -7289,7 +7893,7 @@ function dispose() {
7289
7893
  clearRoot();
7290
7894
  if (workAreaHelper) { if (overlayScene) overlayScene.remove(workAreaHelper); workAreaHelper.geometry.dispose(); workAreaHelper.material.dispose(); workAreaHelper = null; }
7291
7895
  if (wpGroup) { if (scene) scene.remove(wpGroup); wpGroup.traverse((o) => { if (o.geometry) o.geometry.dispose(); if (o.material) o.material.dispose(); }); wpGroup = null; } // the reference plane can exist by default now → dispose it too (code-review)
7292
- clearConnEnvelope(); clearClipGizmo(); setClipPreview(null); setClipPlanePreview(null); disposeFramePreview(); disposeFrameGizmo(); overlayScene = null; // dispose the clip/frame gizmo/preview THREE resources before dropping the scene (Codex)
7896
+ clearConnEnvelope(); clearClipGizmo(); setClipPreview(null); setClipPlanePreview(null); disposeFramePreview(); disposeFrameGizmo(); disposePositionGizmo(); disposePositionLeader(); overlayScene = null; // dispose the clip/frame/position gizmo + leader + preview THREE resources before dropping the scene (Codex)
7293
7897
  clips = []; workArea = null; clipMode = null; selectedClipIds.clear(); clipBoxDraft = null; // clips live on the renderer; drop them with the renderer
7294
7898
  if (renderer) renderer.dispose();
7295
7899
  renderer = scene = camera = perspCam = orthoCam = controls = root = api = canvasEl = ro = null; built = false;
@@ -7528,6 +8132,7 @@ window.Steel3DView = {
7528
8132
  workAreaSetAll, workAreaFromSelection, workAreaToggle, workAreaSetWhole, clearWorkArea, workAreaState,
7529
8133
  armWorkPlanePick, setWorkPlanePrincipal, clearWorkPlane, toggleWorkPlaneVisible, workPlaneInfo,
7530
8134
  armFrame3d, disarmFrame3d, repickFrame3d, setFrame3d, setFrameBasis, setFrameAngle, setFrameOrigin, clearFrame3d, frameInfo, positionAuthoringBasis: positionAuthoringBasisSnapshot, onPositionAuthoringBasisChange, frameArmed: () => frameMode, framePicking, framePickStep, frameHandlesScreen, // 3D local drawing frame (UCS stage 1)
8135
+ setPositionGizmoVisible, positionGizmoHandlesScreen, memberWorldTransform, setPositionTyping, positionLeaderVisible, frameGizmoVisible, // Profile Position gizmo (slice 3a/3b): ⋯ Display toggle + E2E grab-point + world-transform/leader/frame-gizmo probes + typed-HUD camera freeze
7531
8136
  coordReadout: () => { if (!readout || !readout._coord || readout.style.display === 'none' || readout._coord.style.display === 'none') return null; return { local: readout._coord.classList.contains('ro-local'), values: readout._coordV.map((v) => v.textContent), labels: readout._coordL.map((l) => l.textContent.trim()), text: readout._coord.textContent }; }, // UCS stage 2 test probe: the live local-coordinate row (null when hidden)
7532
8137
  cmEscape, cmHasBase, cmClear3d, setCmAxis, cmLastClient, cmHudApply,
7533
8138
  drHudApply, pointEntryBegin, pointEntryEnd, drHasStart: () => !!drDraft, // UCS stage 3: shared typed point-entry HUD (Move/Copy + Add)