@floless/app 0.134.0 → 0.134.2

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, positionSwingDelta, snapToStep, rollCommitNorm, unwrapAngleStep, POSITION_OFFSET_SNAP_MM, POSITION_ROT_SNAP_DEG, 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, translateEndpoints, livePositionState, 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';
@@ -38,6 +38,7 @@ let epRing = null, epPreview = null, epMovedLine = null; // white ring on
38
38
  let hoverEp = null, dragEp = null; // {id,end} of the hovered / dragged end node
39
39
  let refGroup = null; let refLineOn = false; // optional reference (work) lines between each member's end points
40
40
  let insertMode = false; // armed "place a vectored detail" pick (mirrors clipMode)
41
+ let connPick = null; // armed "name the members this connection joins" pick — {jointId, chosen:Set<id>}
41
42
  let insertPending = null; // {name,url} — the detail the editor queued for the next placement click
42
43
  let basePickCol = null; // Mode B: armed "trim column to base" pick — the target column id, or null
43
44
  let basePickLevels = null; // [{ z, label }] level datums the base pick snaps its elevation to
@@ -89,6 +90,12 @@ const baseMat = new Map(); // group key -> MeshStandardMaterial (shar
89
90
  const SELECT_EMISSIVE = 0x3b82f6; // --brand: selected members glow blue
90
91
  const HOVER_EMISSIVE = 0x38bdf8; // sky: a cooler, lighter hue than the selection blue — paired with a softer glow (HOVER_INTENSITY) so hover reads distinct from selection
91
92
  const HOVER_INTENSITY = 0.3; // hover glow strength (softer than the 0.6 selection glow)
93
+ /* The amber lift for a connection whose steel moved underneath it — `--warn` (#fbbf24) straight from the
94
+ locked palette, so no new hue enters the editor for this. Far from BOTH the selection blue and the sky
95
+ hover in hue, and pitched between them in strength: it must never be mistaken for "I clicked this".
96
+ Declared beside them because it is read by the Wire outline long before the material helpers below. */
97
+ const REVIEW_EMISSIVE = 0xfbbf24;
98
+ const REVIEW_INTENSITY = 0.45;
92
99
  const EP_START = 0xfacc15; // start endpoint (end 1) — yellow
93
100
  const EP_END = 0xf472b6; // end endpoint (end 2) — magenta
94
101
 
@@ -346,13 +353,21 @@ function init(canvas, theApi) {
346
353
  window.addEventListener('pointerup', onUp);
347
354
  canvas.addEventListener('pointermove', onHoverMove); // canvas-only: cursor + hover readout when idle
348
355
  canvas.addEventListener('pointerenter', () => { pointerOverCanvas = true; });
349
- canvas.addEventListener('pointerleave', () => { pointerOverCanvas = false; hoverEp = null; if (hoverRAF) { cancelAnimationFrame(hoverRAF); hoverRAF = 0; } setHover(null); setClipPlanePreview(null); if (clipMode && marker) marker.visible = false; updateStatusChip(); }); // leaving the canvas clears the hover glow + chip + clip-plane ghost + a clip snap reticle; cancel any queued hover frame so it can't re-glow the last member after the cursor left
356
+ canvas.addEventListener('pointerleave', () => { pointerOverCanvas = false; hoverEp = null; if (hoverRAF) { cancelAnimationFrame(hoverRAF); hoverRAF = 0; } setHover(null); if (posInteraction !== 'dragging') { setPositionHover(null); if (posHovered) { posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); } } // ...and the position handle's own highlight + tooltip. The hover state only ever cleared by moving to another point ON the canvas, so a pointer that left sideways left a handle amber behind it. Not while dragging: a drag legitimately continues past the canvas edge (pointer capture), and the active handle must stay lit.
357
+ setClipPlanePreview(null); if (clipMode && marker) marker.visible = false; updateStatusChip(); }); // leaving the canvas clears the hover glow + chip + clip-plane ghost + a clip snap reticle; cancel any queued hover frame so it can't re-glow the last member after the cursor left
350
358
  canvas.addEventListener('dblclick', onDblClick); // "zoom to detail": dbl-click a part zooms to it (empty = no-op)
351
359
  // The OS took the pointer away mid-gesture: no pointerup will follow, so onUp's cleanup never runs.
352
360
  // Clear the half-built press too, or orbit stays disabled until some later interaction repairs it.
353
361
  canvas.addEventListener('pointercancel', () => {
354
- if (!teklaDrag) return;
355
- endTeklaDrag();
362
+ // A position gesture has MORE to unwind than a Tekla drag-out — the live drawing state, the amber
363
+ // active handle, the grabbing cursor — and a cancelled pointer sends no pointerup, so onUp never runs.
364
+ // Returning early here (as this handler used to for anything but a drag-out) left the gizmo stuck
365
+ // amber over a half-moved preview with orbit disabled, and nothing but another gesture could repair it.
366
+ if (pending && pending.posGizmo) restorePositionGizmoMesh(pending.posGizmo);
367
+ const hadPos = !!(pending && pending.posGizmo) || posInteraction === 'dragging';
368
+ if (hadPos) { endPositionGesture(); hidePositionLeader(); if (readout) readout.style.display = 'none'; renderPositionGizmo(); }
369
+ if (teklaDrag) endTeklaDrag();
370
+ else if (!hadPos) return;
356
371
  pending = dragging = null; downXY = null; if (controls) controls.enabled = true;
357
372
  });
358
373
  window.addEventListener('keydown', onKey); // Tekla keyboard nav: arrows pan, Ctrl/Shift+arrows rotate
@@ -427,6 +442,10 @@ function loop() {
427
442
  sizeEndpoints();
428
443
  sizeClipHandles();
429
444
  sizeFrameHandle();
445
+ // A gesture in flight rebuilds the position gizmo from its live state — here, ONCE per frame, so a 200 Hz
446
+ // pointer cannot rebuild faster than the display draws. It must run BEFORE the sizing pass, so a group
447
+ // built this frame is scaled before it is rendered rather than appearing at unit size for one frame.
448
+ syncPositionGizmoLive();
430
449
  sizePositionGizmo();
431
450
  sizeGridLabels();
432
451
  positionDimLabels();
@@ -855,6 +874,7 @@ function clearRoot() {
855
874
  m.geometry.dispose();
856
875
  if (m.userData._selMat) m.userData._selMat.dispose(); // per-mesh selection clone (else it leaks per rebuild)
857
876
  if (m.userData._hovMat) m.userData._hovMat.dispose(); // per-mesh hover clone — same leak-per-rebuild story as _selMat
877
+ if (m.userData._revMat) m.userData._revMat.dispose(); // per-mesh review (amber) clone — likewise, and a review lift survives many rebuilds
858
878
  // A placed detail (Slice 4) owns a per-mesh MeshBasicMaterial + its image texture (NOT a shared baseMat);
859
879
  // dispose both or every rebuild — which happens on each edit — leaks the old material + GPU texture.
860
880
  if (String(id).startsWith('det:') && m.material) { if (m.material.map) m.material.map.dispose(); m.material.dispose(); }
@@ -956,6 +976,10 @@ function buildFromScene(sc) {
956
976
  mesh.userData.axis = lengthAxisOf(el); // …and so does the axis, or a clone rebuilds a world-projected shader
957
977
  mesh.userData.derived = !!(el.kind && el.kind !== 'box'); // connection parts: rendered, not member-editable
958
978
  mesh.userData.conn = el.conn || null; mesh.userData.connKind = el.connKind || null; // Connection Component membership (Slice A) — the whole-select/drill handle
979
+ // The connection review state the SERVER derived, stamped per part and ABSENT when the connection is
980
+ // clean (server/steel-joints.ts). Absent is the honest encoding of "nothing to say" — a field on every
981
+ // part would make the common case pay for the rare one.
982
+ mesh.userData.connReview = (el.meta && el.meta.connReview) || null;
959
983
  mesh.receiveShadow = true; // steel catches shadow from steel; casting is decided per-pass in applyDisplayMode
960
984
  root.add(mesh); meshById.set(el.id, mesh);
961
985
  box.expandByObject(mesh);
@@ -2799,11 +2823,71 @@ function setInsertMode(on, pending) {
2799
2823
  }
2800
2824
  function insertModeOn() { return insertMode; }
2801
2825
 
2826
+ /* Arm the member pick that follows a custom connection's placement (connection review, design §5.1).
2827
+ The user NAMES the members — nothing here infers them from geometry, which is the whole point of
2828
+ the step. `chosen` seeds from the member the placement click snapped to, so the common single-member
2829
+ case is already correct and the pick is a confirmation rather than a chore.
2830
+ Selection doubles as the highlight: member-end review already drives the selection the same way, so
2831
+ the chosen members light up through the existing material path with no second highlight mechanism. */
2832
+ let armingConnPick = false;
2833
+ function setConnMemberPick(state) {
2834
+ connPick = state ? { jointId: String(state.jointId || ''), chosen: new Set(state.chosen || []) } : null;
2835
+ /* Deliberately NOT setInsertMode(false): a sticky favourite stays armed UNDERNEATH this pick so the
2836
+ next placement can follow immediately, which is the whole premise of the Enter/Esc ordering below.
2837
+ Disarming here cleared the favourite through onInsertModeChange and silently ended repeat placement.
2838
+ The pick's own pointerdown branch runs BEFORE insertMode's, so an armed insert underneath is inert;
2839
+ a one-shot (IFC import) placement has already disarmed itself by this point. */
2840
+ // Guarded: those disarm calls are no-ops for the abandon hooks (which fire only when a rival is being
2841
+ // ARMED), and this flag keeps that true even if one of them changes direction later.
2842
+ armingConnPick = true;
2843
+ try { if (connPick) { setClipMode(null); setBasePickMode(null); if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); } }
2844
+ finally { armingConnPick = false; }
2845
+ // A sticky favourite stays armed underneath, so the crosshair must survive the pick ending.
2846
+ if (canvasEl) canvasEl.style.cursor = (connPick || insertMode) ? 'crosshair' : 'default';
2847
+ if (connPick) syncConnPickSelection();
2848
+ updateStatusChip(); notifyInstructor();
2849
+ }
2850
+ function connMemberPickOn() { return connPick ? [...connPick.chosen] : null; }
2851
+ /* WHOSE pick is armed. `connMemberPickOn` answers with the chosen ids and can never say that, so a
2852
+ caller waiting on ONE joint's pick could not tell it from a different joint's. The editor's
2853
+ re-placement watchdog needs exactly this distinction. (Found by review.) */
2854
+ function connMemberPickJoint() { return connPick ? connPick.jointId : null; }
2855
+ /* Leaving the pick without answering it. Enter and Esc arrive through onKey, which returns early when
2856
+ focus is in a field, the canvas is hidden (2D), or this pane is inactive (split view) — all ordinary
2857
+ user actions. Without an explicit abandon the pick stays armed forever, and because the editor
2858
+ suppresses the "may need review" clause for the joint being picked, the ONE connection provably not
2859
+ being watched would be the one whose warning is silenced. Abandoning records nothing: the ordinary
2860
+ save already lands the joint `untracked`, which is the truth. */
2861
+ function abandonConnPick(reason) {
2862
+ if (!connPick || armingConnPick) return;
2863
+ const jointId = connPick.jointId;
2864
+ setConnMemberPick(null);
2865
+ if (api && api.onConnMemberPickAbandon) api.onConnMemberPickAbandon(jointId, reason);
2866
+ }
2867
+ /* The chosen set IS the selection while the pick is armed, so the 3D shows exactly what gets recorded. */
2868
+ function syncConnPickSelection() {
2869
+ if (!connPick) return;
2870
+ setSelection(new Set(connPick.chosen)); // setSelection repaints (materials + endpoints) and the view loop draws it
2871
+ }
2872
+ /* Toggle one member into / out of the set. Connection parts (`joint:part`) and details (`det:…`) are
2873
+ not members and are refused by name rather than silently ignored, so a mis-click is explainable. */
2874
+ function connPickToggle(id) {
2875
+ if (!connPick) return;
2876
+ const mid = String(id || '');
2877
+ if (!mid) return; // clicked empty space or the working plane — a miss, not a mistake worth narrating
2878
+ if (mid.includes(':')) { if (api && api.toast) api.toast('Click a MEMBER — that is part of a connection, not steel it joins'); return; }
2879
+ if (connPick.chosen.has(mid)) connPick.chosen.delete(mid); else connPick.chosen.add(mid);
2880
+ syncConnPickSelection();
2881
+ if (api && api.onConnMemberPickChange) api.onConnMemberPickChange([...connPick.chosen]);
2882
+ updateStatusChip(); notifyInstructor();
2883
+ }
2884
+
2802
2885
  // Mode B: arm a "trim column to base" pick on `colId`. The level datums are derived from the OTHER members'
2803
2886
  // rendered top/bottom (world mm, so no display→mm conversion), each labelled by its member mark, so the pick
2804
2887
  // snaps the base to a real framing level. A one-shot left-click hands the picked base elevation to the editor
2805
2888
  // via api.onBasePick. Mirrors setInsertMode.
2806
2889
  function setBasePickMode(colId) {
2890
+ abandonConnPick('other-tool'); // every other mode disarms its rivals; without this the pick keeps swallowing clicks while another tool reports armed
2807
2891
  if (colId) { dropGridLinePick3d(); dropRefMeasure3d(); }
2808
2892
  basePickCol = colId || null;
2809
2893
  basePickLevels = null;
@@ -3592,6 +3676,10 @@ const wireEdges = new Map(); // meshId -> LineSegments (edge
3592
3676
  function wireEdgeColorOf(id, mesh) {
3593
3677
  if (selIds.has(id)) return SELECT_EMISSIVE; // selected → brand-blue outline
3594
3678
  if (hoverGlowIds.includes(id)) return HOVER_EMISSIVE; // hovered → sky outline (matches Solid/X-ray)
3679
+ /* Wire hides the solid fill entirely and the OUTLINE carries the shape, so emissive is ignored here —
3680
+ the amber lift has to be re-stated as a line colour or it silently vanishes in a display mode the
3681
+ user can be sitting in. Same precedence as Solid: selection and hover still out-rank it. */
3682
+ if (mesh.userData && mesh.userData.connReview === 'needs-review') return REVIEW_EMISSIVE;
3595
3683
  const c = mesh.material && mesh.material.color; return c ? c.getHex() : WIRE_EDGE_FALLBACK;
3596
3684
  }
3597
3685
  function wireEdgeMatFor(hex) { let m = wireEdgeMats.get(hex); if (!m) { m = new THREE.LineBasicMaterial({ color: hex }); wireEdgeMats.set(hex, m); } return m; }
@@ -3773,6 +3861,7 @@ function rebuildClipPlanes(c) { // recompute a clip's .planes from its ed
3773
3861
  c.planes = c.kind === 'box' ? boxToPlanes(c.box) : [new THREE.Plane().setFromNormalAndCoplanarPoint(c.n, c.point)];
3774
3862
  }
3775
3863
  function setClipMode(m) { // arm/disarm a clip pick: 'plane' (click a face) | 'box' (draw 2 corners) | null
3864
+ abandonConnPick('other-tool'); // every other mode disarms its rivals; without this the pick keeps swallowing clicks while another tool reports armed
3776
3865
  if (m) { dropGridLinePick3d(); dropRefMeasure3d(); }
3777
3866
  if (m && dimMode3d) toggleDimTool();
3778
3867
  if (m) { if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); cmClear3d(); drClear3d(); disarmFrame3d(); } // clip shares the left-click — disarm Move/Copy + Add + the local frame so their picks don't steal it (onDown routes them first)
@@ -4368,11 +4457,11 @@ function onKey(e) {
4368
4457
  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
4369
4458
  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
4370
4459
  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
4460
+ if (pending && pending.posGizmo && e.key === 'Escape') { // Esc mid-drag → cancel a Profile Position edit; put the live-previewed steel back, no commit — and drop the live gizmo state with it (endPositionGesture, via renderPositionGizmo below)
4372
4461
  e.preventDefault();
4373
4462
  restorePositionGizmoMesh(pending.posGizmo);
4374
4463
  pending = dragging = null;
4375
- posInteraction = 'idle'; hidePositionLeader();
4464
+ endPositionGesture(); hidePositionLeader();
4376
4465
  if (controls) controls.enabled = true;
4377
4466
  if (readout) readout.style.display = 'none';
4378
4467
  renderPositionGizmo();
@@ -4393,6 +4482,18 @@ function onKey(e) {
4393
4482
  // Cancelling here first would make its handler fall through to setGridMode(false) and close the panel too — one Esc
4394
4483
  // doing two things.
4395
4484
  if (wpMode && e.key === 'Escape') { e.preventDefault(); if (wpMode === '3pt' && wpDraft && wpDraft.length) { wpDraft.pop(); updateStatusChip(); } else { wpMode = null; wpDraft = null; marker.visible = false; canvasEl.style.cursor = 'default'; reflectWpBar(); updateStatusChip(); } return; } // Esc steps a 3pt pick back, else disarms the set-plane mode
4485
+ /* The member pick owns Enter and Esc while it is armed, and is tested BEFORE insertMode because a
4486
+ sticky favourite leaves insert armed underneath — otherwise Esc would disarm the placement tool
4487
+ and never reach the pick, losing the connection's baseline in silence. Esc SKIPS (commits with no
4488
+ members named); it does not cancel, because the geometry is already placed by this point. */
4489
+ if (connPick && (e.key === 'Enter' || e.key === 'Escape')) {
4490
+ e.preventDefault();
4491
+ const chosen = e.key === 'Enter' ? [...connPick.chosen] : [];
4492
+ const jointId = connPick.jointId, skipped = e.key === 'Escape';
4493
+ setConnMemberPick(null);
4494
+ if (api && api.onConnMemberPickCommit) api.onConnMemberPickCommit(jointId, chosen, skipped);
4495
+ return;
4496
+ }
4396
4497
  if (insertMode && e.key === 'Escape') { e.preventDefault(); setInsertMode(false); if (api && api.toast) api.toast('Insert cancelled'); return; } // Esc disarms the detail-placement pick
4397
4498
  if (basePickCol && e.key === 'Escape') { e.preventDefault(); setBasePickMode(null); if (api && api.toast) api.toast('Trim cancelled'); return; } // Esc disarms the Mode B column-base pick
4398
4499
  if (clipMode && e.key === 'Escape') { e.preventDefault(); if (clipMode === 'box' && clipBoxDraft) { if (clipBoxDraft.b) clipBoxDraft.b = null; else clipBoxDraft = null; setClipPreview(null); if (marker) marker.visible = false; updateStatusChip(); } else setClipMode(null); return; } // Esc steps back: height→footprint→cancel, else disarms the pick
@@ -4425,6 +4526,7 @@ function onKey(e) {
4425
4526
  }
4426
4527
  // ---- 3D dimension tool controls (driven from the toolbar + the keyboard) ----
4427
4528
  function toggleDimTool() {
4529
+ abandonConnPick('other-tool'); // every other mode disarms its rivals; without this the pick keeps swallowing clicks while another tool reports armed
4428
4530
  // ARMING is refused when the host says the model is read-only (unit 5, P7d). Disabling the #m3dDim
4429
4531
  // BUTTON is not enough and that was measured, not assumed: the tool also arms from a bare `d` keydown
4430
4532
  // on this view, and a DOM `disabled` only suppresses that button's own click — it says nothing about an
@@ -4665,14 +4767,19 @@ function onDblClick(e) {
4665
4767
  // lingering `pending` here upholds the one-editable-gizmo invariant before the HUD opens. This wins over the
4666
4768
  // zoom-to-part below, which only runs past this guard.
4667
4769
  if (positionGizmoVisible && posGizmoState && !frameMode) {
4770
+ // `pickPositionGizmoHandle` itself refuses while a drag is in flight (the drawn handles are tracking
4771
+ // the member and the cached geometry is not), so this cannot open typed entry against one set of
4772
+ // coordinates while the user is looking at another.
4668
4773
  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
4774
  if (ph && ph !== 'anchor') {
4670
4775
  e.preventDefault(); e.stopPropagation();
4671
4776
  if (pending && pending.posGizmo) restorePositionGizmoMesh(pending.posGizmo);
4672
- pending = dragging = null; posInteraction = 'idle'; hidePositionLeader();
4777
+ pending = dragging = null; endPositionGesture(); hidePositionLeader();
4673
4778
  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
4779
  const scr = positionGizmoHandlesScreen();
4675
- const p = scr && (ph === 'depth' ? scr.depthTip : ph === 'width' ? scr.widthTip : scr.rotHandle);
4780
+ const p = scr && (ph === 'depth' ? scr.depthTip : ph === 'width' ? scr.widthTip
4781
+ : ph === 'slide' ? scr.slideTip : ph === 'swingPlan' ? scr.swingPlanHandle
4782
+ : ph === 'swingElev' ? scr.swingElevHandle : scr.rotHandle);
4676
4783
  if (p && api && api.openPositionHud) api.openPositionHud([...selIds][0], ph, [p.x, p.y]);
4677
4784
  return;
4678
4785
  }
@@ -4712,9 +4819,11 @@ function setSelection(ids) {
4712
4819
  if (String(id).startsWith('det:')) { if (mesh.material && mesh.material.color) mesh.material.color.setHex(on ? 0x93c5fd : 0xffffff); continue; }
4713
4820
  // Selected → a per-mesh clone that glows (so one selected member doesn't tint its whole profile
4714
4821
  // group). Deselected → back to the SHARED profile material (its real colour).
4715
- mesh.material = on ? selectedMaterial(mesh) : materialFor(mesh.userData.group, mesh.userData.family, mesh.userData.axis);
4716
- mesh.material.emissive = new THREE.Color(on ? SELECT_EMISSIVE : 0x000000);
4717
- mesh.material.emissiveIntensity = on ? 0.6 : 0;
4822
+ // Deselecting returns to the RESTING material, which is amber when this part's connection is asking
4823
+ // for review — not unconditionally back to plain steel, which would erase the lift on the first click.
4824
+ mesh.material = on ? selectedMaterial(mesh) : restingMaterial(mesh);
4825
+ if (on) { mesh.material.emissive = new THREE.Color(SELECT_EMISSIVE); mesh.material.emissiveIntensity = 0.6; }
4826
+ else if (mesh.userData.connReview !== 'needs-review') { mesh.material.emissive = new THREE.Color(0x000000); mesh.material.emissiveIntensity = 0; }
4718
4827
  }
4719
4828
  selIds = new Set(set); // BEFORE applyDisplayMode: in Wire mode wireEdgeColorOf reads selIds to colour the outline, so it must already be current (mirrors the setHover ordering) — else a just-(de)selected outline keeps its old colour until the NEXT applyDisplayMode. The reglow re-sync below only fires when a still-hovered part was deselected, so it does not save the ordinary click-to-select case
4720
4829
  applyDisplayMode(); // selection swapped the materials → re-apply wire/xray
@@ -4735,6 +4844,66 @@ function highlightClone(mesh) {
4735
4844
  if (tile) applyTriplanar(c, tile, DIRECTIONAL.has(mesh.userData.family) ? mesh.userData.axis : null);
4736
4845
  return c;
4737
4846
  }
4847
+ /* A per-mesh clone, cached and DISPOSED alongside _selMat / _hovMat in clearRoot — an uncached one would
4848
+ tint every member sharing the profile material, and an undisposed one leaks on every rebuild. */
4849
+ function reviewMaterial(mesh) {
4850
+ if (!mesh.userData._revMat) {
4851
+ const m = highlightClone(mesh);
4852
+ m.emissive = new THREE.Color(REVIEW_EMISSIVE);
4853
+ m.emissiveIntensity = REVIEW_INTENSITY;
4854
+ mesh.userData._revMat = m;
4855
+ }
4856
+ return mesh.userData._revMat;
4857
+ }
4858
+ /*
4859
+ * THE RESTING material for a part — what it wears when it is neither selected nor hovered.
4860
+ *
4861
+ * This exists because selection and hover REPLACE mesh.material outright (see setSelection/setHoverGlow
4862
+ * below), so anything painted at build time is gone after one select→deselect cycle. Both paths used to
4863
+ * restore the shared profile material directly; they now come here, so a needs-review part returns to
4864
+ * amber rather than to plain steel.
4865
+ *
4866
+ * Precedence overall is selection > hover > needs-review > base. Selection wins because losing track of
4867
+ * what you clicked is worse than briefly losing a warning — and the warning is not actually lost, because
4868
+ * the inspector chip states it for as long as the connection is selected.
4869
+ *
4870
+ * `untracked` gets NOTHING here, deliberately: every pre-existing connection is untracked, and painting a
4871
+ * legacy model amber on open would train people to ignore the colour outright.
4872
+ */
4873
+ function restingMaterial(mesh) {
4874
+ if (mesh.userData.connReview === 'needs-review') return reviewMaterial(mesh);
4875
+ return materialFor(mesh.userData.group, mesh.userData.family, mesh.userData.axis);
4876
+ }
4877
+ /*
4878
+ * Re-state the review lift on an ALREADY-BUILT scene.
4879
+ *
4880
+ * Needed because the review state can move without the geometry moving — a sign-off in another tab, or
4881
+ * the client re-deriving after its own edit — and neither rebuilds the scene. Without this the header
4882
+ * count would update while the parts kept their old colour, which is precisely the two-surfaces-disagree
4883
+ * failure the server goes out of its way to prevent by deriving both from one read.
4884
+ *
4885
+ * `map` is jointId → 'needs-review' | 'untracked'; a joint ABSENT from it is clean. Selection and hover
4886
+ * are deliberately left alone: they own the material while they are on, and the updated `connReview` is
4887
+ * what their fall-back to restingMaterial will read when they release it.
4888
+ */
4889
+ function setConnReview(map) {
4890
+ const next = map instanceof Map ? map : new Map(Object.entries(map || {}));
4891
+ let touched = false;
4892
+ for (const [id, mesh] of meshById) {
4893
+ const conn = mesh.userData && mesh.userData.conn;
4894
+ if (!conn) continue;
4895
+ const want = next.get(conn) || null;
4896
+ if (mesh.userData.connReview === want) continue;
4897
+ mesh.userData.connReview = want;
4898
+ touched = true;
4899
+ if (selIds.has(id) || hoverGlowIds.includes(id)) continue; // they own the material right now
4900
+ mesh.material = restingMaterial(mesh);
4901
+ mesh.material.emissive = new THREE.Color(want === 'needs-review' ? REVIEW_EMISSIVE : 0x000000);
4902
+ mesh.material.emissiveIntensity = want === 'needs-review' ? REVIEW_INTENSITY : 0;
4903
+ }
4904
+ if (touched) applyDisplayMode(); // Wire reads the colour from wireEdgeColorOf, so the outline must re-resolve too
4905
+ return touched;
4906
+ }
4738
4907
  function selectedMaterial(mesh) {
4739
4908
  if (!mesh.userData._selMat) mesh.userData._selMat = highlightClone(mesh);
4740
4909
  return mesh.userData._selMat;
@@ -4751,9 +4920,11 @@ function setHoverGlow(id, on, sync = true) {
4751
4920
  const mesh = meshById.get(id);
4752
4921
  if (!mesh || String(id).startsWith('det:')) return; // placed details use a texture, no emissive to glow
4753
4922
  if (selIds.has(id)) return; // selected beats hovered — don't disturb its blue glow
4754
- mesh.material = on ? hoverMaterial(mesh) : materialFor(mesh.userData.group, mesh.userData.family, mesh.userData.axis);
4755
- mesh.material.emissive = new THREE.Color(on ? HOVER_EMISSIVE : 0x000000);
4756
- mesh.material.emissiveIntensity = on ? HOVER_INTENSITY : 0;
4923
+ // Leaving hover returns to the RESTING material — amber if this connection is asking for review, so a
4924
+ // pointer sweeping across the model does not wipe the lift off everything it touches.
4925
+ mesh.material = on ? hoverMaterial(mesh) : restingMaterial(mesh);
4926
+ if (on) { mesh.material.emissive = new THREE.Color(HOVER_EMISSIVE); mesh.material.emissiveIntensity = HOVER_INTENSITY; }
4927
+ else if (mesh.userData.connReview !== 'needs-review') { mesh.material.emissive = new THREE.Color(0x000000); mesh.material.emissiveIntensity = 0; }
4757
4928
  if (sync) applyDisplayMode(); // ALWAYS re-sync after a material swap (mirrors setSelection): the swapped-in clone may have been cloned in another mode, and on clear the restored shared material can itself be stale — for a sole-profile member it stays detached while its mesh wears _hovMat, so applyDisplayMode never updated it. emissive is preserved (applyDisplayMode never touches it). sync=false lets a whole-connection glow batch ONE applyDisplayMode() after the loop instead of an O(meshes) sweep per part.
4758
4929
  }
4759
4930
  // The ids that glow together when `id` is hovered: the WHOLE connection's parts (so hovering any part
@@ -5669,36 +5840,140 @@ function sizeFrameHandle() {
5669
5840
  }
5670
5841
 
5671
5842
  // ---- Profile Position gizmo (slice 3a) -----------------------------------------------------------
5672
- // A Tekla-shaped handle anchored to the SELECTED member's start work point: a blue depth arrow and a
5673
- // green width arrow drive the numeric offsets, a red arc about the member axis drives the roll. The
5674
- // editor owns the semantics (`api.positionGizmoState` / `api.commitMemberPosition`); the view only
5675
- // draws the arrows and, on a drag, reports an ABSOLUTE new value back. Lives in `overlayScene` (2nd
5843
+ // A Tekla-shaped handle anchored to the SELECTED member's start work point. Three arrows TRANSLATE the
5844
+ // reference line — blue along the section's depth axis, green along its width, red along the member's own
5845
+ // axis — two quarter arcs re-aim it, and a red arc about the member axis rolls the section on it. The
5846
+ // editor owns the semantics (`api.positionGizmoState` / `api.commitMemberEndpoints` / `commitMemberPosition`);
5847
+ // the view only draws the handles and, on a drag, reports an absolute result back. Lives in `overlayScene` (2nd
5676
5848
  // unclipped pass, `depthTest:false`) so a section plane never cuts it, and the whole group is scaled
5677
5849
  // screen-constant like the frame/clip handles — grabbable on a 6" stub and a 40' girder alike.
5678
5850
  let positionGizmo = null; // THREE.Group, built in LOCAL space around the anchor, positioned + scaled per frame
5851
+ let posWorldGroup = null; // child of the above, counter-scaled each frame so its children are in WORLD mm (the committed tie)
5679
5852
  let positionGizmoVisible = false; // the ⋯ Display-menu toggle, pushed in from the editor
5680
- let posGizmoState = null; // last api.positionGizmoState() snapshot for the single selection (anchor, axes, offsets)
5853
+ let posGizmoState = null; // last api.positionGizmoState() snapshot for the single selection — the COMMITTED state, never the in-gesture one
5854
+ /* The state the gizmo is DRAWN from while a gesture is in flight, and the ONLY thing that reads it is the
5855
+ drawing plus the exported E2E probe. It is deliberately NOT `posGizmoState`: three readers take the
5856
+ committed anchor and would break if it moved under them — `updatePositionLeader` anchors the rubber band
5857
+ there (a translate would drag the band's tail along with its head and it would never grow), the two
5858
+ edge-on guards measure the projected axis from it (a live anchor changes that projection in perspective,
5859
+ so a legal drag could stall the instant it crossed 26 px), and the pick/hover paths hit-test it. So the
5860
+ live state lives here, the committed state stays put, and everything that must be frozen still is. */
5861
+ let posLiveState = null;
5862
+ let posLiveDirty = false; // a pointer-move set a new live state; loop() rebuilds ONCE per frame from it
5681
5863
  // Explicit interaction state consulted by every position-gizmo handler (drag/dblclick/keydown), instead of
5682
5864
  // trusting focus + stopPropagation (Fable 5 review): 'idle' | 'dragging' | 'typing'. 'typing' = the docked
5683
5865
  // numeric HUD is open (camera frozen); handlers that must not fire while typing check this and bail.
5684
5866
  let posInteraction = 'idle';
5685
5867
  let posHovered = false; // a position handle is under the cursor (drives the shared-#tooltip hide on leave)
5868
+ let posHoverHandle = null; // WHICH handle — the hovered one turns amber; null while dragging (the active one owns the highlight)
5869
+ let posActiveHandle = null; // the handle currently being dragged
5686
5870
  let positionLeader = null; // cyan #22d3ee rubber-band line: amber anchor → live drag point, shown for a whole drag
5687
- const POS_GIZMO_REACH_PX = 132; // screen-constant arrow reach (spec §3)
5871
+ let positionTie = null; // muted #67e8f9 line: anchor → the offset profile origin, when a committed offset exists
5872
+ /* Scratch vectors for the per-frame sizing pass. It runs on EVERY frame the gizmo is shown, not only during
5873
+ a gesture, so allocating an anchor + two projection vectors there produced continuous garbage for a
5874
+ function whose whole job is to be cheap. Reused rather than pooled: the three are never live at once
5875
+ across a call boundary. */
5876
+ const _posAnchorV = new THREE.Vector3(), _posProjA = new THREE.Vector3(), _posProjB = new THREE.Vector3();
5877
+ const POS_GIZMO_REACH_PX = 132; // screen-constant arrow reach (spec §3) — the CEILING, not a fixed size
5878
+ /* A fixed 132 px is right on a member that fills the view and absurd on one that does not: zoomed out to a
5879
+ whole frame, an 80 px member carried a ~350 px apparatus — over 4x the thing it manipulates, because the
5880
+ arrows, the roll arc AND the swing arcs are all scaled off this one basis and none of them tracks the
5881
+ member. So 132 px becomes a ceiling and the reach follows the member's own on-screen length, floored so
5882
+ it stays grabbable on a 6" stub (spec §3's requirement, which the ceiling alone was standing in for). */
5883
+ const POS_GIZMO_REACH_MIN_PX = 46; // still grabbable, and still bigger than the 26 px edge-on refusal
5884
+ // Head + shaft in LOCAL units (reach = 1.0), read off the mockup's 132 px drawing: 11 x 18 px head, shaft to 0.86.
5885
+ const POS_ARROW_STEM = 0.86, POS_HEAD_R = 11 / 2 / 132, POS_HEAD_H = 18 / 132;
5886
+ const POS_GIZMO_REACH_FRAC = 0.42; // of the member's on-screen length
5887
+ /* THREE RADII, not one. The mockup draws all three quarter arcs at 0.66 — which reads correctly in a
5888
+ fixed 2D drawing and is unusable in a rotatable 3D view, because arcs at the same radius meet wherever
5889
+ their planes share an axis: roll (y->z) and tilt (x->z) both pass through +z, and plan (x->y) and tilt
5890
+ both pass through +x. Screen-space nearest-point picking then resolves those regions arbitrarily, and
5891
+ the E2E caught the consequence — a press on the tilt arc's own midpoint rolled the section instead.
5892
+ Staggering is the mockup's own language for this (its Option B stages 0.58 / 1.12 for the same reason);
5893
+ only the literal 0.66 is being departed from, not the form. */
5894
+ const POS_ARC_R = { rot: 0.58, swingPlan: 0.74, swingElev: 0.90 }; // all inside the 1.0 arrows
5895
+ /* Both swing arcs are drawn from `swingBasis.e1`, which IS the member direction in each of their planes —
5896
+ so at that end they meet at the same point, and the nearest-point pick resolves the first stretch of
5897
+ sweep by `if` ORDER rather than by geometry (swingPlan always won, leaving swingElev ungrabbable there).
5898
+ The lobes this replaced carried an explicit dead zone over the axis for exactly that reason; a quarter
5899
+ arc that starts 15 degrees off it keeps Option A's form and restores the separation. */
5900
+ const POS_SWING_START = Math.PI / 12; // 15 degrees off the member axis
5901
+ const POS_LETTER_PX = 13; // X/Y/Z glyph, screen-CONSTANT (not a fraction of the reach)
5902
+ const POS_LETTER_GAP_PX = 12; // ...and a fixed gap past the drawn arrow tip, so it never closes up as the reach shrinks
5903
+ const POS_ANCHOR_PX = 9; // the amber square origin marker, likewise screen-constant
5904
+ const POS_HOT = 0xfbbf24; // hover / active amber — one hue above the axis colour, never a new one
5905
+ const POS_TIE_COL = 0x67e8f9; // committed relationship — the tint the placed dimensions already use
5906
+ /* Two tiers, and a third state for "a gesture is running". The three profile handles are primary; the three
5907
+ that re-shape the reference line sit back until wanted. The mockup put that split behind a second mode
5908
+ ("six handles was three too many"); after the redesign five of the six handles move the line, so a
5909
+ profile-vs-reference-line MODE no longer describes anything — the tiering carries the same hierarchy
5910
+ while leaving every handle discoverable. Mid-drag everything but the active handle drops away, so the
5911
+ one element that is both amber and undimmed is the one under the hand. */
5912
+ /* The mockup's numbers were 0.95 / 0.45 / 0.25 / 0.12, drawn as 2 px SVG strokes. `LineBasicMaterial`
5913
+ ignores `linewidth` on Windows, so every stroke here is ONE pixel, and a 1 px line at 0.45 on this
5914
+ ground is close to invisible — the secondary tier stopped reading as "sit back" and started reading as
5915
+ "not there". The secondary values are raised to carry the same weight in a thinner medium; the gap to
5916
+ the primary tier is what the hierarchy is made of, and 0.95 vs 0.62 still reads at a glance. (The
5917
+ faithful alternative the mockup names — a thin CylinderGeometry stem, so the stroke really is 2 px — is
5918
+ a bigger change and is recorded as a follow-up rather than smuggled in here.) */
5919
+ const POS_TIER = { primary: 0.95, secondary: 0.62, dragPrimary: 0.3, dragSecondary: 0.24 };
5920
+ /* WHICH handles sit back, re-derived rather than inherited. The mockup's secondary trio was the
5921
+ "reference-line" handles — the slide and the two swings — because the primary trio wrote profile
5922
+ offsets. After the redesign the depth and width arrows translate the line exactly as the slide does, so
5923
+ that boundary describes nothing. The line that still means something is REACH vs RE-AIM: the three
5924
+ arrows and the roll keep the member's direction, while the two swings change where it points, which is
5925
+ the larger and rarer edit. So the swings sit back and the slide joins its fellow arrows. */
5926
+ const POS_SECONDARY = new Set(['swingPlan', 'swingElev']);
5688
5927
  // Per-handle hover copy — leads with the consequence (spec §3) + the double-click-to-type hint (3b.3). Shown
5689
5928
  // through the shared themed #tooltip (api.showHandleTip), never a native title=.
5690
5929
  const POS_HANDLE_TIP = {
5691
- depth: 'Slides the section along its depth axis. Drag, or double-click to type an exact value — ¼" snap; hold Shift for no snap.',
5692
- width: 'Slides the section along its width axis. Drag, or double-click to type an exact value — ¼" snap; hold Shift for no snap.',
5930
+ // depth/width MOVE THE MEMBER now: both work points translate along the profile axis, exactly as the
5931
+ // member-axis arrow already slides them along the axis. They no longer slide the profile off its
5932
+ // reference line — that is the Position panel's job, and its two offsets are panel-only numbers.
5933
+ depth: 'Moves the member along its depth axis. Drag, or double-click to type an exact value — ¼" snap; hold Shift for no snap.',
5934
+ width: 'Moves the member along its width axis. Drag, or double-click to type an exact value — ¼" snap; hold Shift for no snap.',
5693
5935
  rot: 'Rolls the section about the reference line. Drag, or double-click to type an exact angle — 5° snap; hold Shift for no snap.',
5694
- anchor: 'Reference-line start — the profile pivots here. This point never moves.',
5936
+ 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.',
5937
+ 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.',
5938
+ 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.',
5939
+ 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.',
5695
5940
  };
5696
- function disposePositionGizmo() {
5697
- hidePositionLeader(); // the transient drag leader never outlives a gizmo rebuild
5941
+ 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
5942
+ /* One CanvasTexture per glyph, built lazily and kept for the module's life. The gizmo is rebuilt once per
5943
+ animation frame while a gesture runs (see `posLiveState`), and `SpriteMaterial.dispose()` does NOT
5944
+ dispose its map — so a texture minted per rebuild would leak a canvas per frame. */
5945
+ const posGlyphTex = {};
5946
+ function posGlyphTexture(kind, colorCss) {
5947
+ const key = kind + '|' + colorCss;
5948
+ if (posGlyphTex[key]) return posGlyphTex[key];
5949
+ const S = 64, c = document.createElement('canvas'); c.width = c.height = S;
5950
+ const g = c.getContext('2d'), HALO = 'rgba(2,8,23,0.92)';
5951
+ if (kind === 'square') { // the origin marker: a filled square with a dark keyline, CAD's vertex glyph
5952
+ g.fillStyle = HALO; g.fillRect(12, 12, 40, 40);
5953
+ g.fillStyle = colorCss; g.fillRect(15, 15, 34, 34);
5954
+ } else { // an axis letter, stroked dark then filled, so it survives bright steel behind it
5955
+ g.font = 'bold 44px ui-sans-serif,system-ui,sans-serif'; g.textAlign = 'center'; g.textBaseline = 'middle';
5956
+ g.lineWidth = 8; g.lineJoin = 'round'; g.strokeStyle = HALO; g.strokeText(kind, S / 2, S / 2 + 2);
5957
+ g.fillStyle = colorCss; g.fillText(kind, S / 2, S / 2 + 2);
5958
+ }
5959
+ const tex = new THREE.CanvasTexture(c); if (THREE.SRGBColorSpace) tex.colorSpace = THREE.SRGBColorSpace; tex.needsUpdate = true;
5960
+ posGlyphTex[key] = tex; return tex;
5961
+ }
5962
+ function disposePositionGizmo(opts) {
5963
+ if (!(opts && opts.keepLeader)) hidePositionLeader(); // the transient drag leader never outlives a COMMITTED rebuild — but a live in-gesture rebuild must not blink it out between pointer events
5698
5964
  if (!positionGizmo) return;
5699
5965
  if (overlayScene) overlayScene.remove(positionGizmo);
5700
- positionGizmo.traverse((o) => { if (o.geometry) o.geometry.dispose(); if (o.material) o.material.dispose(); });
5701
- positionGizmo = null;
5966
+ /* Materials are per-build and disposed. TWO things here are shared and must NOT be:
5967
+ - the glyph TEXTURES are module-cached (see posGlyphTexture), and a SpriteMaterial.dispose() leaves
5968
+ its map alone, so they survive correctly;
5969
+ - every THREE.Sprite in the application shares ONE module-level BufferGeometry (three.core.js:21598
5970
+ mints `_geometry` once and hands the same instance to every sprite). Disposing it here would delete
5971
+ the GPU buffers behind the snap reticle, the grid labels and the dimension labels — and this runs
5972
+ once per animation FRAME during a drag, so it would churn them continuously during exactly the
5973
+ interaction that has to stay smooth. The gizmo grew sprites in this redesign; before that the
5974
+ blanket traverse was harmless. */
5975
+ positionGizmo.traverse((o) => { if (o.geometry && !o.isSprite) o.geometry.dispose(); if (o.material) o.material.dispose(); });
5976
+ positionGizmo = null; posWorldGroup = null; positionTie = null;
5702
5977
  }
5703
5978
  // The gizmo shows only when the toggle is on, exactly one member is selected, we are not in a work-plane
5704
5979
  // pick, and the editor reports the member as available (resolvable frame + offsets). Otherwise → null.
@@ -5716,47 +5991,164 @@ function currentPositionGizmoState() {
5716
5991
  if (st && st.reason) console.debug('steel-3d: Profile Position handle hidden —', st.reason);
5717
5992
  return null;
5718
5993
  }
5994
+ // The state the gizmo is DRAWN from: the live one mid-gesture, the committed one otherwise.
5995
+ function drawnPositionState() { return posLiveState || posGizmoState; }
5996
+ // The member's PROFILE axes for a state — its rolled depth/width. Every consumer goes through here, so the
5997
+ // arrow that is drawn, the axis the drag measures along and the direction the steel actually travels are
5998
+ // one thing. The fallback to the unrolled frame is for a state minted before `profile` existed.
5999
+ function posProfileAxes(st) {
6000
+ return (st && st.profile && st.profile.y && st.profile.z) ? st.profile : { y: st.yAxis, z: st.zAxis };
6001
+ }
6002
+ /* The colour + opacity a handle draws at, from the interaction state alone.
6003
+ Hover recolours ONLY the hovered handle: dimming its neighbours on every mousemove would flicker as the
6004
+ pointer skims across them. A drag is the state that dims — and then the active handle is the single
6005
+ element that is both amber and undimmed, so "which handle am I dragging" has exactly one answer. */
6006
+ function posHandleStyle(tag, col) {
6007
+ const dragging = !!posActiveHandle;
6008
+ const hot = dragging ? posActiveHandle === tag : posHoverHandle === tag;
6009
+ const secondary = POS_SECONDARY.has(tag);
6010
+ const opacity = hot ? 1
6011
+ : dragging ? (secondary ? POS_TIER.dragSecondary : POS_TIER.dragPrimary)
6012
+ : (secondary ? POS_TIER.secondary : POS_TIER.primary);
6013
+ return { color: hot ? POS_HOT : col, opacity };
6014
+ }
6015
+ // Set the in-gesture state the gizmo draws from, and mark it for ONE rebuild on the next frame. Called from
6016
+ // the drag handlers; `loop()` consumes the flag, so a 200 Hz pointer never rebuilds more than the display.
6017
+ function setPositionLive(st) { if (st) { posLiveState = st; posLiveDirty = true; } }
6018
+ function syncPositionGizmoLive() {
6019
+ if (!posLiveDirty) return;
6020
+ posLiveDirty = false;
6021
+ if (posLiveState) buildPositionGizmo(posLiveState, { keepLeader: true });
6022
+ }
5719
6023
  function renderPositionGizmo() {
5720
- disposePositionGizmo();
6024
+ posLiveState = null; posLiveDirty = false;
6025
+ /* Drop the hover with it. This path is reached by rebuilds the POINTER did not drive — an external
6026
+ write, a selection changed from the panel or the keyboard, a work-plane change — and the hover was
6027
+ only ever cleared by a pointermove or by leaving the canvas. So the new gizmo came up with a handle
6028
+ already amber and the cursor still `grab`, under a pointer nowhere near it, and nothing corrected it
6029
+ until the user happened to move the mouse. */
6030
+ posHoverHandle = null;
6031
+ if (canvasEl && posInteraction === 'idle') canvasEl.style.cursor = 'default';
5721
6032
  const st = currentPositionGizmoState(); posGizmoState = st;
6033
+ buildPositionGizmo(st);
6034
+ }
6035
+ /*
6036
+ * Build the whole gizmo from ONE state — the committed one at rest, the live one mid-gesture. Everything
6037
+ * that reads geometry (the drawing here, the screen probe, the pick sampler) goes through the same state
6038
+ * and the same scale, so they cannot disagree about where a handle is.
6039
+ *
6040
+ * Built in LOCAL space with the anchor at (0,0,0): the group carries no rotation, so local coords ARE
6041
+ * world offsets from the anchor, and scaling the whole group keeps every part screen-constant.
6042
+ */
6043
+ function buildPositionGizmo(st, opts) {
6044
+ disposePositionGizmo(opts);
5722
6045
  if (!st) return;
5723
6046
  const g = new THREE.Group();
5724
6047
  const V = (a) => new THREE.Vector3(a[0], a[1], a[2]);
5725
- const yv = V(st.yAxis), zv = V(st.zAxis);
5726
- // Built in LOCAL space with the anchor at (0,0,0): the group carries no rotation, so local coords ARE
5727
- // world offsets from the anchor, and scaling the whole group keeps every part screen-constant.
6048
+ const P = posProfileAxes(st);
6049
+ const yv = V(P.y), zv = V(P.z);
6050
+ const mat = (tag, col, extra) => {
6051
+ const s = posHandleStyle(tag, col);
6052
+ return new THREE.LineBasicMaterial({ color: s.color, transparent: true, opacity: s.opacity, depthTest: false, ...(extra || {}) });
6053
+ };
6054
+ /* Mockup proportions (§3 / §9): the shaft stops at POS_ARROW_STEM and an 11 x 18 px head sits FLUSH on
6055
+ it, tip landing on the reach. What shipped was a 0.13 x 0.36 head — ~34 x 48 px, roughly 3x the drawn
6056
+ width — CENTRED on the tip, so it overshot the reach to 1.18 and swamped a 1 px stem. */
5728
6057
  const arrow = (dirArr, col, tag) => {
5729
- const d = V(dirArr).normalize();
5730
- const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), d.clone().multiplyScalar(1)]),
5731
- new THREE.LineBasicMaterial({ color: col }));
5732
- line.material.depthTest = false; line.renderOrder = 997; line.userData = { posHandle: tag, stem: true }; g.add(line);
5733
- const cone = new THREE.Mesh(new THREE.ConeGeometry(0.13, 0.36, 16), new THREE.MeshBasicMaterial({ color: col }));
5734
- cone.material.depthTest = false; cone.renderOrder = 998; cone.quaternion.setFromUnitVectors(_YA, d);
5735
- cone.position.copy(d.clone().multiplyScalar(1)); cone.userData = { posHandle: tag, arrow: true }; g.add(cone);
6058
+ const d = V(dirArr).normalize(), s = posHandleStyle(tag, col);
6059
+ const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), d.clone().multiplyScalar(POS_ARROW_STEM)]),
6060
+ mat(tag, col));
6061
+ line.renderOrder = 997; line.userData = { posHandle: tag, stem: true }; g.add(line);
6062
+ const cone = new THREE.Mesh(new THREE.ConeGeometry(POS_HEAD_R, POS_HEAD_H, 16),
6063
+ new THREE.MeshBasicMaterial({ color: s.color, transparent: true, opacity: s.opacity, depthTest: false }));
6064
+ cone.renderOrder = 998; cone.quaternion.setFromUnitVectors(_YA, d);
6065
+ cone.position.copy(d.clone().multiplyScalar(POS_ARROW_STEM + POS_HEAD_H / 2)); // FLUSH on the stem, tip at the reach
6066
+ cone.userData = { posHandle: tag, arrow: true }; g.add(cone);
6067
+ };
6068
+ /* A QUARTER arc bridging exactly the two axes it rotates between (mockup Option A), replacing the 270°
6069
+ roll sweep and the four flanking swing lobes. The lobes existed because two same-radius arcs both
6070
+ centred on ±x̂ would COINCIDE there and the nearest-point pick would be arbitrary; three quarter arcs
6071
+ in three distinct planes touch only at a shared axis endpoint, so the ambiguity is gone by geometry —
6072
+ and five long curves become three short ones, which is most of the "unreadable when zoomed out"
6073
+ complaint answered without hiding a single handle. */
6074
+ const quarterArc = (e1, e2, col, tag, from = 0) => {
6075
+ const R = POS_ARC_R[tag], a = V(e1).normalize(), b = V(e2).normalize(), pts = [];
6076
+ for (let i = 0; i <= 24; i++) { const p = from + (i / 24) * (Math.PI / 2 - from);
6077
+ pts.push(a.clone().multiplyScalar(Math.cos(p) * R).add(b.clone().multiplyScalar(Math.sin(p) * R))); }
6078
+ const arc = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), mat(tag, col));
6079
+ arc.renderOrder = 997; arc.userData = { posHandle: tag, arc: true }; g.add(arc);
6080
+ };
6081
+ // A letter takes the tier of the handle it NAMES — posHandleStyle, not a second copy of the rule. The X
6082
+ // was drawn at the primary tier while its own arrow sat at the secondary one, which is precisely the
6083
+ // kind of drift a single style function exists to prevent. Colour stays by axis: a letter labels an
6084
+ // axis, not a grip, so it does not take the hover amber.
6085
+ const letter = (glyph, dirArr, colorCss, tag) => {
6086
+ const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: posGlyphTexture(glyph, colorCss), transparent: true, depthTest: false,
6087
+ opacity: posHandleStyle(tag, 0).opacity }));
6088
+ s.renderOrder = 999;
6089
+ // Position + scale are set every frame by sizePositionGizmo: the letter is a FIXED px glyph a FIXED px
6090
+ // past the drawn tip, not a fraction of a reach that shrinks (at the 46 px floor a multiplicative
6091
+ // k = 1.16 leaves a ~7 px gap and the glyph collides with the head).
6092
+ s.userData = { posLetter: true, axis: [dirArr[0], dirArr[1], dirArr[2]], pxSize: POS_LETTER_PX };
6093
+ g.add(s);
5736
6094
  };
5737
- // BY DESIGN the arrows point along the UNROTATED part axes (st.zAxis/st.yAxis), because a Profile
5738
- // Position offset is defined on the unrotated profile (§1.3). For a rolled member (rot ≠ 0) the steel
5739
- // therefore travels along the roll-swung direction, not along the arrow — the gizmo stays internally
5740
- // consistent (grab arrow → offset changes by the amount dragged along it) and preview↔commit agree, but
5741
- // arrow and motion diverge. Re-expressing the roll so they coincide is slice 3b; do not "fix" one half.
5742
- arrow(st.zAxis, 0x3b82f6, 'depth'); // blue = depth (positionOffset)
5743
- arrow(st.yAxis, 0x22c55e, 'width'); // green = width (positionHOffset)
5744
- // Rotation arc (red) about the member axis, drawn in the width–depth plane over a 270° sweep so both
5745
- // ends stay clear of the two arrows.
5746
- const R = 0.72, pts = [];
5747
- for (let i = 0; i <= 36; i++) { const p = (-0.75 + (i / 36) * 1.5) * Math.PI;
5748
- pts.push(yv.clone().multiplyScalar(Math.cos(p) * R).add(zv.clone().multiplyScalar(Math.sin(p) * R))); }
5749
- const arc = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineBasicMaterial({ color: 0xef4444 }));
5750
- arc.material.depthTest = false; arc.renderOrder = 997; arc.userData = { posHandle: 'rot', arc: true }; g.add(arc);
5751
- // Anchor dot (amber) — the reference-line start the whole gizmo pivots on.
5752
- const dot = new THREE.Mesh(new THREE.SphereGeometry(0.08, 12, 8), new THREE.MeshBasicMaterial({ color: 0xf59e0b }));
5753
- dot.material.depthTest = false; dot.renderOrder = 999; dot.userData = { posHandle: 'anchor' }; g.add(dot);
6095
+ arrow(P.z, 0x3b82f6, 'depth'); // blue = depth
6096
+ arrow(P.y, 0x22c55e, 'width'); // green = width
6097
+ quarterArc(P.y, P.z, 0xef4444, 'rot'); // red = roll about the member axis, bridging width → depth
6098
+ if (st.handles && st.handles.slide && st.handles.slide.available) arrow(st.xAxis, 0xef4444, 'slide');
6099
+ /* The swing arcs stay on the UNROLLED authoring frame, because that is where their axes are defined: an
6100
+ elevation swing about a ROLLED y is not a tilt, it is some mixture of tilt and plan swing. So the gizmo
6101
+ carries two frames — the profile frame for depth/width/roll, the reference-line frame for the slide and
6102
+ the two swings — and each handle is drawn in the one it is actually defined in. */
6103
+ const swingArc = (axisArr, col, tag, towardUp) => {
6104
+ const b = axisArr && swingBasis(st.anchor, st.end, axisArr);
6105
+ 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
6106
+ quarterArc(b.e1, swingArcE2(b, st.up, towardUp), col, tag, POS_SWING_START); // dead zone over the shared axis end
6107
+ };
6108
+ if (st.handles && st.handles.swingPlan && st.handles.swingPlan.available) swingArc(st.up, 0x3b82f6, 'swingPlan', false);
6109
+ if (st.handles && st.handles.swingElev && st.handles.swingElev.available) swingArc(st.yAxis, 0x22c55e, 'swingElev', true);
6110
+ letter('X', st.xAxis, '#ef4444', 'slide'); letter('Y', P.y, '#22c55e', 'width'); letter('Z', P.z, '#3b82f6', 'depth');
6111
+ // Anchor square (amber) — the reference-line start the whole gizmo pivots on. A sprite, so it is
6112
+ // screen-constant independently of the group scale (see sizePositionGizmo) and always faces the camera.
6113
+ const dot = new THREE.Sprite(new THREE.SpriteMaterial({ map: posGlyphTexture('square', '#f59e0b'), transparent: true, depthTest: false,
6114
+ opacity: posHoverHandle === 'anchor' ? 1 : 0.95 }));
6115
+ dot.renderOrder = 999; dot.userData = { posHandle: 'anchor', pxSize: POS_ANCHOR_PX }; g.add(dot);
6116
+ /* The committed tie: anchor → the offset profile's origin, in the muted #67e8f9 the placed dimensions
6117
+ already use for "committed". It matters MORE since the arrows stopped writing offsets, not less — the
6118
+ panel's two offsets are now the only thing that can separate the steel from its work line, and without
6119
+ this the 3D view has no cue at all that one is set. There is deliberately NO live/bright variant: the
6120
+ mockup's Option C brightened it to #22d3ee during a gesture, but no 3D gesture touches the offsets any
6121
+ more, so that would be a branch nothing can reach. Drawn only when an offset is actually non-zero. */
6122
+ const off = +st.positionOffset || 0, hoff = +st.positionHOffset || 0;
6123
+ if (off || hoff) {
6124
+ // WORLD mm, not gizmo units: posWorldGroup is counter-scaled each frame so its children keep real size.
6125
+ posWorldGroup = new THREE.Group();
6126
+ const fr = { y: st.yAxis, z: st.zAxis };
6127
+ const dv = positionSwingDelta(fr, 'depth', off, st.rot || 0), wv = positionSwingDelta(fr, 'width', hoff, st.rot || 0);
6128
+ const tip = new THREE.Vector3(dv[0] + wv[0], dv[1] + wv[1], dv[2] + wv[2]);
6129
+ positionTie = new THREE.Line(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), tip]),
6130
+ new THREE.LineBasicMaterial({ color: POS_TIE_COL, transparent: true, opacity: 0.75, depthTest: false }));
6131
+ positionTie.renderOrder = 996;
6132
+ posWorldGroup.add(positionTie); g.add(posWorldGroup);
6133
+ }
5754
6134
  g.position.set(st.anchor[0], st.anchor[1], st.anchor[2]);
5755
6135
  positionGizmo = g; overlayScene.add(g); sizePositionGizmo();
5756
6136
  }
6137
+ /* A swing arc's second in-plane axis, with the sweep turned so the arc rises rather than dives. `swingBasis`
6138
+ fixes e1 (the member direction in the plane) and e2 = axis × e1; for an elevation swing e2 can point below
6139
+ the member as easily as above it, and an arc that hangs downward reads as the wrong gesture. Flipping e2
6140
+ sweeps the same great circle through the opposite quadrant — the pick samples whatever is drawn, so this
6141
+ is purely which quadrant the affordance occupies. */
6142
+ function swingArcE2(basis, up, towardUp) {
6143
+ if (!towardUp || !up) return basis.e2;
6144
+ const d = basis.e2[0] * up[0] + basis.e2[1] * up[1] + basis.e2[2] * up[2];
6145
+ return d < 0 ? [-basis.e2[0], -basis.e2[1], -basis.e2[2]] : basis.e2;
6146
+ }
5757
6147
  // Cyan #22d3ee rubber-band leader from the amber anchor to the live drag point — the "offsetting from a fixed
5758
6148
  // point" signal. #22d3ee already ships as the frame-gizmo rotation ring + the cmHud selected-segment accent, so
5759
6149
  // it is in-palette (blessed by the ui-ux pass). Lives in the overlay scene, depthTest:false, above the arrows.
6150
+ // Its ORIGIN is the COMMITTED anchor on purpose: the band measures how far the gesture has come from where it
6151
+ // started, which it cannot do if its own tail travels with the drag.
5760
6152
  function updatePositionLeader(tipWorld) {
5761
6153
  if (!overlayScene || !posGizmoState) return;
5762
6154
  const O = posGizmoState.anchor, pts = [new THREE.Vector3(O[0], O[1], O[2]), new THREE.Vector3(tipWorld[0], tipWorld[1], tipWorld[2])];
@@ -5773,25 +6165,87 @@ function disposePositionLeader() {
5773
6165
  if (positionLeader.geometry) positionLeader.geometry.dispose(); if (positionLeader.material) positionLeader.material.dispose();
5774
6166
  positionLeader = null;
5775
6167
  }
5776
- // Screen-constant: scale the whole group so a unit-length arrow spans POS_GIZMO_REACH_PX at the anchor.
6168
+ // The world size of one LOCAL gizmo unit — i.e. of the arrow reach. ONE definition, because the drawing, the
6169
+ // screen probe, the pick sampler and the roll leader all have to agree about where a handle is; while the
6170
+ // sizing used the adaptive reach and everyone else still used the fixed 132 px ceiling, the pick target on a
6171
+ // zoomed-out member sat about three times further out than the arrowhead it was supposed to be on.
6172
+ /* `st` is threaded, not implied. The reach depends on the member's on-screen LENGTH, so a screen probe
6173
+ asked about frozen drag-start geometry has to measure the frozen end too — otherwise the reach (and with
6174
+ it the projected tip distance the edge-on test compares against) drifts as the drag proceeds, and the
6175
+ guard the doc comment calls frozen is only half frozen. Omit `st` and it falls back to the drawn state,
6176
+ which is what the per-frame sizing pass wants. */
6177
+ function positionGizmoScale(anchor, st) { return pxToWorldAt(positionGizmoReachPx(anchor, st), anchor); }
6178
+ // Screen-constant: scale the whole group so a unit-length arrow spans the current reach at the anchor, then
6179
+ // a SECOND pass for the children that must be a fixed number of PIXELS rather than a fraction of the reach —
6180
+ // the amber square and the X/Y/Z letters. Without it a "9 px" square renders at ~3 px once the reach is
6181
+ // floored to 46, because a single group scale is all any child gets. (`sizeFrameHandle` does the same thing
6182
+ // for the frame gizmo's origin dot.)
5777
6183
  function sizePositionGizmo() {
5778
- if (!positionGizmo || !posGizmoState) return;
5779
- const O = posGizmoState.anchor;
5780
- positionGizmo.scale.setScalar(pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2])));
6184
+ if (!positionGizmo) return;
6185
+ const dst = drawnPositionState(); if (!dst) return;
6186
+ const O = dst.anchor, anchor = _posAnchorV.set(O[0], O[1], O[2]); // scratch: this runs EVERY frame, idle included
6187
+ const sc = positionGizmoScale(anchor);
6188
+ if (!(sc > 0)) return;
6189
+ positionGizmo.scale.setScalar(sc);
6190
+ if (posWorldGroup) posWorldGroup.scale.setScalar(1 / sc); // its children are authored in world mm
6191
+ const px = (n) => pxToWorldAt(n, anchor) / sc; // n screen px, expressed in LOCAL units
6192
+ const letterOut = 1 + px(POS_LETTER_GAP_PX + POS_LETTER_PX / 2);
6193
+ for (const c of positionGizmo.children) {
6194
+ const u = c.userData; if (!u) continue;
6195
+ if (u.pxSize) c.scale.setScalar(px(u.pxSize));
6196
+ if (u.posLetter && u.axis) c.position.set(u.axis[0] * letterOut, u.axis[1] * letterOut, u.axis[2] * letterOut);
6197
+ }
6198
+ }
6199
+ /* The member's on-screen length, in px, or null when it cannot be measured (no far point, degenerate
6200
+ projection). Measured through the SAME camera the gizmo is drawn with, so it is correct in ortho and
6201
+ perspective alike rather than assuming a distance model. */
6202
+ function memberScreenLengthPx(anchor, st) {
6203
+ const dst = st || drawnPositionState(), E = dst && dst.end;
6204
+ if (!E || !canvasEl) return null;
6205
+ const a = _posProjA.copy(anchor).project(camera), b = _posProjB.set(E[0], E[1], E[2]).project(camera);
6206
+ const w = canvasEl.clientWidth || 1, h = canvasEl.clientHeight || 1;
6207
+ const px = Math.hypot((b.x - a.x) * w / 2, (b.y - a.y) * h / 2);
6208
+ return Number.isFinite(px) && px > 0 ? px : null;
6209
+ }
6210
+ function positionGizmoReachPx(anchor, st) {
6211
+ const len = memberScreenLengthPx(anchor, st);
6212
+ if (len == null) return POS_GIZMO_REACH_PX; // unmeasurable → the old fixed reach, never a collapsed gizmo
6213
+ return Math.max(POS_GIZMO_REACH_MIN_PX, Math.min(POS_GIZMO_REACH_PX, len * POS_GIZMO_REACH_FRAC));
5781
6214
  }
5782
- // The gizmo's grab points in client px, for an E2E to drive precise drags (mirrors frameHandlesScreen).
5783
- function positionGizmoHandlesScreen() {
5784
- if (!canvasEl || !posGizmoState) return null;
6215
+ /*
6216
+ * The gizmo's grab points in client px, for an E2E to drive precise drags (mirrors frameHandlesScreen).
6217
+ *
6218
+ * With no argument it reports the DRAWN state — live while a gesture runs, so a test can sample mid-drag and
6219
+ * see the handles track. The two edge-on guards pass the FROZEN drag-start state explicitly: they measure
6220
+ * whether the axis is too foreshortened to drag along, and that question is asked of the geometry the drag's
6221
+ * arithmetic is frozen against, not of geometry the drag is itself moving.
6222
+ */
6223
+ function positionGizmoHandlesScreen(stOverride) {
6224
+ const st = stOverride || drawnPositionState();
6225
+ if (!canvasEl || !st) return null;
5785
6226
  camera.updateMatrixWorld();
5786
- const rect = canvasEl.getBoundingClientRect(), O = posGizmoState.anchor;
5787
- const sc = pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2]));
6227
+ const rect = canvasEl.getBoundingClientRect(), O = st.anchor;
6228
+ const sc = positionGizmoScale(new THREE.Vector3(O[0], O[1], O[2]), st);
6229
+ const P = posProfileAxes(st);
5788
6230
  const toS = (p) => { const w = new THREE.Vector3(p[0], p[1], p[2]).project(camera);
5789
6231
  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 }; };
5790
6232
  const at = (ax, k) => toS([O[0] + ax[0] * sc * k, O[1] + ax[1] * sc * k, O[2] + ax[2] * sc * k]);
5791
- const rotArr = [posGizmoState.yAxis[0] * 0.51 + posGizmoState.zAxis[0] * 0.51,
5792
- posGizmoState.yAxis[1] * 0.51 + posGizmoState.zAxis[1] * 0.51,
5793
- posGizmoState.yAxis[2] * 0.51 + posGizmoState.zAxis[2] * 0.51];
5794
- return { anchor: toS(O), depthTip: at(posGizmoState.zAxis, 1), widthTip: at(posGizmoState.yAxis, 1), rotHandle: at(rotArr, 1), available: true };
6233
+ // Every arc grab sits at its 45° point — the same point the pick samples nearest, so an E2E drag from
6234
+ // here lands on the handle it named.
6235
+ const mid = (e1, e2, tag, from = 0) => {
6236
+ const p = (from + Math.PI / 2) / 2, c = Math.cos(p), s2 = Math.sin(p); // the DRAWN arc's midpoint, which moves with its dead zone
6237
+ return at([e1[0] * c + e2[0] * s2, e1[1] * c + e2[1] * s2, e1[2] * c + e2[2] * s2], POS_ARC_R[tag]);
6238
+ };
6239
+ const swingGrab = (axisArr, tag, towardUp) => {
6240
+ const b = axisArr && st.end && swingBasis(st.anchor, st.end, axisArr);
6241
+ return b ? mid(b.e1, swingArcE2(b, st.up, towardUp), tag, POS_SWING_START) : null;
6242
+ };
6243
+ const h = st.handles;
6244
+ return { anchor: toS(O), depthTip: at(P.z, 1), widthTip: at(P.y, 1), rotHandle: mid(P.y, P.z, 'rot'),
6245
+ slideTip: h && h.slide && h.slide.available ? at(st.xAxis, 1) : null,
6246
+ swingPlanHandle: h && h.swingPlan && h.swingPlan.available ? swingGrab(st.up, 'swingPlan', false) : null,
6247
+ swingElevHandle: h && h.swingElev && h.swingElev.available ? swingGrab(st.yAxis, 'swingElev', true) : null,
6248
+ handles: h || null, available: true };
5795
6249
  }
5796
6250
  function setPositionGizmoVisible(on) { positionGizmoVisible = !!on; syncGizmoVisibility(); } // ⋯ Display toggle → editor pushes the flag (also (un)hides the frame gizmo)
5797
6251
  // The editor's docked numeric HUD is open on a handle → freeze the camera so orbit/zoom can't drift the anchor
@@ -5799,9 +6253,18 @@ function setPositionGizmoVisible(on) { positionGizmoVisible = !!on; syncGizmoVis
5799
6253
  function setPositionTyping(on) {
5800
6254
  posInteraction = on ? 'typing' : 'idle';
5801
6255
  if (controls) controls.enabled = !on; // idle default = orbit enabled; typing = frozen
5802
- if (on) { hidePositionLeader(); posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); }
6256
+ if (on) { hidePositionLeader(); posHovered = false; setPositionHover(null); if (api && api.hideHandleTip) api.hideHandleTip(); }
5803
6257
  if (canvasEl) canvasEl.style.cursor = on ? 'text' : 'default';
5804
6258
  }
6259
+ /* Hover is a rebuild, not a per-frame mutation: the gizmo is already rebuilt on every state change, and a
6260
+ hover changes at human speed. The cursor is load-bearing rather than decorative — it is the second of
6261
+ three redundant channels (colour, cursor, tooltip) so the highlight does not rest on hue alone. */
6262
+ function setPositionHover(tag) {
6263
+ if (posHoverHandle === tag) return;
6264
+ posHoverHandle = tag;
6265
+ if (canvasEl && posInteraction !== 'typing') canvasEl.style.cursor = (tag && tag !== 'anchor') ? 'grab' : 'default';
6266
+ if (positionGizmo) buildPositionGizmo(drawnPositionState(), { keepLeader: true });
6267
+ }
5805
6268
  // E2E read-only probe: a member mesh's WORLD transform, so a test can assert a gizmo drag's live preview
5806
6269
  // equals the committed rebuild (no jump on release) and that "From member" leaves the steel exactly put.
5807
6270
  function memberWorldTransform(id) {
@@ -5815,12 +6278,32 @@ function memberWorldTransform(id) {
5815
6278
  // drawn? The latter proves the mutual hide (position gizmo showing → frame gizmo null → not pickable).
5816
6279
  function positionLeaderVisible() { return !!(positionLeader && positionLeader.visible); }
5817
6280
  function frameGizmoVisible() { return !!frameGizmo; }
5818
-
5819
- // --- Profile Position gizmo: pick + drag. depth/width arrows drive the numeric offsets; the arc drives
5820
- // the roll. Every gesture reports an ABSOLUTE new value to the editor on release (one undo entry).
6281
+ // E2E read-only probe: which handle is currently highlighted, and at what reach the gizmo is drawn — so a
6282
+ // test can assert the amber hover and the "proportionate to the member" sizing without reading pixels.
6283
+ function positionGizmoStyleProbe() {
6284
+ const dst = drawnPositionState(); if (!dst) return null;
6285
+ const anchor = new THREE.Vector3(dst.anchor[0], dst.anchor[1], dst.anchor[2]);
6286
+ return { hover: posHoverHandle, active: posActiveHandle, hot: '#fbbf24',
6287
+ reachPx: positionGizmoReachPx(anchor), memberPx: memberScreenLengthPx(anchor),
6288
+ cursor: canvasEl ? canvasEl.style.cursor : null, // reported here rather than left to a test to guess which element carries it
6289
+ live: !!posLiveState, tie: !!positionTie };
6290
+ }
6291
+
6292
+ // --- Profile Position gizmo: pick + drag. The three arrows TRANSLATE the reference line (both work points
6293
+ // move together); the two swing arcs re-aim it; the roll arc turns the profile about it. Every gesture
6294
+ // reports an absolute result to the editor on release — one undo entry.
5821
6295
  const POS_SNAP_MM = POSITION_OFFSET_SNAP_MM; // ¼" offset snap (shared with the bake helpers, in steel-3d-core)
5822
6296
  const POS_SNAP_DEG = POSITION_ROT_SNAP_DEG; // 5° rotation snap
5823
- const POS_EDGE_ON_PX = 26; // below this projected axis length a drag is refused (spec §3.1)
6297
+ /* Spec §3.1 refuses a drag below 26 px of projected axis length, because a foreshortened axis inflates
6298
+ mm-per-pixel without bound. That number was calibrated against a FIXED 132 px reach, where it means "the
6299
+ axis is within ~11 degrees of the view direction". Once the reach became adaptive the same 26 px started
6300
+ meaning something different at every zoom — at the 46 px floor it refuses at ~34 degrees, so a drag that
6301
+ worked perfectly zoomed in reports "View is edge-on" zoomed out, and the same test gates PICKING the
6302
+ slide arrow and both swing arcs. The sensitivity it protects against depends only on foreshortening, not
6303
+ on how big the gizmo happens to be drawn, so the threshold scales with the reach and the ratio — not the
6304
+ pixel count — is the constant. */
6305
+ const POS_EDGE_ON_FRAC = 26 / 132;
6306
+ function posEdgeOnPx(anchor, st) { return POS_EDGE_ON_FRAC * positionGizmoReachPx(anchor, st); }
5824
6307
  function posGizmoRay(e) {
5825
6308
  const rect = canvasEl.getBoundingClientRect();
5826
6309
  const ndc = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
@@ -5843,23 +6326,101 @@ function posGizmoArcAngle(e, st) {
5843
6326
  const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(new THREE.Vector3(st.xAxis[0], st.xAxis[1], st.xAxis[2]).normalize(), O);
5844
6327
  const hit = new THREE.Vector3(); if (!ray.intersectPlane(plane, hit)) return null;
5845
6328
  const d = new THREE.Vector3().subVectors(hit, O);
5846
- 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])));
6329
+ const P = posProfileAxes(st); // the roll is measured in the plane the roll ARC is drawn in, so grabbing the arc and turning it agree
6330
+ return Math.atan2(d.dot(new THREE.Vector3(P.z[0], P.z[1], P.z[2])), d.dot(new THREE.Vector3(P.y[0], P.y[1], P.y[2])));
6331
+ }
6332
+ /**
6333
+ * The pointer's angle in a swing's own plane, measured in the FROZEN in-plane basis: `atan2(d·e2, d·e1)`
6334
+ * with `e1 × e2 = axis`. Because the basis is right-handed about the rotation axis, a positive angle is
6335
+ * the same sweep whichever side of the screen the camera is on — which a screen-pixel delta cannot give,
6336
+ * and which is why the arc is drawn in this same basis. null when the ray is parallel to the plane.
6337
+ */
6338
+ function posSwingAngle(e, st, axisArr, basis) {
6339
+ if (!axisArr || !basis) return null;
6340
+ const ray = posGizmoRay(e);
6341
+ const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
6342
+ const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(new THREE.Vector3(axisArr[0], axisArr[1], axisArr[2]).normalize(), O);
6343
+ const hit = new THREE.Vector3(); if (!ray.intersectPlane(plane, hit)) return null;
6344
+ const d = new THREE.Vector3().subVectors(hit, O);
6345
+ return Math.atan2(d.dot(new THREE.Vector3(basis.e2[0], basis.e2[1], basis.e2[2])),
6346
+ d.dot(new THREE.Vector3(basis.e1[0], basis.e1[1], basis.e1[2])));
5847
6347
  }
5848
6348
  function pickPositionGizmoHandle(cx, cy) {
5849
- if (!positionGizmoVisible || !posGizmoState || !canvasEl) return null;
5850
- const h = positionGizmoHandlesScreen(); if (!h) return null;
6349
+ // Never mid-gesture: the drawn handles are tracking the member while the cached state is not, so a
6350
+ // hit-test here would answer about geometry the user is no longer looking at. Nothing needed this guard
6351
+ // until the gizmo started following the drag.
6352
+ if (!positionGizmoVisible || !posGizmoState || !canvasEl || posInteraction === 'dragging') return null;
6353
+ const h = positionGizmoHandlesScreen(posGizmoState); if (!h) return null;
6354
+ // Tolerance is GEOMETRY-only and never reads material opacity: a secondary handle faded to 0.12 mid-drag
6355
+ // stays exactly as grabbable as it is at 0.45. (Pinned by test, because "fade what you cannot reach" is
6356
+ // an easy future change to make in the wrong direction.)
6357
+ const st = posGizmoState, O0 = st.anchor;
5851
6358
  const hit = (pt) => pt && !pt.behind && Math.hypot(pt.x - cx, pt.y - cy) <= 14;
5852
6359
  if (hit(h.depthTip)) return 'depth';
5853
6360
  if (hit(h.widthTip)) return 'width';
5854
- // Arc: sample it in screen space and grab the nearest point within tolerance.
5855
- const O = posGizmoState.anchor, sc = pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2]));
5856
- const rect = canvasEl.getBoundingClientRect(), yv = posGizmoState.yAxis, zv = posGizmoState.zAxis; let best = 12;
5857
- 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;
5858
- const w = 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).project(camera);
5859
- 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;
5860
- const dd = Math.hypot(sx - cx, sy - cy); if (dd < best) best = dd; }
5861
- return best < 12 ? 'rot' : null;
5862
- }
6361
+ // Sighting straight down the member axis collapses the slide arrow to a point AND takes both swing arc
6362
+ // planes edge-on at once — a genuinely degenerate view. Refuse those three picks there rather than try to
6363
+ // out-geometry it, exactly as the depth/width arrows already refuse their own edge-on drag.
6364
+ const axisOk = h.anchor && !h.anchor.behind && h.slideTip && !h.slideTip.behind
6365
+ && Math.hypot(h.slideTip.x - h.anchor.x, h.slideTip.y - h.anchor.y) >= posEdgeOnPx(_posAnchorV.set(O0[0], O0[1], O0[2]), st);
6366
+ if (axisOk && hit(h.slideTip)) return 'slide';
6367
+ const O = O0;
6368
+ const sc = positionGizmoScale(new THREE.Vector3(O[0], O[1], O[2]), st); // the SAME scale the gizmo is drawn at — see positionGizmoScale
6369
+ const rect = canvasEl.getBoundingClientRect();
6370
+ // Sample an arc in screen space and take the nearest point within tolerance.
6371
+ /* Screen distance to the NEAREST sample, or Infinity when nothing is within tolerance. It returns the
6372
+ distance rather than a boolean because the three arcs are picked by nearest-wins, not by `if` order:
6373
+ staggered radii keep them apart in 3D, but a camera can still project two of them close together, and
6374
+ "whichever I tested first" is not an answer a user can predict. */
6375
+ const nearestOn = (samples) => { let best = Infinity;
6376
+ for (const w0 of samples) { const w = w0.project(camera);
6377
+ 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;
6378
+ const dd = Math.hypot(sx - cx, sy - cy); if (dd < best) best = dd; }
6379
+ return best <= 12 ? best : Infinity; };
6380
+ // The three quarter arcs, sampled exactly as they are drawn — same radius, same bases, same sweep — so
6381
+ // the pick can never target a curve the user cannot see.
6382
+ const arcSamples = (e1, e2, tag, from = 0) => {
6383
+ const out = [], R = POS_ARC_R[tag] * sc;
6384
+ for (let i = 0; i <= 24; i++) { const p = from + (i / 24) * (Math.PI / 2 - from), c = Math.cos(p) * R, s = Math.sin(p) * R;
6385
+ out.push(new THREE.Vector3(O[0] + e1[0] * c + e2[0] * s, O[1] + e1[1] * c + e2[1] * s, O[2] + e1[2] * c + e2[2] * s)); }
6386
+ return out; };
6387
+ const P = posProfileAxes(st);
6388
+ const swingSamples = (axisArr, tag, towardUp) => {
6389
+ const b = st.end && axisArr && swingBasis(st.anchor, st.end, axisArr);
6390
+ return b ? arcSamples(b.e1, swingArcE2(b, st.up, towardUp), tag, POS_SWING_START) : []; // the SAME dead zone the arc is drawn with
6391
+ };
6392
+ // Nearest wins. The roll used to be tested first and returned on any hit, so wherever the camera put it
6393
+ // within tolerance of the tilt arc the tilt could not be grabbed at all — its own midpoint rolled the
6394
+ // section instead. Sighting down the member axis still refuses the three axis-dependent handles outright.
6395
+ const arcs = [['rot', nearestOn(arcSamples(P.y, P.z, 'rot'))]];
6396
+ if (axisOk) {
6397
+ if (h.swingPlanHandle) arcs.push(['swingPlan', nearestOn(swingSamples(st.up, 'swingPlan', false))]);
6398
+ if (h.swingElevHandle) arcs.push(['swingElev', nearestOn(swingSamples(st.yAxis, 'swingElev', true))]);
6399
+ }
6400
+ let bestTag = null, bestD = Infinity;
6401
+ for (const [tag, d] of arcs) if (d < bestD) { bestD = d; bestTag = tag; }
6402
+ return bestTag;
6403
+ }
6404
+ // The amber anchor dot, hit-tested SEPARATELY and consulted ONLY by the hover/tooltip path. Deliberately
6405
+ // not part of `pickPositionGizmoHandle`: that function's answers arm a drag in onDown, and the dot is not
6406
+ // draggable — a mousedown on it must keep falling through to ordinary click-select, exactly as it always
6407
+ // has. Two independent checks over the same pixels, with different consumers. (Before 3b.1 the anchor's
6408
+ // tooltip copy existed but could never be shown, because nothing ever answered 'anchor'.)
6409
+ function pickPositionAnchorHover(cx, cy) {
6410
+ if (!positionGizmoVisible || !posGizmoState || !canvasEl || posInteraction === 'dragging') return false;
6411
+ const h = positionGizmoHandlesScreen(posGizmoState);
6412
+ return !!(h && h.anchor && !h.anchor.behind && Math.hypot(h.anchor.x - cx, h.anchor.y - cy) <= 11);
6413
+ }
6414
+ /* The translate axis a handle drags along, in world coords: the member axis for the slide, and the member's
6415
+ ROLLED depth/width for the other two. One place, so the arrow that is drawn, the scalar the drag measures,
6416
+ the preview, the leader and the committed endpoints all travel the same direction. */
6417
+ function posTranslateAxis(st, kind) {
6418
+ const P = posProfileAxes(st);
6419
+ return kind === 'slide' ? st.xAxis : kind === 'depth' ? P.z : kind === 'width' ? P.y : null;
6420
+ }
6421
+ // The three handles that MOVE the reference line without re-aiming it, plus the two that swing it: everything
6422
+ // except the roll arc, which is the only handle left that writes a stored member field.
6423
+ function posMovesLine(kind) { return kind !== 'rot'; }
5863
6424
  function startPositionGizmoDrag(kind, e) {
5864
6425
  const id = [...selIds][0], st = api.positionGizmoState(id);
5865
6426
  // The handle was picked from the CACHED snapshot, but the base value comes from a FRESH read — if the
@@ -5867,14 +6428,65 @@ function startPositionGizmoDrag(kind, e) {
5867
6428
  // a fall-through click on empty space would strand the camera). code-review: silent-failure #1.
5868
6429
  if (!st || !st.available) { pending = null; if (controls) controls.enabled = true; return; }
5869
6430
  const mesh = meshById.get(id);
5870
- const base = kind === 'depth' ? st.positionOffset : kind === 'width' ? st.positionHOffset : st.rot;
5871
- const startScalar = kind === 'rot' ? posGizmoArcAngle(e, st) : posGizmoAxisScalar(e, st, kind === 'depth' ? st.zAxis : st.yAxis);
6431
+ const mesh0 = { meshPos0: mesh ? mesh.position.clone() : null, meshQuat0: mesh ? mesh.quaternion.clone() : null };
6432
+ const armed = () => {
6433
+ posInteraction = 'dragging'; posActiveHandle = kind; posHoverHandle = null; posHovered = false;
6434
+ if (canvasEl) canvasEl.style.cursor = 'grabbing';
6435
+ 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
6436
+ if (positionGizmo) buildPositionGizmo(st, { keepLeader: true }); // repaint at the drag tiering immediately, so the active handle is amber from the first pixel
6437
+ downXY = [e.clientX, e.clientY];
6438
+ };
6439
+ // --- Reference-line gestures: freeze EVERYTHING the gesture depends on, right here.
6440
+ // The rotation axis, the drag-start far endpoint, the in-plane basis and the plumb barriers are all
6441
+ // constants for the whole gesture, so each tick applies the TOTAL angle to the frozen endpoint rather
6442
+ // than composing per-tick rotations (which drifts, and makes the 5° snap chatter). The barriers in
6443
+ // particular are closed-form and cannot change while the geometry is frozen — computing them once here
6444
+ // instead of per pointer-move keeps the drag path O(1).
6445
+ if (posMovesLine(kind)) {
6446
+ const avail = st.handles && st.handles[kind];
6447
+ if (!avail || !avail.available) {
6448
+ // A VISIBLE, hovering, tooltipped handle that does nothing on press is confusing — the handles are
6449
+ // hit-tested from the cached state while this re-reads fresh, so a model change in between can make
6450
+ // one dead. Say so, exactly as openPositionHud already does for the same stale-cache case, instead
6451
+ // of returning into silence. (console.debug alone is invisible at Chrome's default level.)
6452
+ const why = (avail && avail.reason) || 'That handle isn’t available on this member.';
6453
+ console.warn('steel-3d: reference-line handle refused —', why);
6454
+ positionGizmoReadout(e, why, '');
6455
+ pending = null; if (controls) controls.enabled = true; return;
6456
+ }
6457
+ const swinging = kind === 'swingPlan' || kind === 'swingElev';
6458
+ const swingAxis = kind === 'swingPlan' ? st.up : kind === 'swingElev' ? st.yAxis : null;
6459
+ const basis = swingAxis ? swingBasis(st.anchor, st.end, swingAxis) : null;
6460
+ // Only the ELEVATION swing can reach plumb: a plan swing preserves the member's distance from the
6461
+ // degeneracy cone exactly, so it can neither enter nor leave it and needs no barrier at all.
6462
+ const barriers = kind === 'swingElev' ? swingBarriers(st.anchor, st.end, st.yAxis, st.up, POS_SWING_MARGIN_RAD) : null;
6463
+ if (swinging && (!basis || (kind === 'swingElev' && !barriers))) {
6464
+ const why = 'This member can’t be swung from its current direction — set its geometry in the Inspect panel.';
6465
+ console.warn('steel-3d: reference-line swing refused — no usable', basis ? 'plumb barrier' : 'swing plane');
6466
+ positionGizmoReadout(e, why, '');
6467
+ pending = null; if (controls) controls.enabled = true; return;
6468
+ }
6469
+ const transAxis = swinging ? null : posTranslateAxis(st, kind);
6470
+ const startScalar = swinging ? posSwingAngle(e, st, swingAxis, basis) : posGizmoAxisScalar(e, st, transAxis);
6471
+ pending = { posGizmo: { id, axis: kind, state: st, refline: true, base: 0, startScalar, newVal: 0,
6472
+ swingAxis, basis, barriers, transAxis, accumRad: 0, prevAng: startScalar, ...mesh0 } };
6473
+ armed();
6474
+ return;
6475
+ }
6476
+ const base = st.rot;
6477
+ const startScalar = posGizmoArcAngle(e, st);
5872
6478
  pending = { posGizmo: { id, axis: kind, state: st, base, startScalar, newVal: base,
5873
- accumRad: 0, prevAng: kind === 'rot' ? startScalar : null, // rot: accumulate the arc CONTINUOUSLY (unwrapAngleStep) so a ±180° seam crossing never jumps ~2π
5874
- meshPos0: mesh ? mesh.position.clone() : null, meshQuat0: mesh ? mesh.quaternion.clone() : null } };
5875
- posInteraction = 'dragging';
5876
- 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
5877
- downXY = [e.clientX, e.clientY];
6479
+ accumRad: 0, prevAng: startScalar, // rot: accumulate the arc CONTINUOUSLY (unwrapAngleStep) so a ±180° seam crossing never jumps ~2π
6480
+ ...mesh0 } };
6481
+ armed();
6482
+ }
6483
+ // A gesture ended (committed, refused, or cancelled): drop the in-flight highlight and the live state, and
6484
+ // give the pointer back its ordinary cursor. Kept in ONE place because three paths end a drag — onUp, the
6485
+ // Esc handler and the double-click guard — and any of them leaving `posActiveHandle` set would freeze the
6486
+ // whole gizmo at its mid-drag tiering.
6487
+ function endPositionGesture() {
6488
+ posInteraction = 'idle'; posActiveHandle = null; posLiveState = null; posLiveDirty = false;
6489
+ if (canvasEl) canvasEl.style.cursor = 'default';
5878
6490
  }
5879
6491
  function positionGizmoReadout(e, txt, type) {
5880
6492
  if (!readout) return;
@@ -5890,57 +6502,113 @@ function onMovePositionGizmo(e) {
5890
6502
  if (!dragging && Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]) <= DRAG_TOL_PX) return;
5891
6503
  dragging = pending;
5892
6504
  const pg = pending.posGizmo, st = pg.state, mesh = meshById.get(pg.id);
5893
- if (pg.axis === 'rot') {
5894
- const ang = posGizmoArcAngle(e, st);
5895
- if (ang == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
5896
- if (pg.startScalar == null) { pg.startScalar = ang; pg.prevAng = ang; return; } // grab was edge-on → set the reference on the first valid hit
5897
- if (pg.prevAng == null) pg.prevAng = ang;
5898
- // Accumulate the arc CONTINUOUSLY (shortest-arc step per move) so dragging across the ±180° seam adds a
5899
- // small increment instead of the ~2π jump a bare (ang − start) makes near the seam. The running total is
5900
- // the true swept angle, so the value tracks the hand monotonically and renormalizes only on commit.
5901
- pg.accumRad += unwrapAngleStep(pg.prevAng, ang); pg.prevAng = ang;
5902
- // Snap the DELTA, not the absolute value: since 3b.2 the resting roll is re-expressed into the current
5903
- // frame and is generically off-grid (e.g. 33.71°), so snapping the absolute would yank the steel to the
5904
- // 5° grid on the very first drag tick (a jump at drag-START). Stepping the delta keeps the value at the
5905
- // member's own roll when Δ=0 and moves in 5° increments from there.
5906
- const rawDeltaDeg = pg.accumRad * 180 / Math.PI;
5907
- const deg = pg.base + (e.shiftKey ? rawDeltaDeg : snapToStep(rawDeltaDeg, POS_SNAP_DEG));
5908
- pg.newVal = deg;
5909
- if (mesh && pg.meshPos0 && pg.meshQuat0) { // exact live preview: roll about the reference-line anchor
5910
- const axis = new THREE.Vector3(st.xAxis[0], st.xAxis[1], st.xAxis[2]).normalize();
5911
- const roll = new THREE.Quaternion().setFromAxisAngle(axis, (deg - pg.base) * Math.PI / 180);
5912
- const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
5913
- mesh.position.copy(pg.meshPos0.clone().sub(O).applyQuaternion(roll).add(O));
5914
- mesh.quaternion.copy(roll.clone().multiply(pg.meshQuat0));
6505
+ if (pg.refline) { onMoveRefLineGizmo(e, pg, st, mesh); return; }
6506
+ const ang = posGizmoArcAngle(e, st);
6507
+ if (ang == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6508
+ if (pg.startScalar == null) { pg.startScalar = ang; pg.prevAng = ang; return; } // grab was edge-on → set the reference on the first valid hit
6509
+ if (pg.prevAng == null) pg.prevAng = ang;
6510
+ // Accumulate the arc CONTINUOUSLY (shortest-arc step per move) so dragging across the ±180° seam adds a
6511
+ // small increment instead of the ~2π jump a bare (ang − start) makes near the seam. The running total is
6512
+ // the true swept angle, so the value tracks the hand monotonically and renormalizes only on commit.
6513
+ pg.accumRad += unwrapAngleStep(pg.prevAng, ang); pg.prevAng = ang;
6514
+ // Snap the DELTA, not the absolute value: since 3b.2 the resting roll is re-expressed into the current
6515
+ // frame and is generically off-grid (e.g. 33.71°), so snapping the absolute would yank the steel to the
6516
+ // 5° grid on the very first drag tick (a jump at drag-START). Stepping the delta keeps the value at the
6517
+ // member's own roll when Δ=0 and moves in 5° increments from there.
6518
+ const rawDeltaDeg = pg.accumRad * 180 / Math.PI;
6519
+ const deg = pg.base + (e.shiftKey ? rawDeltaDeg : snapToStep(rawDeltaDeg, POS_SNAP_DEG));
6520
+ pg.newVal = deg;
6521
+ if (mesh && pg.meshPos0 && pg.meshQuat0) { // exact live preview: roll about the reference-line anchor
6522
+ const axis = new THREE.Vector3(st.xAxis[0], st.xAxis[1], st.xAxis[2]).normalize();
6523
+ const roll = new THREE.Quaternion().setFromAxisAngle(axis, (deg - pg.base) * Math.PI / 180);
6524
+ const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
6525
+ mesh.position.copy(pg.meshPos0.clone().sub(O).applyQuaternion(roll).add(O));
6526
+ mesh.quaternion.copy(roll.clone().multiply(pg.meshQuat0));
6527
+ }
6528
+ setPositionLive(livePositionState(st, 'rot', deg)); // the gizmo's own profile axes turn WITH the roll being dragged
6529
+ { const O = st.anchor, R = POS_ARC_R.rot * positionGizmoScale(new THREE.Vector3(O[0], O[1], O[2])), c = Math.cos(ang), s2 = Math.sin(ang), P = posProfileAxes(st);
6530
+ updatePositionLeader([O[0] + (P.y[0] * c + P.z[0] * s2) * R, O[1] + (P.y[1] * c + P.z[1] * s2) * R, O[2] + (P.y[2] * c + P.z[2] * s2) * R]); }
6531
+ positionGizmoReadout(e, 'Rotation ' + Math.round(deg) + '°', ''); // label-first, to match the Inspect panel's "Rotation" row
6532
+ }
6533
+ /*
6534
+ * The gestures that move the member's WORK POINTS — the three translates and the two swings. The live
6535
+ * preview is a RIGID transform of the existing mesh: a translation, or one rotation about the anchor.
6536
+ * Nothing is rebuilt mid-drag, which is also why the view never has to freeze the depth face: a rigid
6537
+ * transform cannot re-derive it. The fold is decided once, at commit, in the editor.
6538
+ *
6539
+ * Every gesture reports a DELTA (mm along the axis, or radians about the frozen axis); `onUp` turns that
6540
+ * into absolute world work points through the same pure helpers the tests exercise.
6541
+ */
6542
+ function onMoveRefLineGizmo(e, pg, st, mesh) {
6543
+ // The member axis going edge-on collapses the slide arrow AND both arc planes at once. Refuse rather than
6544
+ // let mm-per-pixel run away, matching the shipped depth/width refusal word for word. Measured on the
6545
+ // FROZEN drag-start geometry — the drawn handles are travelling with the gesture, and a guard that
6546
+ // followed them would re-answer "is this axis foreshortened" about geometry the drag itself is moving,
6547
+ // stalling a legal drag the moment its projection crossed the threshold.
6548
+ const scr = positionGizmoHandlesScreen(st);
6549
+ const trans = pg.axis === 'slide' || pg.axis === 'depth' || pg.axis === 'width';
6550
+ if (trans && pg.axis !== 'slide') {
6551
+ const tip = pg.axis === 'depth' ? scr && scr.depthTip : scr && scr.widthTip;
6552
+ if (scr && tip && !tip.behind && Math.hypot(tip.x - scr.anchor.x, tip.y - scr.anchor.y) < posEdgeOnPx(_posAnchorV.set(st.anchor[0], st.anchor[1], st.anchor[2]), st)) {
6553
+ positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return;
5915
6554
  }
5916
- { 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);
5917
- 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]); }
5918
- positionGizmoReadout(e, 'Rotation ' + Math.round(deg) + '°', ''); // label-first, to match the Inspect panel's "Rotation" row
5919
- return;
5920
- }
5921
- // depth / width: refuse an edge-on axis (a foreshortened axis inflates mm-per-pixel without bound).
5922
- const scr = positionGizmoHandlesScreen();
5923
- const tip = scr && (pg.axis === 'depth' ? scr.depthTip : scr.widthTip);
5924
- if (scr && tip && !tip.behind && Math.hypot(tip.x - scr.anchor.x, tip.y - scr.anchor.y) < POS_EDGE_ON_PX) {
6555
+ } else if (scr && scr.anchor && scr.slideTip && !scr.slideTip.behind
6556
+ && Math.hypot(scr.slideTip.x - scr.anchor.x, scr.slideTip.y - scr.anchor.y) < posEdgeOnPx(_posAnchorV.set(st.anchor[0], st.anchor[1], st.anchor[2]), st)) {
5925
6557
  positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return;
5926
6558
  }
5927
- const s = posGizmoAxisScalar(e, st, pg.axis === 'depth' ? st.zAxis : st.yAxis);
5928
- if (s == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
5929
- if (pg.startScalar == null) { pg.startScalar = s; return; } // grab was edge-on → set the reference on the first valid hit (mirrors the rot arm)
5930
- // Snap the DELTA, not the absolute (see the rot arm): a base offset need not be grid-aligned — since 3b.2
5931
- // it commonly is not — so snapping the absolute would jump to the ¼" grid on the first tick. Stepping the
5932
- // delta holds the value at the member's own offset when Δ=0.
5933
- const rawDeltaMm = s - pg.startScalar;
5934
- const val = pg.base + (e.shiftKey ? rawDeltaMm : snapToStep(rawDeltaMm, POS_SNAP_MM));
5935
- pg.newVal = val;
5936
- { const O = st.anchor, ax = pg.axis === 'depth' ? st.zAxis : st.yAxis; // leader to the drag point on this axis
5937
- updatePositionLeader([O[0] + ax[0] * s, O[1] + ax[1] * s, O[2] + ax[2] * s]); }
5938
- if (mesh && pg.meshPos0) { // exact live preview: the SAME swing the bake uses (positionSwingDelta), so the steel never jumps on release
5939
- const w = positionSwingDelta({ y: st.yAxis, z: st.zAxis }, pg.axis, val - pg.base, st.rot || 0);
5940
- mesh.position.set(pg.meshPos0.x + w[0], pg.meshPos0.y + w[1], pg.meshPos0.z + w[2]);
5941
- }
5942
- const shownVal = api && api.fmtLen ? api.fmtLen(val) : Math.round(val) + ' mm';
5943
- positionGizmoReadout(e, (pg.axis === 'depth' ? 'Depth ' : 'Width ') + shownVal, ''); // label-first + panel's own unit (fmtLen), to match the Inspect panel exactly
6559
+ if (trans) {
6560
+ // `ax` is used raw here while the commit normalises inside translateEndpoints. Safe because every
6561
+ // axis this can return is unit — partFrame is orthonormal and rolledProfileAxes is a rotation of it,
6562
+ // which steel-3d-core's own test pins — so preview and commit cannot diverge.
6563
+ const ax = pg.transAxis || posTranslateAxis(st, pg.axis);
6564
+ const s = posGizmoAxisScalar(e, st, ax);
6565
+ if (s == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6566
+ if (pg.startScalar == null) { pg.startScalar = s; return; } // grab was edge-on → set the reference on the first valid hit
6567
+ const raw = s - pg.startScalar;
6568
+ const delta = e.shiftKey ? raw : snapToStep(raw, POS_SNAP_MM);
6569
+ pg.newVal = delta;
6570
+ if (mesh && pg.meshPos0) {
6571
+ mesh.position.set(pg.meshPos0.x + ax[0] * delta, pg.meshPos0.y + ax[1] * delta, pg.meshPos0.z + ax[2] * delta);
6572
+ }
6573
+ setPositionLive(livePositionState(st, pg.axis, delta, ax));
6574
+ updatePositionLeader([st.anchor[0] + ax[0] * s, st.anchor[1] + ax[1] * s, st.anchor[2] + ax[2] * s]);
6575
+ // Label-first, and each one names its own axis: three arrows that all translate the line would be
6576
+ // indistinguishable in the readout if they all just said "Move".
6577
+ const word = pg.axis === 'slide' ? 'Slide ' : pg.axis === 'depth' ? 'Depth ' : 'Width ';
6578
+ positionGizmoReadout(e, word + (api && api.fmtLen ? api.fmtLen(delta) : Math.round(delta) + ' mm'), '');
6579
+ return;
6580
+ }
6581
+ // --- swing: rotate the member DIRECTION about the frozen axis, moving only the far work point.
6582
+ const ang = posSwingAngle(e, st, pg.swingAxis, pg.basis);
6583
+ if (ang == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6584
+ if (pg.startScalar == null) { pg.startScalar = ang; pg.prevAng = ang; return; }
6585
+ if (pg.prevAng == null) pg.prevAng = ang;
6586
+ // Accumulate CONTINUOUSLY, as the shipped roll arc does, so crossing the ±180° seam adds an increment
6587
+ // rather than ~2π. Then snap the DELTA (the member's own heading is generically off-grid, so snapping an
6588
+ // absolute would yank the steel to the 5° grid on the very first tick).
6589
+ pg.accumRad += unwrapAngleStep(pg.prevAng, ang); pg.prevAng = ang;
6590
+ let theta = e.shiftKey ? pg.accumRad : snapToStep(pg.accumRad * 180 / Math.PI, POS_SNAP_DEG) * Math.PI / 180;
6591
+ if (pg.barriers) {
6592
+ const c = clampSwingTheta(theta, pg.barriers, e.shiftKey ? 'free' : 'snapped', POS_SNAP_DEG * Math.PI / 180);
6593
+ 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
6594
+ theta = c.theta; pg.clamped = c.clamped;
6595
+ }
6596
+ pg.newVal = theta;
6597
+ if (mesh && pg.meshPos0 && pg.meshQuat0) { // exact rigid preview: one rotation about the anchor
6598
+ const axis = new THREE.Vector3(pg.swingAxis[0], pg.swingAxis[1], pg.swingAxis[2]).normalize();
6599
+ const q = new THREE.Quaternion().setFromAxisAngle(axis, theta);
6600
+ const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
6601
+ mesh.position.copy(pg.meshPos0.clone().sub(O).applyQuaternion(q).add(O));
6602
+ mesh.quaternion.copy(q.clone().multiply(pg.meshQuat0));
6603
+ }
6604
+ setPositionLive(livePositionState(st, pg.axis, theta, pg.swingAxis));
6605
+ const tip = swingEndpoint(st.anchor, st.end, pg.swingAxis, theta);
6606
+ if (tip) updatePositionLeader(tip);
6607
+ const degRaw = theta * 180 / Math.PI;
6608
+ 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
6609
+ // "Swing" and "Tilt", never "Rotation" — that label belongs to the roll arc, and reusing it would blur
6610
+ // which of the two red-family handles is live mid-drag.
6611
+ positionGizmoReadout(e, (pg.axis === 'swingPlan' ? 'Swing ' : 'Tilt ') + deg + '°' + (pg.clamped ? ' (limit)' : ''), '');
5944
6612
  }
5945
6613
  // --- frame manipulator: grab + drag the gizmo's origin (translate) or ring (rotate about Z). Armed only. ---
5946
6614
  const FRAME_RING_R = (1524 * 2 / 2) * 0.8; // ring radius (matches renderFrameGizmo's half*0.8, N=2)
@@ -6130,7 +6798,7 @@ function renderWorkPlane() {
6130
6798
  function reflectWpBar() { const b = document.getElementById('m3dWp'); if (b) { b.classList.toggle('on', !!wpMode || !!workPlane);
6131
6799
  const kind = workPlane && workPlane.kind ? { face: 'Face', p3: '3pt', xy: 'XY', xz: 'XZ', yz: 'YZ' }[workPlane.kind] || '' : '';
6132
6800
  b.textContent = wpMode ? '◇ Plane ✕' : (kind ? '◇ Plane: ' + kind + ' ▾' : '◇ Plane ▾'); } reflectDimAxisBar(); } // the label reads the active plane without opening the menu (ux review); relabel the dim-axis bar (a set/cleared plane flips X/Y between World and local)
6133
- function armWorkPlanePick(mode) { if (wpMode === mode) { wpMode = null; wpDraft = null; } else { wpMode = mode; wpDraft = null; dropGridLinePick3d(); dropRefMeasure3d(); if (dimMode3d) toggleDimTool(); if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); cmClear3d(); drClear3d(); disarmFrame3d(); } marker.visible = false; canvasEl.style.cursor = wpMode ? 'crosshair' : 'default'; reflectWpBar(); updateStatusChip(); } // a set-plane pick shares the left-click — disarm Move/Copy + Add + the local frame (their onDown routes run first)
6801
+ function armWorkPlanePick(mode) { abandonConnPick('other-tool'); if (wpMode === mode) { wpMode = null; wpDraft = null; } else { wpMode = mode; wpDraft = null; dropGridLinePick3d(); dropRefMeasure3d(); if (dimMode3d) toggleDimTool(); if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); cmClear3d(); drClear3d(); disarmFrame3d(); } marker.visible = false; canvasEl.style.cursor = wpMode ? 'crosshair' : 'default'; reflectWpBar(); updateStatusChip(); } // a set-plane pick shares the left-click — disarm Move/Copy + Add + the local frame (their onDown routes run first)
6134
6802
  function setWorkPlanePrincipal(kind, offsetMm) {
6135
6803
  const off = offsetMm || 0;
6136
6804
  const def = { xy: { normal: [0, 0, 1], xAxis: [1, 0, 0] }, xz: { normal: [0, 1, 0], xAxis: [1, 0, 0] }, yz: { normal: [1, 0, 0], xAxis: [0, 1, 0] } }[kind];
@@ -6644,6 +7312,7 @@ function onDown(e) {
6644
7312
  if (addActive()) { e.stopPropagation(); controls.enabled = true; drClick(e); return; } // Add-member armed (editor state) → two plane picks draw a member
6645
7313
  if (cmActive()) { if (tfClick(e)) { e.stopPropagation(); controls.enabled = true; return; } } // Move/Copy armed (editor state) → picks land on the working plane; an empty-selection click falls through to select
6646
7314
  if (basePickCol) { e.stopPropagation(); const r = basePickPoint(e.clientX, e.clientY); if (r) { if (api && api.onBasePick) api.onBasePick(r); setBasePickMode(null); } return; } // Mode B: commit + disarm only on a valid on-column pick; an off-column click is ignored (stays armed) — Esc cancels
7315
+ if (connPick) { e.stopPropagation(); const r = insertPick(e.clientX, e.clientY); connPickToggle(r && r.anchorId); return; } // armed: clicking a member toggles it into the set this connection is recorded against
6647
7316
  if (insertMode) { e.stopPropagation(); const r = insertPick(e.clientX, e.clientY); const sticky = insertPending && insertPending.sticky; if (r && api && api.onInsertPlace) api.onInsertPlace(r, insertPending); if (!sticky) setInsertMode(false); return; } // armed: place at the pick. One-shot for a detail / IFC import; a sticky pending (a favourite) STAYS armed for repeat placement — Esc/onInsertPlace's own cancel disarms.
6648
7317
  if (clipMode === 'plane') { e.stopPropagation(); if (addClipPlaneAtScreen(e.clientX, e.clientY)) setClipMode(null); return; } // armed: left-click a face → place ONE clip plane, then the command is done (a miss keeps it armed to try again)
6649
7318
  if (clipMode === 'box') { e.stopPropagation(); onClipBoxClick(e); return; } // armed: 2-corner clip-box draw on the floor plane
@@ -6721,6 +7390,14 @@ function onDown(e) {
6721
7390
  if (positionGizmoVisible && posGizmoState) {
6722
7391
  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)
6723
7392
  if (pgh) { e.stopPropagation(); controls.enabled = false; startPositionGizmoDrag(pgh, e); if (pending) return; }
7393
+ // The amber anchor is not draggable, but a press on it must not COST the user their selection either.
7394
+ // The dot floats half a section depth above the steel, so a click there usually misses the member mesh
7395
+ // and reaches empty space — which clears the selection and takes the whole gizmo with it. That was
7396
+ // survivable while the dot was silent; now that it explains itself on hover, people click it. So
7397
+ // consume the gesture and stay put, exactly as a filtered grid does. A drag past the tolerance still
7398
+ // becomes a marquee (below), so an 11px dot cannot blanket-block box selection.
7399
+ let onAnchorDown = false; try { onAnchorDown = pickPositionAnchorHover(e.clientX, e.clientY); } catch (err) { console.error('steel-3d: position-anchor hit-test failed', err); onAnchorDown = false; }
7400
+ if (onAnchorDown) { e.stopPropagation(); controls.enabled = false; pending = { posAnchor: true }; return; }
6724
7401
  }
6725
7402
  let id = null; try { id = pickAt(e.clientX, e.clientY); } catch { id = null; }
6726
7403
  // Geometry-edit mode (Trim/Extend or Split armed in the inspector): a click does the edit, no drag.
@@ -6990,7 +7667,7 @@ function onMove(e) {
6990
7667
  if (pending && pending.frameDrag) { onMoveFrame(e); return; } // dragging the local-frame origin / rotation ring
6991
7668
  if (pending && pending.posGizmo) { onMovePositionGizmo(e); return; } // dragging a Profile Position handle (depth/width offset or roll)
6992
7669
  if (!pending || pending.geo) return;
6993
- 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
7670
+ 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
6994
7671
  if (pending.epDrag) { onMoveEndpoint(e); return; }
6995
7672
  if (!pending.grab || !pending.origMm) return;
6996
7673
  if (!dragging && Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]) <= DRAG_TOL_PX) return;
@@ -7174,25 +7851,53 @@ function onUp(e) {
7174
7851
  controls.enabled = true;
7175
7852
  const moved = downXY ? Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]) : Infinity; downXY = null;
7176
7853
  if (!p) return;
7177
- if(p.filteredGrid||p.filteredReference)return;
7854
+ if(p.filteredGrid||p.filteredReference||p.posAnchor)return; // an anchor-dot press is inert BY DESIGN: no drag, and no selection change either
7178
7855
  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;}
7179
7856
  if (p.clipDrag) return; // a clip handle drag is applied live during onMoveClip; nothing to commit on up (controls re-enabled above)
7180
7857
  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)
7181
7858
  if (p.posGizmo) { // Profile Position handle → commit the ABSOLUTE new offset/roll through the editor (one undo entry)
7182
7859
  if (readout) readout.style.display = 'none';
7183
7860
  hidePositionLeader();
7184
- posInteraction = 'idle';
7861
+ endPositionGesture();
7185
7862
  const pg = p.posGizmo;
7186
- // rot is compared by ANGULAR equality (mod 360): a drag that loops the arc back to the member's own roll
7187
- // (Δ = 360°) reads as no move and must commit nothing / push no undo entry (Fable 5 test 1). depth/width
7188
- // stay a linear compare.
7189
- const moved = pg.axis === 'rot'
7190
- ? Math.abs((((pg.newVal - pg.base) % 360) + 540) % 360 - 180) > 1e-6 // shortest angular distance (deg) from base
7191
- : Math.abs(pg.newVal - pg.base) > 1e-9;
7863
+ if (pg.refline) { // the handles that move the WORK POINTS, committed as absolute world mm
7864
+ const st = pg.state;
7865
+ const moved = pg.newVal != null && Math.abs(pg.newVal) > 1e-12;
7866
+ if (wasDragging && moved && api && api.commitMemberEndpoints) {
7867
+ // Rebuild the absolute points from the FROZEN drag-start geometry and the total delta, through the
7868
+ // same pure helpers the unit tests pin — never from whatever the mesh preview happens to show.
7869
+ let spec = null;
7870
+ const tax = posTranslateAxis(st, pg.axis);
7871
+ if (tax) {
7872
+ // All three translates share one helper and one gesture policy: the reference line keeps its
7873
+ // direction and its length whichever axis it moves along, so `commitMemberEndpoints` need only
7874
+ // check that partFrame's BRANCH is unchanged. 'slide' keeps its own name because the readout,
7875
+ // the tooltip and the depth-pin diagnostics all say it.
7876
+ const r = translateEndpoints(st.anchor, st.end, tax, pg.newVal);
7877
+ if (r) spec = { from: r.from, to: r.to, gesture: pg.axis === 'slide' ? 'slide' : 'translate', expect: st.fingerprint };
7878
+ } else {
7879
+ const to = swingEndpoint(st.anchor, st.end, pg.swingAxis, pg.newVal);
7880
+ if (to) spec = { to, gesture: pg.axis, expect: st.fingerprint };
7881
+ }
7882
+ if (!spec) console.warn('steel-3d: a reference-line gesture produced no commit — geometry helper returned null', pg.axis, pg.newVal);
7883
+ // The editor's own refusals toast; a THROW here (a member the world-mm primitive cannot address)
7884
+ // would otherwise escape this pointer handler and strand the moved preview over an unchanged model,
7885
+ // which is precisely the failure the primitive's own comment set out to prevent.
7886
+ let ok = false;
7887
+ try { ok = !!(spec && api.commitMemberEndpoints(pg.id, spec, null)); }
7888
+ catch (err) { console.error('steel-3d: reference-line commit failed', err); ok = false; }
7889
+ if (!ok) { restorePositionGizmoMesh(pg); renderPositionGizmo(); } // refused (stale gesture, unknown elevation, a frame it would break) → put the preview back
7890
+ } else { restorePositionGizmoMesh(pg); renderPositionGizmo(); }
7891
+ return;
7892
+ }
7893
+ // Only the ROLL reaches here: it is the last handle that writes a stored member field instead of moving
7894
+ // the work points, so this is the 3D view's last call to commitMemberPosition. It is compared by ANGULAR
7895
+ // equality (mod 360), because a drag that loops the arc back to the member's own roll (Δ = 360°) reads
7896
+ // as no move and must commit nothing / push no undo entry (Fable 5 test 1).
7897
+ const moved = Math.abs((((pg.newVal - pg.base) % 360) + 540) % 360 - 180) > 1e-6; // shortest angular distance (deg) from base
7192
7898
  if (wasDragging && pg.newVal != null && moved && api && api.commitMemberPosition) {
7193
- const key = pg.axis === 'depth' ? 'positionOffset' : pg.axis === 'width' ? 'positionHOffset' : 'rot';
7194
- const val = pg.axis === 'rot' ? rollCommitNorm(pg.newVal) : pg.newVal; // fold the accumulated/off-grid roll to the panel's stored convention
7195
- const ok = api.commitMemberPosition(pg.id, { [key]: val }, null); // editor's edit() rebuilds → renderPositionGizmo re-anchors
7899
+ const val = rollCommitNorm(pg.newVal); // fold the accumulated/off-grid roll to the panel's stored convention
7900
+ const ok = api.commitMemberPosition(pg.id, { rot: val }, null); // editor's edit() rebuilds → renderPositionGizmo re-anchors
7196
7901
  if (!ok) { restorePositionGizmoMesh(pg); renderPositionGizmo(); } // refused (e.g. frame drifted) → snap the live preview back
7197
7902
  } else { restorePositionGizmoMesh(pg); renderPositionGizmo(); } // no net move or a plain click → restore the preview
7198
7903
  return;
@@ -7369,11 +8074,23 @@ function onHoverMove(e) {
7369
8074
  // tooltip. Mirrors onDown precedence (the handle sits ON the member and wins over the passive frame origin).
7370
8075
  if (positionGizmoVisible && posGizmoState && !frameMode && posInteraction !== 'typing') {
7371
8076
  let ph = null; try { ph = pickPositionGizmoHandle(lastHoverXY[0], lastHoverXY[1]); } catch { ph = null; }
7372
- if (ph) { canvasEl.style.cursor = 'grab';
8077
+ // setPositionHover owns BOTH the amber repaint and the grab cursor — colour, cursor and tooltip are
8078
+ // three redundant channels for the same fact, so the highlight never rests on hue alone.
8079
+ if (ph) { setPositionHover(ph);
7373
8080
  if (api && api.showHandleTip) api.showHandleTip(POS_HANDLE_TIP[ph], lastHoverXY[0], lastHoverXY[1]);
7374
8081
  posHovered = true; return; }
8082
+ // The anchor is hover-only: it explains itself but never arms a drag, so it is checked here and NOT
8083
+ // in pickPositionGizmoHandle. Cursor stays default — a grab cursor would promise a drag that a
8084
+ // mousedown here does not perform (it falls through to click-select, as it always has).
8085
+ let onAnchor = false; try { onAnchor = pickPositionAnchorHover(lastHoverXY[0], lastHoverXY[1]); } catch { onAnchor = false; }
8086
+ // The anchor brightens rather than turning amber: it IS amber already, and two near-identical ambers
8087
+ // read as no change at all — while a grab cursor would promise a drag it does not perform.
8088
+ if (onAnchor) { setPositionHover('anchor');
8089
+ if (api && api.showHandleTip) api.showHandleTip(POS_HANDLE_TIP.anchor, lastHoverXY[0], lastHoverXY[1]);
8090
+ posHovered = true; return; }
8091
+ setPositionHover(null);
7375
8092
  if (posHovered) { posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); }
7376
- } else if (posHovered) { posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); } // gizmo disappeared while a tip was up
8093
+ } else if (posHovered) { setPositionHover(null); posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); } // gizmo disappeared while a tip was up
7377
8094
  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"
7378
8095
  let fh = null; try { fh = pickFrameHandle(lastHoverXY[0], lastHoverXY[1], true); } catch { fh = null; }
7379
8096
  if (fh) { canvasEl.style.cursor = 'pointer'; return; }
@@ -7420,6 +8137,12 @@ function instructorCommand() {
7420
8137
  if (refMeasure3d) return { armed: 'steel.reference-measure', step: refMeasure3d.a ? 1 : 0 };
7421
8138
  if (framePickStep() != null) return { armed: 'steel.local-frame', step: framePickStep() };
7422
8139
  if (frameMode) return { armed: 'steel.frame-adjust', step: 0 };
8140
+ if (connPick) return { armed: 'steel.connection-members', step: connPick.chosen.size ? 1 : 0 };
8141
+ /* BEFORE the generic insert line, because a re-placement arms through the same insert mode and would
8142
+ otherwise narrate "Place a detail" — the wrong action, with the wrong steps and the wrong Esc. It
8143
+ covers the CROSSHAIR stage only; once the point is accepted the pick above takes over and
8144
+ `steel.connection-members` narrates naming the members. (Found by review.) */
8145
+ if (insertMode && insertPending && insertPending.kind === 'connection-replace') return { armed: 'steel.connection-replace', step: 0 };
7423
8146
  if (insertMode) return { armed: 'steel.insert-detail', step: 0 };
7424
8147
  if (basePickCol) return { armed: 'steel.base-pick', step: 0 };
7425
8148
  if (gridLinePick3d) return { armed: 'steel.grid-line', step: gridLinePick3d.a ? 1 : 0 };
@@ -7463,6 +8186,14 @@ function armedStepText(commandId) {
7463
8186
  if (commandId && g.commandId && g.commandId !== commandId) return null;
7464
8187
  return g.parts[0];
7465
8188
  }
8189
+ /* How many members the connection pick holds. Live state this canvas owns — the same boundary the
8190
+ host-drag badge sits on — and the only running feedback the step gives, so it appears in the rich
8191
+ and the degraded readout alike. */
8192
+ function pickedCountTxt(armed) {
8193
+ if (armed !== 'steel.connection-members' || !connPick || !connPick.chosen.size) return '';
8194
+ const n = connPick.chosen.size;
8195
+ return ` · ${n} member${n === 1 ? '' : 's'} picked`;
8196
+ }
7466
8197
  function updateStatusChip() {
7467
8198
  if (!hoverChip || !canvasEl) return;
7468
8199
  const rect = canvasEl.getBoundingClientRect();
@@ -7475,6 +8206,7 @@ function updateStatusChip() {
7475
8206
  gridLinePickActive: !!gridLinePick3d, clipMode, dimensionMode: dimMode3d,
7476
8207
  dimensionHasStart: !!dimDraft3d, insertMode, insertName: insertPending && insertPending.name,
7477
8208
  basePickColumn: basePickCol, frameMode, framePickStep: framePickStep(), geometryMode: geoMode(),
8209
+ connectionMemberPick: !!connPick, connectionMemberPickCount: connPick ? connPick.chosen.size : 0,
7478
8210
  });
7479
8211
  const forceOpen = toolGuidance.forceOpen;
7480
8212
  const selectionStatus=objectSelectionStatus(selIds.size,selectedGridIds.size),showId=hoverId||(!selectionStatus&&selIds.size===1?[...selIds][0]:null);
@@ -7507,10 +8239,17 @@ function updateStatusChip() {
7507
8239
  drag = ` · ${n} ${n === 1 ? 'member' : 'members'}`
7508
8240
  + (teklaDrag.target ? ` · over ${HOST_SHORT[teklaDrag.target]}` : '');
7509
8241
  }
7510
- txt = stepTxt + suffix + kept + drag + ' · Esc to cancel';
8242
+ /* The picked count is live state this canvas owns — the same boundary the drag badge sits on, and
8243
+ deliberately not in the registry step. */
8244
+ const meta3d = window.Commands && window.Commands.get(cmd3d.armed);
8245
+ const escRoute3d = (meta3d && meta3d.escLabel) || (cmd3d.armed === 'steel.connection-members' ? 'Esc to skip' : 'Esc to cancel');
8246
+ txt = stepTxt + suffix + kept + drag + pickedCountTxt(cmd3d.armed) + ' · ' + escRoute3d;
7511
8247
  }
7512
8248
  else if (cmd3d) { const meta = window.Commands && window.Commands.get(cmd3d.armed);
7513
- txt = (meta ? meta.label : cmd3d.armed) + ' · Esc to cancel'; } // reporter-unavailable fallback
8249
+ // The registry may be unreachable here, so the safe route for THIS command is a literal: its Esc
8250
+ // commits an unwatched connection, and a fallback saying "cancel" promises an undo that cannot happen.
8251
+ const escRoute = (meta && meta.escLabel) || (cmd3d.armed === 'steel.connection-members' ? 'Esc to skip' : 'Esc to cancel');
8252
+ txt = (meta ? meta.label : cmd3d.armed) + pickedCountTxt(cmd3d.armed) + ' · ' + escRoute; } // reporter-unavailable fallback
7514
8253
  else if (toolGuidance.text) txt = toolGuidance.text;
7515
8254
  else if (showId) { const m = memberById(showId); txt = m ? `${m.id} · ${m.profile || '—'}` : ''; }
7516
8255
  else if (selectionStatus) txt = selectionStatus;
@@ -7545,6 +8284,7 @@ function updateStatusChip() {
7545
8284
  // short stalls would add up into one bogus warning.
7546
8285
  function show() { camFramed = camFitted; unframedFrames = 0; unframedWarned = false; if (controls) controls.enabled = true; if (canvasEl) { canvasEl.style.display = 'block'; resize(); } if (!rafId) loop(); updateStatusChip(); refreshDims(); refreshOverlayDims(); renderFrameGizmo(); } // resume the render loop (reset orbit in case a gesture was stranded by a mid-drag hide)
7547
8286
  function hide() {
8287
+ abandonConnPick('left-3d'); // Enter/Esc cannot reach an armed pick once this canvas is hidden
7548
8288
  invalidatePointEntry('hide'); // leaving 3D → drop any open typed entry + stale base/start
7549
8289
  if (dimMode3d) toggleDimTool(); // disarm the dim tool + sync its toolbar (no stale draft/armed state on return)
7550
8290
  // …and the reference measure, through the editor so its panel card goes with it. Routed via
@@ -7563,11 +8303,18 @@ function hide() {
7563
8303
  }
7564
8304
  // The editor's active-pane state, pushed in. Defaults true so every existing caller — and vector-3d.html,
7565
8305
  // which has no split and never calls this — keeps today's behaviour with no change.
7566
- function setInputActive(on) { inputActive = on !== false; }
8306
+ function setInputActive(on) { inputActive = on !== false; if (!inputActive) abandonConnPick('pane-inactive'); }
7567
8307
  function isReady() { return built; }
7568
8308
 
7569
8309
  function dispose() {
7570
8310
  positionBasisListeners.clear();
8311
+ /* THROUGH abandonConnPick, not `connPick = null`. A re-placement transaction in the editor AWAITS this
8312
+ pick's settlement and holds the write gate until it comes; clearing the state without firing the
8313
+ callback left that promise unresolved forever, which disabled saving for the rest of the session —
8314
+ strictly worse than the torn placement the gate exists to prevent. Teardown is a settle path like
8315
+ Enter, Esc and a pane switch, and the only one that used to stay silent. (Codex code review.) */
8316
+ abandonConnPick('disposed');
8317
+ connPick = null;
7571
8318
  // Stage D, torn down like every sibling overlay above. Without it a re-init() mints a fresh line and
7572
8319
  // label while refMeasure3d still reports armed:true against a reference id from the previous
7573
8320
  // session — a chip asking for a first point over a scene where every click is a no-op.
@@ -7645,7 +8392,16 @@ function dispose() {
7645
8392
  clearRoot();
7646
8393
  if (workAreaHelper) { if (overlayScene) overlayScene.remove(workAreaHelper); workAreaHelper.geometry.dispose(); workAreaHelper.material.dispose(); workAreaHelper = null; }
7647
8394
  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)
7648
- 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)
8395
+ clearConnEnvelope(); clearClipGizmo(); setClipPreview(null); setClipPlanePreview(null); disposeFramePreview(); disposeFrameGizmo();
8396
+ /* MODULE state, not scene state: disposing the objects leaves posInteraction/posActiveHandle/posLiveState
8397
+ exactly as the gesture left them, and init() mints a fresh view around them — which would come up with
8398
+ orbit disabled and a handle already amber. End the gesture before dropping the scene it belonged to.
8399
+ `pending`/`dragging`/`downXY` go with it: they hold the OLD gesture's frozen state and meshes, and
8400
+ onMove dispatches on `pending.posGizmo` — so a first pointer move after re-init would resume a drag
8401
+ against a scene that no longer contains the member it was computed from. */
8402
+ endPositionGesture(); posHoverHandle = null; posHovered = false;
8403
+ pending = dragging = null; downXY = null;
8404
+ disposePositionGizmo(); disposePositionLeader(); overlayScene = null; // dispose the clip/frame/position gizmo + leader + preview THREE resources before dropping the scene (Codex)
7649
8405
  clips = []; workArea = null; clipMode = null; selectedClipIds.clear(); clipBoxDraft = null; // clips live on the renderer; drop them with the renderer
7650
8406
  if (renderer) renderer.dispose();
7651
8407
  renderer = scene = camera = perspCam = orthoCam = controls = root = api = canvasEl = ro = null; built = false;
@@ -7812,9 +8568,16 @@ window.Steel3DView = {
7812
8568
  setProjection, projection, setDisplayMode, mode: () => displayMode, frameAll, frameSelection, applyView,
7813
8569
  setRefLine, refLine: () => refLineOn,
7814
8570
  setInsertMode, insertMode: insertModeOn, // arm/query the detail-placement pick (Slice 4)
8571
+ setConnMemberPick, connMemberPick: connMemberPickOn, connMemberPickJoint, // arm/query "name the members this connection joins"
8572
+ /* Exported because a whole-document flush in the editor cannot wait behind a human naming members —
8573
+ it settles the pick instead, which is the safe direction. (Found by review.) */
8574
+ abandonConnMemberPick: abandonConnPick,
7815
8575
  refreshStatus: updateStatusChip, // editor-owned armed modes (Extend/Trim, Split) refresh the disclosure immediately
7816
8576
  setBasePickMode, basePickMode: basePickModeOn, // arm/query the Mode B column-base pick (level-snapped elevation)
7817
8577
  selectWholeConn, clearConnSel, ascendConn, connContext, connEnvelopeOn: () => !!connEnvelope, // Connection Components (Slice A): whole-select / drill / ascend + test probes
8578
+ // Re-state the review lift on an already-built scene — the review state can move without the geometry
8579
+ // moving (a sign-off elsewhere, or the client re-deriving after its own edit), and neither rebuilds.
8580
+ setConnReview,
7818
8581
  // Reference models (#278) — an editor-only layer. `setReferences` takes the geometry the editor
7819
8582
  // fetched from the reference route; nothing here ever passes through contractToScene, which is what
7820
8583
  // keeps borrowed geometry out of every export by construction rather than by filtering.
@@ -7884,7 +8647,7 @@ window.Steel3DView = {
7884
8647
  workAreaSetAll, workAreaFromSelection, workAreaToggle, workAreaSetWhole, clearWorkArea, workAreaState,
7885
8648
  armWorkPlanePick, setWorkPlanePrincipal, clearWorkPlane, toggleWorkPlaneVisible, workPlaneInfo,
7886
8649
  armFrame3d, disarmFrame3d, repickFrame3d, setFrame3d, setFrameBasis, setFrameAngle, setFrameOrigin, clearFrame3d, frameInfo, positionAuthoringBasis: positionAuthoringBasisSnapshot, onPositionAuthoringBasisChange, frameArmed: () => frameMode, framePicking, framePickStep, frameHandlesScreen, // 3D local drawing frame (UCS stage 1)
7887
- 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
8650
+ setPositionGizmoVisible, positionGizmoHandlesScreen, memberWorldTransform, setPositionTyping, positionLeaderVisible, frameGizmoVisible, positionGizmoStyleProbe, // Profile Position gizmo (slice 3a/3b): ⋯ Display toggle + E2E grab-point + world-transform/leader/frame-gizmo probes + typed-HUD camera freeze
7888
8651
  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)
7889
8652
  cmEscape, cmHasBase, cmClear3d, setCmAxis, cmLastClient, cmHudApply,
7890
8653
  drHudApply, pointEntryBegin, pointEntryEnd, drHasStart: () => !!drDraft, // UCS stage 3: shared typed point-entry HUD (Move/Copy + Add)