@floless/app 0.134.1 → 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, slideEndpoints, swingBasis, swingEndpoint, swingBarriers, clampSwingTheta, POSITION_SWING_MARGIN_RAD, POSITION_OFFSET_SNAP_MM, POSITION_ROT_SNAP_DEG, POSITION_BASIS_CAPABILITY_VERSION } from './steel-3d-core.js';
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,11 +4767,14 @@ 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
4780
  const p = scr && (ph === 'depth' ? scr.depthTip : ph === 'width' ? scr.widthTip
@@ -4714,9 +4819,11 @@ function setSelection(ids) {
4714
4819
  if (String(id).startsWith('det:')) { if (mesh.material && mesh.material.color) mesh.material.color.setHex(on ? 0x93c5fd : 0xffffff); continue; }
4715
4820
  // Selected → a per-mesh clone that glows (so one selected member doesn't tint its whole profile
4716
4821
  // group). Deselected → back to the SHARED profile material (its real colour).
4717
- mesh.material = on ? selectedMaterial(mesh) : materialFor(mesh.userData.group, mesh.userData.family, mesh.userData.axis);
4718
- mesh.material.emissive = new THREE.Color(on ? SELECT_EMISSIVE : 0x000000);
4719
- 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; }
4720
4827
  }
4721
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
4722
4829
  applyDisplayMode(); // selection swapped the materials → re-apply wire/xray
@@ -4737,6 +4844,66 @@ function highlightClone(mesh) {
4737
4844
  if (tile) applyTriplanar(c, tile, DIRECTIONAL.has(mesh.userData.family) ? mesh.userData.axis : null);
4738
4845
  return c;
4739
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
+ }
4740
4907
  function selectedMaterial(mesh) {
4741
4908
  if (!mesh.userData._selMat) mesh.userData._selMat = highlightClone(mesh);
4742
4909
  return mesh.userData._selMat;
@@ -4753,9 +4920,11 @@ function setHoverGlow(id, on, sync = true) {
4753
4920
  const mesh = meshById.get(id);
4754
4921
  if (!mesh || String(id).startsWith('det:')) return; // placed details use a texture, no emissive to glow
4755
4922
  if (selIds.has(id)) return; // selected beats hovered — don't disturb its blue glow
4756
- mesh.material = on ? hoverMaterial(mesh) : materialFor(mesh.userData.group, mesh.userData.family, mesh.userData.axis);
4757
- mesh.material.emissive = new THREE.Color(on ? HOVER_EMISSIVE : 0x000000);
4758
- 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; }
4759
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.
4760
4929
  }
4761
4930
  // The ids that glow together when `id` is hovered: the WHOLE connection's parts (so hovering any part
@@ -5671,54 +5840,140 @@ function sizeFrameHandle() {
5671
5840
  }
5672
5841
 
5673
5842
  // ---- Profile Position gizmo (slice 3a) -----------------------------------------------------------
5674
- // A Tekla-shaped handle anchored to the SELECTED member's start work point: a blue depth arrow and a
5675
- // green width arrow drive the numeric offsets, a red arc about the member axis drives the roll. The
5676
- // editor owns the semantics (`api.positionGizmoState` / `api.commitMemberPosition`); the view only
5677
- // draws the arrows and, on a drag, reports an ABSOLUTE new value back. Lives in `overlayScene` (2nd
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
5678
5848
  // unclipped pass, `depthTest:false`) so a section plane never cuts it, and the whole group is scaled
5679
5849
  // screen-constant like the frame/clip handles — grabbable on a 6" stub and a 40' girder alike.
5680
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)
5681
5852
  let positionGizmoVisible = false; // the ⋯ Display-menu toggle, pushed in from the editor
5682
- let posGizmoState = null; // last api.positionGizmoState() snapshot for the single selection (anchor, axes, offsets)
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
5683
5863
  // Explicit interaction state consulted by every position-gizmo handler (drag/dblclick/keydown), instead of
5684
5864
  // trusting focus + stopPropagation (Fable 5 review): 'idle' | 'dragging' | 'typing'. 'typing' = the docked
5685
5865
  // numeric HUD is open (camera frozen); handlers that must not fire while typing check this and bail.
5686
5866
  let posInteraction = 'idle';
5687
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
5688
5870
  let positionLeader = null; // cyan #22d3ee rubber-band line: amber anchor → live drag point, shown for a whole drag
5689
- const POS_GIZMO_REACH_PX = 132; // screen-constant arrow reach (spec §3)
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']);
5690
5927
  // Per-handle hover copy — leads with the consequence (spec §3) + the double-click-to-type hint (3b.3). Shown
5691
5928
  // through the shared themed #tooltip (api.showHandleTip), never a native title=.
5692
5929
  const POS_HANDLE_TIP = {
5693
- depth: 'Slides the section along its depth axis. Drag, or double-click to type an exact value — ¼" snap; hold Shift for no snap.',
5694
- width: 'Slides the section along its width axis. Drag, or double-click to type an exact value — ¼" snap; hold Shift for no snap.',
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.',
5695
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.',
5696
- // Slice 3b.1 — the three that move the reference LINE (and so the member itself), not the profile on it.
5697
- // Each leads with that consequence, because it is the difference a detailer must not have to guess.
5698
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.',
5699
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.',
5700
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.',
5701
- // Was unreachable until 3b.1 (pickPositionGizmoHandle could only answer depth/width/rot), and its old
5702
- // wording — "This point never moves" — became false the moment the member-axis arrow shipped.
5703
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.',
5704
5940
  };
5705
- // The reference-line handles' geometry (ui-ux pass). BOTH swing arcs are inherently centred on the member
5706
- // axis — each rotates x̂ within its own plane — so at ±x̂ two same-radius arcs would COINCIDE and the
5707
- // screen-space nearest-point pick would be arbitrary. Hence two lobes per arc, flanking +x̂ only, with a
5708
- // dead zone over the axis itself: nearest arc point to the slide arrow's tip ≈42 px, plan lobe to elevation
5709
- // lobe ≈55 px, both clear of the 26 px combined pick tolerance. Nothing is lost by not drawing near −x̂
5710
- // (dragging the member "from behind" is not a real interaction), and the pointer may still be dragged past
5711
- // the drawn lobe — the arc is the affordance, not the limit.
5712
- const POS_SWING_R = 1.15; // both swing arcs, outside the 1.0 arrows and the 0.72 roll arc
5713
- const POS_LOBE_START = 1 / 12; // 15° off the member axis, in PI units
5714
- const POS_LOBE_SWEEP = 1 / 3; // ...through to 75°
5715
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
5716
- function disposePositionGizmo() {
5717
- hidePositionLeader(); // the transient drag leader never outlives a gizmo rebuild
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
5718
5964
  if (!positionGizmo) return;
5719
5965
  if (overlayScene) overlayScene.remove(positionGizmo);
5720
- positionGizmo.traverse((o) => { if (o.geometry) o.geometry.dispose(); if (o.material) o.material.dispose(); });
5721
- 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;
5722
5977
  }
5723
5978
  // The gizmo shows only when the toggle is on, exactly one member is selected, we are not in a work-plane
5724
5979
  // pick, and the editor reports the member as available (resolvable frame + offsets). Otherwise → null.
@@ -5736,72 +5991,164 @@ function currentPositionGizmoState() {
5736
5991
  if (st && st.reason) console.debug('steel-3d: Profile Position handle hidden —', st.reason);
5737
5992
  return null;
5738
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
+ }
5739
6023
  function renderPositionGizmo() {
5740
- 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';
5741
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);
5742
6045
  if (!st) return;
5743
6046
  const g = new THREE.Group();
5744
6047
  const V = (a) => new THREE.Vector3(a[0], a[1], a[2]);
5745
- const yv = V(st.yAxis), zv = V(st.zAxis);
5746
- // Built in LOCAL space with the anchor at (0,0,0): the group carries no rotation, so local coords ARE
5747
- // world offsets from the anchor, and scaling the whole group keeps every part screen-constant.
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. */
5748
6057
  const arrow = (dirArr, col, tag) => {
5749
- const d = V(dirArr).normalize();
5750
- const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(0, 0, 0), d.clone().multiplyScalar(1)]),
5751
- new THREE.LineBasicMaterial({ color: col }));
5752
- line.material.depthTest = false; line.renderOrder = 997; line.userData = { posHandle: tag, stem: true }; g.add(line);
5753
- const cone = new THREE.Mesh(new THREE.ConeGeometry(0.13, 0.36, 16), new THREE.MeshBasicMaterial({ color: col }));
5754
- cone.material.depthTest = false; cone.renderOrder = 998; cone.quaternion.setFromUnitVectors(_YA, d);
5755
- cone.position.copy(d.clone().multiplyScalar(1)); cone.userData = { posHandle: tag, arrow: true }; g.add(cone);
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);
5756
6094
  };
5757
- // BY DESIGN the arrows point along the UNROTATED part axes (st.zAxis/st.yAxis), because a Profile
5758
- // Position offset is defined on the unrotated profile (§1.3). For a rolled member (rot ≠ 0) the steel
5759
- // therefore travels along the roll-swung direction, not along the arrow — the gizmo stays internally
5760
- // consistent (grab arrow → offset changes by the amount dragged along it) and preview↔commit agree, but
5761
- // arrow and motion diverge. Re-expressing the roll so they coincide is slice 3b; do not "fix" one half.
5762
- arrow(st.zAxis, 0x3b82f6, 'depth'); // blue = depth (positionOffset)
5763
- arrow(st.yAxis, 0x22c55e, 'width'); // green = width (positionHOffset)
5764
- // Rotation arc (red) about the member axis, drawn in the width–depth plane over a 270° sweep so both
5765
- // ends stay clear of the two arrows.
5766
- const R = 0.72, pts = [];
5767
- for (let i = 0; i <= 36; i++) { const p = (-0.75 + (i / 36) * 1.5) * Math.PI;
5768
- pts.push(yv.clone().multiplyScalar(Math.cos(p) * R).add(zv.clone().multiplyScalar(Math.sin(p) * R))); }
5769
- const arc = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineBasicMaterial({ color: 0xef4444 }));
5770
- arc.material.depthTest = false; arc.renderOrder = 997; arc.userData = { posHandle: 'rot', arc: true }; g.add(arc);
5771
- // --- Reference-line handles (slice 3b.1) ---------------------------------------------------------
5772
- // These move the member's WORK POINTS; the three above move the profile within a fixed reference line.
5773
- // COLOUR IS BY AXIS, not by that family split: the shipped mapping is already blue=Z(depth),
5774
- // green=Y(width), red=X (the roll arc rotates ABOUT x), each axis carrying only one of its two degrees
5775
- // of freedom. These complete the pairs — red for the X translate (pairing with the red X roll arc, told
5776
- // apart by shape exactly as the blue/green arrows already are), green for the rotation about Y, blue for
5777
- // the plan swing. The last is a LABELLED approximation: it rotates about basis-up, which equals the local
5778
- // zAxis only for a level unrolled member — which is why its copy says "in plan" and never "depth axis".
5779
- // The palette is locked; this adds no hue.
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
5780
6098
  if (st.handles && st.handles.slide && st.handles.slide.available) arrow(st.xAxis, 0xef4444, 'slide');
5781
- const swingArc = (axisArr, col, tag) => {
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) => {
5782
6104
  const b = axisArr && swingBasis(st.anchor, st.end, axisArr);
5783
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
5784
- for (const side of [1, -1]) {
5785
- const pts = [];
5786
- for (let i = 0; i <= 36; i++) {
5787
- const p = side * (POS_LOBE_START + (i / 36) * POS_LOBE_SWEEP) * Math.PI, c = Math.cos(p) * POS_SWING_R, s = Math.sin(p) * POS_SWING_R;
5788
- pts.push(new THREE.Vector3(b.e1[0] * c + b.e2[0] * s, b.e1[1] * c + b.e2[1] * s, b.e1[2] * c + b.e2[2] * s));
5789
- }
5790
- const lobe = new THREE.Line(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineBasicMaterial({ color: col }));
5791
- lobe.material.depthTest = false; lobe.renderOrder = 997; lobe.userData = { posHandle: tag, arc: true }; g.add(lobe);
5792
- }
6106
+ quarterArc(b.e1, swingArcE2(b, st.up, towardUp), col, tag, POS_SWING_START); // dead zone over the shared axis end
5793
6107
  };
5794
- if (st.handles && st.handles.swingPlan && st.handles.swingPlan.available) swingArc(st.up, 0x3b82f6, 'swingPlan');
5795
- if (st.handles && st.handles.swingElev && st.handles.swingElev.available) swingArc(st.yAxis, 0x22c55e, 'swingElev');
5796
- // Anchor dot (amber) — the reference-line start the whole gizmo pivots on.
5797
- const dot = new THREE.Mesh(new THREE.SphereGeometry(0.08, 12, 8), new THREE.MeshBasicMaterial({ color: 0xf59e0b }));
5798
- dot.material.depthTest = false; dot.renderOrder = 999; dot.userData = { posHandle: 'anchor' }; g.add(dot);
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
+ }
5799
6134
  g.position.set(st.anchor[0], st.anchor[1], st.anchor[2]);
5800
6135
  positionGizmo = g; overlayScene.add(g); sizePositionGizmo();
5801
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
+ }
5802
6147
  // Cyan #22d3ee rubber-band leader from the amber anchor to the live drag point — the "offsetting from a fixed
5803
6148
  // point" signal. #22d3ee already ships as the frame-gizmo rotation ring + the cmHud selected-segment accent, so
5804
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.
5805
6152
  function updatePositionLeader(tipWorld) {
5806
6153
  if (!overlayScene || !posGizmoState) return;
5807
6154
  const O = posGizmoState.anchor, pts = [new THREE.Vector3(O[0], O[1], O[2]), new THREE.Vector3(tipWorld[0], tipWorld[1], tipWorld[2])];
@@ -5818,37 +6165,86 @@ function disposePositionLeader() {
5818
6165
  if (positionLeader.geometry) positionLeader.geometry.dispose(); if (positionLeader.material) positionLeader.material.dispose();
5819
6166
  positionLeader = null;
5820
6167
  }
5821
- // 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.)
5822
6183
  function sizePositionGizmo() {
5823
- if (!positionGizmo || !posGizmoState) return;
5824
- const O = posGizmoState.anchor;
5825
- positionGizmo.scale.setScalar(pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2])));
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));
5826
6214
  }
5827
- // The gizmo's grab points in client px, for an E2E to drive precise drags (mirrors frameHandlesScreen).
5828
- function positionGizmoHandlesScreen() {
5829
- if (!canvasEl || !posGizmoState) return null;
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;
5830
6226
  camera.updateMatrixWorld();
5831
- const rect = canvasEl.getBoundingClientRect(), O = posGizmoState.anchor;
5832
- const sc = pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2]));
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);
5833
6230
  const toS = (p) => { const w = new THREE.Vector3(p[0], p[1], p[2]).project(camera);
5834
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 }; };
5835
6232
  const at = (ax, k) => toS([O[0] + ax[0] * sc * k, O[1] + ax[1] * sc * k, O[2] + ax[2] * sc * k]);
5836
- const rotArr = [posGizmoState.yAxis[0] * 0.51 + posGizmoState.zAxis[0] * 0.51,
5837
- posGizmoState.yAxis[1] * 0.51 + posGizmoState.zAxis[1] * 0.51,
5838
- posGizmoState.yAxis[2] * 0.51 + posGizmoState.zAxis[2] * 0.51];
5839
- // Slice 3b.1 grab points. The swing grabs sit mid-lobe (45° off the member axis) on the +side lobe —
5840
- // the same point the pick samples nearest, so an E2E drag from here lands on the handle it named.
5841
- const swingGrab = (axisArr) => {
5842
- const b = axisArr && posGizmoState.end && swingBasis(posGizmoState.anchor, posGizmoState.end, axisArr);
5843
- if (!b) return null;
5844
- const p = (POS_LOBE_START + POS_LOBE_SWEEP / 2) * Math.PI, c = Math.cos(p), s = Math.sin(p);
5845
- return at([b.e1[0] * c + b.e2[0] * s, b.e1[1] * c + b.e2[1] * s, b.e1[2] * c + b.e2[2] * s], POS_SWING_R);
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]);
5846
6238
  };
5847
- const h = posGizmoState.handles;
5848
- return { anchor: toS(O), depthTip: at(posGizmoState.zAxis, 1), widthTip: at(posGizmoState.yAxis, 1), rotHandle: at(rotArr, 1),
5849
- slideTip: h && h.slide && h.slide.available ? at(posGizmoState.xAxis, 1) : null,
5850
- swingPlanHandle: h && h.swingPlan && h.swingPlan.available ? swingGrab(posGizmoState.up) : null,
5851
- swingElevHandle: h && h.swingElev && h.swingElev.available ? swingGrab(posGizmoState.yAxis) : null,
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,
5852
6248
  handles: h || null, available: true };
5853
6249
  }
5854
6250
  function setPositionGizmoVisible(on) { positionGizmoVisible = !!on; syncGizmoVisibility(); } // ⋯ Display toggle → editor pushes the flag (also (un)hides the frame gizmo)
@@ -5857,9 +6253,18 @@ function setPositionGizmoVisible(on) { positionGizmoVisible = !!on; syncGizmoVis
5857
6253
  function setPositionTyping(on) {
5858
6254
  posInteraction = on ? 'typing' : 'idle';
5859
6255
  if (controls) controls.enabled = !on; // idle default = orbit enabled; typing = frozen
5860
- 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(); }
5861
6257
  if (canvasEl) canvasEl.style.cursor = on ? 'text' : 'default';
5862
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
+ }
5863
6268
  // E2E read-only probe: a member mesh's WORLD transform, so a test can assert a gizmo drag's live preview
5864
6269
  // equals the committed rebuild (no jump on release) and that "From member" leaves the steel exactly put.
5865
6270
  function memberWorldTransform(id) {
@@ -5873,12 +6278,32 @@ function memberWorldTransform(id) {
5873
6278
  // drawn? The latter proves the mutual hide (position gizmo showing → frame gizmo null → not pickable).
5874
6279
  function positionLeaderVisible() { return !!(positionLeader && positionLeader.visible); }
5875
6280
  function frameGizmoVisible() { return !!frameGizmo; }
5876
-
5877
- // --- Profile Position gizmo: pick + drag. depth/width arrows drive the numeric offsets; the arc drives
5878
- // the roll. Every gesture reports an ABSOLUTE new value to the editor on release (one undo entry).
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.
5879
6295
  const POS_SNAP_MM = POSITION_OFFSET_SNAP_MM; // ¼" offset snap (shared with the bake helpers, in steel-3d-core)
5880
6296
  const POS_SNAP_DEG = POSITION_ROT_SNAP_DEG; // 5° rotation snap
5881
- const POS_EDGE_ON_PX = 26; // below this projected axis length a drag is refused (spec §3.1)
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); }
5882
6307
  function posGizmoRay(e) {
5883
6308
  const rect = canvasEl.getBoundingClientRect();
5884
6309
  const ndc = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
@@ -5901,7 +6326,8 @@ function posGizmoArcAngle(e, st) {
5901
6326
  const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(new THREE.Vector3(st.xAxis[0], st.xAxis[1], st.xAxis[2]).normalize(), O);
5902
6327
  const hit = new THREE.Vector3(); if (!ray.intersectPlane(plane, hit)) return null;
5903
6328
  const d = new THREE.Vector3().subVectors(hit, O);
5904
- return Math.atan2(d.dot(new THREE.Vector3(st.zAxis[0], st.zAxis[1], st.zAxis[2])), d.dot(new THREE.Vector3(st.yAxis[0], st.yAxis[1], st.yAxis[2])));
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])));
5905
6331
  }
5906
6332
  /**
5907
6333
  * The pointer's angle in a swing's own plane, measured in the FROZEN in-plane basis: `atan2(d·e2, d·e1)`
@@ -5920,8 +6346,15 @@ function posSwingAngle(e, st, axisArr, basis) {
5920
6346
  d.dot(new THREE.Vector3(basis.e1[0], basis.e1[1], basis.e1[2])));
5921
6347
  }
5922
6348
  function pickPositionGizmoHandle(cx, cy) {
5923
- if (!positionGizmoVisible || !posGizmoState || !canvasEl) return null;
5924
- 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;
5925
6358
  const hit = (pt) => pt && !pt.behind && Math.hypot(pt.x - cx, pt.y - cy) <= 14;
5926
6359
  if (hit(h.depthTip)) return 'depth';
5927
6360
  if (hit(h.widthTip)) return 'width';
@@ -5929,33 +6362,44 @@ function pickPositionGizmoHandle(cx, cy) {
5929
6362
  // planes edge-on at once — a genuinely degenerate view. Refuse those three picks there rather than try to
5930
6363
  // out-geometry it, exactly as the depth/width arrows already refuse their own edge-on drag.
5931
6364
  const axisOk = h.anchor && !h.anchor.behind && h.slideTip && !h.slideTip.behind
5932
- && Math.hypot(h.slideTip.x - h.anchor.x, h.slideTip.y - h.anchor.y) >= POS_EDGE_ON_PX;
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);
5933
6366
  if (axisOk && hit(h.slideTip)) return 'slide';
5934
- const O = posGizmoState.anchor, sc = pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2]));
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
5935
6369
  const rect = canvasEl.getBoundingClientRect();
5936
6370
  // Sample an arc in screen space and take the nearest point within tolerance.
5937
- const nearestOn = (samples) => { let best = 12;
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;
5938
6376
  for (const w0 of samples) { const w = w0.project(camera);
5939
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;
5940
6378
  const dd = Math.hypot(sx - cx, sy - cy); if (dd < best) best = dd; }
5941
- return best < 12; };
5942
- const yv = posGizmoState.yAxis, zv = posGizmoState.zAxis, roll = [];
5943
- for (let i = 0; i <= 36; i++) { const p = (-0.75 + (i / 36) * 1.5) * Math.PI, c = Math.cos(p) * 0.72, s = Math.sin(p) * 0.72;
5944
- roll.push(new THREE.Vector3(O[0] + (yv[0] * c + zv[0] * s) * sc, O[1] + (yv[1] * c + zv[1] * s) * sc, O[2] + (yv[2] * c + zv[2] * s) * sc)); }
5945
- if (nearestOn(roll)) return 'rot';
5946
- if (!axisOk) return null;
5947
- const lobeSamples = (axisArr) => {
5948
- const b = posGizmoState.end && axisArr && swingBasis(posGizmoState.anchor, posGizmoState.end, axisArr);
5949
- if (!b) return [];
5950
- const out = [];
5951
- for (const side of [1, -1]) for (let i = 0; i <= 36; i++) {
5952
- const p = side * (POS_LOBE_START + (i / 36) * POS_LOBE_SWEEP) * Math.PI, c = Math.cos(p) * POS_SWING_R * sc, s = Math.sin(p) * POS_SWING_R * sc;
5953
- out.push(new THREE.Vector3(O[0] + b.e1[0] * c + b.e2[0] * s, O[1] + b.e1[1] * c + b.e2[1] * s, O[2] + b.e1[2] * c + b.e2[2] * s));
5954
- }
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)); }
5955
6386
  return out; };
5956
- if (h.swingPlanHandle && nearestOn(lobeSamples(posGizmoState.up))) return 'swingPlan';
5957
- if (h.swingElevHandle && nearestOn(lobeSamples(posGizmoState.yAxis))) return 'swingElev';
5958
- return null;
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;
5959
6403
  }
5960
6404
  // The amber anchor dot, hit-tested SEPARATELY and consulted ONLY by the hover/tooltip path. Deliberately
5961
6405
  // not part of `pickPositionGizmoHandle`: that function's answers arm a drag in onDown, and the dot is not
@@ -5963,10 +6407,20 @@ function pickPositionGizmoHandle(cx, cy) {
5963
6407
  // has. Two independent checks over the same pixels, with different consumers. (Before 3b.1 the anchor's
5964
6408
  // tooltip copy existed but could never be shown, because nothing ever answered 'anchor'.)
5965
6409
  function pickPositionAnchorHover(cx, cy) {
5966
- if (!positionGizmoVisible || !posGizmoState || !canvasEl) return false;
5967
- const h = positionGizmoHandlesScreen();
6410
+ if (!positionGizmoVisible || !posGizmoState || !canvasEl || posInteraction === 'dragging') return false;
6411
+ const h = positionGizmoHandlesScreen(posGizmoState);
5968
6412
  return !!(h && h.anchor && !h.anchor.behind && Math.hypot(h.anchor.x - cx, h.anchor.y - cy) <= 11);
5969
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'; }
5970
6424
  function startPositionGizmoDrag(kind, e) {
5971
6425
  const id = [...selIds][0], st = api.positionGizmoState(id);
5972
6426
  // The handle was picked from the CACHED snapshot, but the base value comes from a FRESH read — if the
@@ -5975,13 +6429,20 @@ function startPositionGizmoDrag(kind, e) {
5975
6429
  if (!st || !st.available) { pending = null; if (controls) controls.enabled = true; return; }
5976
6430
  const mesh = meshById.get(id);
5977
6431
  const mesh0 = { meshPos0: mesh ? mesh.position.clone() : null, meshQuat0: mesh ? mesh.quaternion.clone() : null };
5978
- // --- Reference-line gestures (slice 3b.1): freeze EVERYTHING the gesture depends on, right here.
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.
5979
6440
  // The rotation axis, the drag-start far endpoint, the in-plane basis and the plumb barriers are all
5980
6441
  // constants for the whole gesture, so each tick applies the TOTAL angle to the frozen endpoint rather
5981
6442
  // than composing per-tick rotations (which drifts, and makes the 5° snap chatter). The barriers in
5982
6443
  // particular are closed-form and cannot change while the geometry is frozen — computing them once here
5983
6444
  // instead of per pointer-move keeps the drag path O(1).
5984
- if (kind === 'slide' || kind === 'swingPlan' || kind === 'swingElev') {
6445
+ if (posMovesLine(kind)) {
5985
6446
  const avail = st.handles && st.handles[kind];
5986
6447
  if (!avail || !avail.available) {
5987
6448
  // A VISIBLE, hovering, tooltipped handle that does nothing on press is confusing — the handles are
@@ -5993,33 +6454,39 @@ function startPositionGizmoDrag(kind, e) {
5993
6454
  positionGizmoReadout(e, why, '');
5994
6455
  pending = null; if (controls) controls.enabled = true; return;
5995
6456
  }
6457
+ const swinging = kind === 'swingPlan' || kind === 'swingElev';
5996
6458
  const swingAxis = kind === 'swingPlan' ? st.up : kind === 'swingElev' ? st.yAxis : null;
5997
6459
  const basis = swingAxis ? swingBasis(st.anchor, st.end, swingAxis) : null;
5998
6460
  // Only the ELEVATION swing can reach plumb: a plan swing preserves the member's distance from the
5999
6461
  // degeneracy cone exactly, so it can neither enter nor leave it and needs no barrier at all.
6000
6462
  const barriers = kind === 'swingElev' ? swingBarriers(st.anchor, st.end, st.yAxis, st.up, POS_SWING_MARGIN_RAD) : null;
6001
- if (kind !== 'slide' && (!basis || (kind === 'swingElev' && !barriers))) {
6463
+ if (swinging && (!basis || (kind === 'swingElev' && !barriers))) {
6002
6464
  const why = 'This member can’t be swung from its current direction — set its geometry in the Inspect panel.';
6003
6465
  console.warn('steel-3d: reference-line swing refused — no usable', basis ? 'plumb barrier' : 'swing plane');
6004
6466
  positionGizmoReadout(e, why, '');
6005
6467
  pending = null; if (controls) controls.enabled = true; return;
6006
6468
  }
6007
- const startScalar = kind === 'slide' ? posGizmoAxisScalar(e, st, st.xAxis) : posSwingAngle(e, st, swingAxis, basis);
6469
+ const transAxis = swinging ? null : posTranslateAxis(st, kind);
6470
+ const startScalar = swinging ? posSwingAngle(e, st, swingAxis, basis) : posGizmoAxisScalar(e, st, transAxis);
6008
6471
  pending = { posGizmo: { id, axis: kind, state: st, refline: true, base: 0, startScalar, newVal: 0,
6009
- swingAxis, basis, barriers, accumRad: 0, prevAng: startScalar, ...mesh0 } };
6010
- posInteraction = 'dragging';
6011
- posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip();
6012
- downXY = [e.clientX, e.clientY];
6472
+ swingAxis, basis, barriers, transAxis, accumRad: 0, prevAng: startScalar, ...mesh0 } };
6473
+ armed();
6013
6474
  return;
6014
6475
  }
6015
- const base = kind === 'depth' ? st.positionOffset : kind === 'width' ? st.positionHOffset : st.rot;
6016
- const startScalar = kind === 'rot' ? posGizmoArcAngle(e, st) : posGizmoAxisScalar(e, st, kind === 'depth' ? st.zAxis : st.yAxis);
6476
+ const base = st.rot;
6477
+ const startScalar = posGizmoArcAngle(e, st);
6017
6478
  pending = { posGizmo: { id, axis: kind, state: st, base, startScalar, newVal: base,
6018
- accumRad: 0, prevAng: kind === 'rot' ? startScalar : null, // rot: accumulate the arc CONTINUOUSLY (unwrapAngleStep) so a ±180° seam crossing never jumps ~2π
6479
+ accumRad: 0, prevAng: startScalar, // rot: accumulate the arc CONTINUOUSLY (unwrapAngleStep) so a ±180° seam crossing never jumps ~2π
6019
6480
  ...mesh0 } };
6020
- posInteraction = 'dragging';
6021
- posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); // the hover handler is inert during a drag — clear any lingering handle tip so it doesn't sit where the readout will land
6022
- downXY = [e.clientX, e.clientY];
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';
6023
6490
  }
6024
6491
  function positionGizmoReadout(e, txt, type) {
6025
6492
  if (!readout) return;
@@ -6036,87 +6503,79 @@ function onMovePositionGizmo(e) {
6036
6503
  dragging = pending;
6037
6504
  const pg = pending.posGizmo, st = pg.state, mesh = meshById.get(pg.id);
6038
6505
  if (pg.refline) { onMoveRefLineGizmo(e, pg, st, mesh); return; }
6039
- if (pg.axis === 'rot') {
6040
- const ang = posGizmoArcAngle(e, st);
6041
- if (ang == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6042
- if (pg.startScalar == null) { pg.startScalar = ang; pg.prevAng = ang; return; } // grab was edge-on → set the reference on the first valid hit
6043
- if (pg.prevAng == null) pg.prevAng = ang;
6044
- // Accumulate the arc CONTINUOUSLY (shortest-arc step per move) so dragging across the ±180° seam adds a
6045
- // small increment instead of the ~2π jump a bare (ang − start) makes near the seam. The running total is
6046
- // the true swept angle, so the value tracks the hand monotonically and renormalizes only on commit.
6047
- pg.accumRad += unwrapAngleStep(pg.prevAng, ang); pg.prevAng = ang;
6048
- // Snap the DELTA, not the absolute value: since 3b.2 the resting roll is re-expressed into the current
6049
- // frame and is generically off-grid (e.g. 33.71°), so snapping the absolute would yank the steel to the
6050
- // 5° grid on the very first drag tick (a jump at drag-START). Stepping the delta keeps the value at the
6051
- // member's own roll when Δ=0 and moves in 5° increments from there.
6052
- const rawDeltaDeg = pg.accumRad * 180 / Math.PI;
6053
- const deg = pg.base + (e.shiftKey ? rawDeltaDeg : snapToStep(rawDeltaDeg, POS_SNAP_DEG));
6054
- pg.newVal = deg;
6055
- if (mesh && pg.meshPos0 && pg.meshQuat0) { // exact live preview: roll about the reference-line anchor
6056
- const axis = new THREE.Vector3(st.xAxis[0], st.xAxis[1], st.xAxis[2]).normalize();
6057
- const roll = new THREE.Quaternion().setFromAxisAngle(axis, (deg - pg.base) * Math.PI / 180);
6058
- const O = new THREE.Vector3(st.anchor[0], st.anchor[1], st.anchor[2]);
6059
- mesh.position.copy(pg.meshPos0.clone().sub(O).applyQuaternion(roll).add(O));
6060
- mesh.quaternion.copy(roll.clone().multiply(pg.meshQuat0));
6061
- }
6062
- { const O = st.anchor, R = 0.72 * pxToWorldAt(POS_GIZMO_REACH_PX, new THREE.Vector3(O[0], O[1], O[2])), c = Math.cos(ang), s2 = Math.sin(ang);
6063
- updatePositionLeader([O[0] + (st.yAxis[0] * c + st.zAxis[0] * s2) * R, O[1] + (st.yAxis[1] * c + st.zAxis[1] * s2) * R, O[2] + (st.yAxis[2] * c + st.zAxis[2] * s2) * R]); }
6064
- positionGizmoReadout(e, 'Rotation ' + Math.round(deg) + '°', ''); // label-first, to match the Inspect panel's "Rotation" row
6065
- return;
6066
- }
6067
- // depth / width: refuse an edge-on axis (a foreshortened axis inflates mm-per-pixel without bound).
6068
- const scr = positionGizmoHandlesScreen();
6069
- const tip = scr && (pg.axis === 'depth' ? scr.depthTip : scr.widthTip);
6070
- if (scr && tip && !tip.behind && Math.hypot(tip.x - scr.anchor.x, tip.y - scr.anchor.y) < POS_EDGE_ON_PX) {
6071
- positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return;
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));
6072
6527
  }
6073
- const s = posGizmoAxisScalar(e, st, pg.axis === 'depth' ? st.zAxis : st.yAxis);
6074
- if (s == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6075
- if (pg.startScalar == null) { pg.startScalar = s; return; } // grab was edge-on → set the reference on the first valid hit (mirrors the rot arm)
6076
- // Snap the DELTA, not the absolute (see the rot arm): a base offset need not be grid-aligned — since 3b.2
6077
- // it commonly is not — so snapping the absolute would jump to the ¼" grid on the first tick. Stepping the
6078
- // delta holds the value at the member's own offset when Δ=0.
6079
- const rawDeltaMm = s - pg.startScalar;
6080
- const val = pg.base + (e.shiftKey ? rawDeltaMm : snapToStep(rawDeltaMm, POS_SNAP_MM));
6081
- pg.newVal = val;
6082
- { const O = st.anchor, ax = pg.axis === 'depth' ? st.zAxis : st.yAxis; // leader to the drag point on this axis
6083
- updatePositionLeader([O[0] + ax[0] * s, O[1] + ax[1] * s, O[2] + ax[2] * s]); }
6084
- if (mesh && pg.meshPos0) { // exact live preview: the SAME swing the bake uses (positionSwingDelta), so the steel never jumps on release
6085
- const w = positionSwingDelta({ y: st.yAxis, z: st.zAxis }, pg.axis, val - pg.base, st.rot || 0);
6086
- mesh.position.set(pg.meshPos0.x + w[0], pg.meshPos0.y + w[1], pg.meshPos0.z + w[2]);
6087
- }
6088
- const shownVal = api && api.fmtLen ? api.fmtLen(val) : Math.round(val) + ' mm';
6089
- positionGizmoReadout(e, (pg.axis === 'depth' ? 'Depth ' : 'Width ') + shownVal, ''); // label-first + panel's own unit (fmtLen), to match the Inspect panel exactly
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
6090
6532
  }
6091
6533
  /*
6092
- * The reference-line gestures (slice 3b.1). These move the member's WORK POINTS, so the live preview is a
6093
- * RIGID transform of the existing mesh — a translation for the slide, one rotation about the anchor for a
6094
- * swing. Nothing is rebuilt mid-drag, which is also why the view never has to freeze the depth face: a
6095
- * rigid transform cannot re-derive it. The fold is decided once, at commit, in the editor.
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.
6096
6538
  *
6097
6539
  * Every gesture reports a DELTA (mm along the axis, or radians about the frozen axis); `onUp` turns that
6098
6540
  * into absolute world work points through the same pure helpers the tests exercise.
6099
6541
  */
6100
6542
  function onMoveRefLineGizmo(e, pg, st, mesh) {
6101
6543
  // The member axis going edge-on collapses the slide arrow AND both arc planes at once. Refuse rather than
6102
- // let mm-per-pixel run away, matching the shipped depth/width refusal word for word.
6103
- const scr = positionGizmoHandlesScreen();
6104
- if (scr && scr.anchor && scr.slideTip && !scr.slideTip.behind
6105
- && Math.hypot(scr.slideTip.x - scr.anchor.x, scr.slideTip.y - scr.anchor.y) < POS_EDGE_ON_PX) {
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;
6554
+ }
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)) {
6106
6557
  positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return;
6107
6558
  }
6108
- if (pg.axis === 'slide') {
6109
- const s = posGizmoAxisScalar(e, st, st.xAxis);
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);
6110
6565
  if (s == null) { positionGizmoReadout(e, 'View is edge-on — orbit, or set the value in Inspect', ''); return; }
6111
6566
  if (pg.startScalar == null) { pg.startScalar = s; return; } // grab was edge-on → set the reference on the first valid hit
6112
6567
  const raw = s - pg.startScalar;
6113
6568
  const delta = e.shiftKey ? raw : snapToStep(raw, POS_SNAP_MM);
6114
6569
  pg.newVal = delta;
6115
6570
  if (mesh && pg.meshPos0) {
6116
- mesh.position.set(pg.meshPos0.x + st.xAxis[0] * delta, pg.meshPos0.y + st.xAxis[1] * delta, pg.meshPos0.z + st.xAxis[2] * delta);
6571
+ mesh.position.set(pg.meshPos0.x + ax[0] * delta, pg.meshPos0.y + ax[1] * delta, pg.meshPos0.z + ax[2] * delta);
6117
6572
  }
6118
- updatePositionLeader([st.anchor[0] + st.xAxis[0] * s, st.anchor[1] + st.xAxis[1] * s, st.anchor[2] + st.xAxis[2] * s]);
6119
- positionGizmoReadout(e, 'Slide ' + (api && api.fmtLen ? api.fmtLen(delta) : Math.round(delta) + ' mm'), '');
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'), '');
6120
6579
  return;
6121
6580
  }
6122
6581
  // --- swing: rotate the member DIRECTION about the frozen axis, moving only the far work point.
@@ -6142,6 +6601,7 @@ function onMoveRefLineGizmo(e, pg, st, mesh) {
6142
6601
  mesh.position.copy(pg.meshPos0.clone().sub(O).applyQuaternion(q).add(O));
6143
6602
  mesh.quaternion.copy(q.clone().multiply(pg.meshQuat0));
6144
6603
  }
6604
+ setPositionLive(livePositionState(st, pg.axis, theta, pg.swingAxis));
6145
6605
  const tip = swingEndpoint(st.anchor, st.end, pg.swingAxis, theta);
6146
6606
  if (tip) updatePositionLeader(tip);
6147
6607
  const degRaw = theta * 180 / Math.PI;
@@ -6338,7 +6798,7 @@ function renderWorkPlane() {
6338
6798
  function reflectWpBar() { const b = document.getElementById('m3dWp'); if (b) { b.classList.toggle('on', !!wpMode || !!workPlane);
6339
6799
  const kind = workPlane && workPlane.kind ? { face: 'Face', p3: '3pt', xy: 'XY', xz: 'XZ', yz: 'YZ' }[workPlane.kind] || '' : '';
6340
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)
6341
- 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)
6342
6802
  function setWorkPlanePrincipal(kind, offsetMm) {
6343
6803
  const off = offsetMm || 0;
6344
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];
@@ -6852,6 +7312,7 @@ function onDown(e) {
6852
7312
  if (addActive()) { e.stopPropagation(); controls.enabled = true; drClick(e); return; } // Add-member armed (editor state) → two plane picks draw a member
6853
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
6854
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
6855
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.
6856
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)
6857
7318
  if (clipMode === 'box') { e.stopPropagation(); onClipBoxClick(e); return; } // armed: 2-corner clip-box draw on the floor plane
@@ -7397,18 +7858,23 @@ function onUp(e) {
7397
7858
  if (p.posGizmo) { // Profile Position handle → commit the ABSOLUTE new offset/roll through the editor (one undo entry)
7398
7859
  if (readout) readout.style.display = 'none';
7399
7860
  hidePositionLeader();
7400
- posInteraction = 'idle';
7861
+ endPositionGesture();
7401
7862
  const pg = p.posGizmo;
7402
- if (pg.refline) { // slice 3b.1 — the handles that move the WORK POINTS, committed as absolute world mm
7863
+ if (pg.refline) { // the handles that move the WORK POINTS, committed as absolute world mm
7403
7864
  const st = pg.state;
7404
7865
  const moved = pg.newVal != null && Math.abs(pg.newVal) > 1e-12;
7405
7866
  if (wasDragging && moved && api && api.commitMemberEndpoints) {
7406
7867
  // Rebuild the absolute points from the FROZEN drag-start geometry and the total delta, through the
7407
7868
  // same pure helpers the unit tests pin — never from whatever the mesh preview happens to show.
7408
7869
  let spec = null;
7409
- if (pg.axis === 'slide') {
7410
- const r = slideEndpoints(st.anchor, st.end, st.xAxis, pg.newVal);
7411
- if (r) spec = { from: r.from, to: r.to, gesture: 'slide', expect: st.fingerprint };
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 };
7412
7878
  } else {
7413
7879
  const to = swingEndpoint(st.anchor, st.end, pg.swingAxis, pg.newVal);
7414
7880
  if (to) spec = { to, gesture: pg.axis, expect: st.fingerprint };
@@ -7424,16 +7890,14 @@ function onUp(e) {
7424
7890
  } else { restorePositionGizmoMesh(pg); renderPositionGizmo(); }
7425
7891
  return;
7426
7892
  }
7427
- // rot is compared by ANGULAR equality (mod 360): a drag that loops the arc back to the member's own roll
7428
- // (Δ = 360°) reads as no move and must commit nothing / push no undo entry (Fable 5 test 1). depth/width
7429
- // stay a linear compare.
7430
- const moved = pg.axis === 'rot'
7431
- ? Math.abs((((pg.newVal - pg.base) % 360) + 540) % 360 - 180) > 1e-6 // shortest angular distance (deg) from base
7432
- : Math.abs(pg.newVal - pg.base) > 1e-9;
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
7433
7898
  if (wasDragging && pg.newVal != null && moved && api && api.commitMemberPosition) {
7434
- const key = pg.axis === 'depth' ? 'positionOffset' : pg.axis === 'width' ? 'positionHOffset' : 'rot';
7435
- const val = pg.axis === 'rot' ? rollCommitNorm(pg.newVal) : pg.newVal; // fold the accumulated/off-grid roll to the panel's stored convention
7436
- const ok = api.commitMemberPosition(pg.id, { [key]: val }, null); // editor's edit() rebuilds → renderPositionGizmo re-anchors
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
7437
7901
  if (!ok) { restorePositionGizmoMesh(pg); renderPositionGizmo(); } // refused (e.g. frame drifted) → snap the live preview back
7438
7902
  } else { restorePositionGizmoMesh(pg); renderPositionGizmo(); } // no net move or a plain click → restore the preview
7439
7903
  return;
@@ -7610,18 +8074,23 @@ function onHoverMove(e) {
7610
8074
  // tooltip. Mirrors onDown precedence (the handle sits ON the member and wins over the passive frame origin).
7611
8075
  if (positionGizmoVisible && posGizmoState && !frameMode && posInteraction !== 'typing') {
7612
8076
  let ph = null; try { ph = pickPositionGizmoHandle(lastHoverXY[0], lastHoverXY[1]); } catch { ph = null; }
7613
- 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);
7614
8080
  if (api && api.showHandleTip) api.showHandleTip(POS_HANDLE_TIP[ph], lastHoverXY[0], lastHoverXY[1]);
7615
8081
  posHovered = true; return; }
7616
8082
  // The anchor is hover-only: it explains itself but never arms a drag, so it is checked here and NOT
7617
8083
  // in pickPositionGizmoHandle. Cursor stays default — a grab cursor would promise a drag that a
7618
8084
  // mousedown here does not perform (it falls through to click-select, as it always has).
7619
8085
  let onAnchor = false; try { onAnchor = pickPositionAnchorHover(lastHoverXY[0], lastHoverXY[1]); } catch { onAnchor = false; }
7620
- if (onAnchor) {
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');
7621
8089
  if (api && api.showHandleTip) api.showHandleTip(POS_HANDLE_TIP.anchor, lastHoverXY[0], lastHoverXY[1]);
7622
8090
  posHovered = true; return; }
8091
+ setPositionHover(null);
7623
8092
  if (posHovered) { posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); }
7624
- } else if (posHovered) { posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); } // gizmo disappeared while a tip was up
8093
+ } else if (posHovered) { setPositionHover(null); posHovered = false; if (api && api.hideHandleTip) api.hideHandleTip(); } // gizmo disappeared while a tip was up
7625
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"
7626
8095
  let fh = null; try { fh = pickFrameHandle(lastHoverXY[0], lastHoverXY[1], true); } catch { fh = null; }
7627
8096
  if (fh) { canvasEl.style.cursor = 'pointer'; return; }
@@ -7668,6 +8137,12 @@ function instructorCommand() {
7668
8137
  if (refMeasure3d) return { armed: 'steel.reference-measure', step: refMeasure3d.a ? 1 : 0 };
7669
8138
  if (framePickStep() != null) return { armed: 'steel.local-frame', step: framePickStep() };
7670
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 };
7671
8146
  if (insertMode) return { armed: 'steel.insert-detail', step: 0 };
7672
8147
  if (basePickCol) return { armed: 'steel.base-pick', step: 0 };
7673
8148
  if (gridLinePick3d) return { armed: 'steel.grid-line', step: gridLinePick3d.a ? 1 : 0 };
@@ -7711,6 +8186,14 @@ function armedStepText(commandId) {
7711
8186
  if (commandId && g.commandId && g.commandId !== commandId) return null;
7712
8187
  return g.parts[0];
7713
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
+ }
7714
8197
  function updateStatusChip() {
7715
8198
  if (!hoverChip || !canvasEl) return;
7716
8199
  const rect = canvasEl.getBoundingClientRect();
@@ -7723,6 +8206,7 @@ function updateStatusChip() {
7723
8206
  gridLinePickActive: !!gridLinePick3d, clipMode, dimensionMode: dimMode3d,
7724
8207
  dimensionHasStart: !!dimDraft3d, insertMode, insertName: insertPending && insertPending.name,
7725
8208
  basePickColumn: basePickCol, frameMode, framePickStep: framePickStep(), geometryMode: geoMode(),
8209
+ connectionMemberPick: !!connPick, connectionMemberPickCount: connPick ? connPick.chosen.size : 0,
7726
8210
  });
7727
8211
  const forceOpen = toolGuidance.forceOpen;
7728
8212
  const selectionStatus=objectSelectionStatus(selIds.size,selectedGridIds.size),showId=hoverId||(!selectionStatus&&selIds.size===1?[...selIds][0]:null);
@@ -7755,10 +8239,17 @@ function updateStatusChip() {
7755
8239
  drag = ` · ${n} ${n === 1 ? 'member' : 'members'}`
7756
8240
  + (teklaDrag.target ? ` · over ${HOST_SHORT[teklaDrag.target]}` : '');
7757
8241
  }
7758
- 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;
7759
8247
  }
7760
8248
  else if (cmd3d) { const meta = window.Commands && window.Commands.get(cmd3d.armed);
7761
- 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
7762
8253
  else if (toolGuidance.text) txt = toolGuidance.text;
7763
8254
  else if (showId) { const m = memberById(showId); txt = m ? `${m.id} · ${m.profile || '—'}` : ''; }
7764
8255
  else if (selectionStatus) txt = selectionStatus;
@@ -7793,6 +8284,7 @@ function updateStatusChip() {
7793
8284
  // short stalls would add up into one bogus warning.
7794
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)
7795
8286
  function hide() {
8287
+ abandonConnPick('left-3d'); // Enter/Esc cannot reach an armed pick once this canvas is hidden
7796
8288
  invalidatePointEntry('hide'); // leaving 3D → drop any open typed entry + stale base/start
7797
8289
  if (dimMode3d) toggleDimTool(); // disarm the dim tool + sync its toolbar (no stale draft/armed state on return)
7798
8290
  // …and the reference measure, through the editor so its panel card goes with it. Routed via
@@ -7811,11 +8303,18 @@ function hide() {
7811
8303
  }
7812
8304
  // The editor's active-pane state, pushed in. Defaults true so every existing caller — and vector-3d.html,
7813
8305
  // which has no split and never calls this — keeps today's behaviour with no change.
7814
- function setInputActive(on) { inputActive = on !== false; }
8306
+ function setInputActive(on) { inputActive = on !== false; if (!inputActive) abandonConnPick('pane-inactive'); }
7815
8307
  function isReady() { return built; }
7816
8308
 
7817
8309
  function dispose() {
7818
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;
7819
8318
  // Stage D, torn down like every sibling overlay above. Without it a re-init() mints a fresh line and
7820
8319
  // label while refMeasure3d still reports armed:true against a reference id from the previous
7821
8320
  // session — a chip asking for a first point over a scene where every click is a no-op.
@@ -7893,7 +8392,16 @@ function dispose() {
7893
8392
  clearRoot();
7894
8393
  if (workAreaHelper) { if (overlayScene) overlayScene.remove(workAreaHelper); workAreaHelper.geometry.dispose(); workAreaHelper.material.dispose(); workAreaHelper = null; }
7895
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)
7896
- clearConnEnvelope(); clearClipGizmo(); setClipPreview(null); setClipPlanePreview(null); disposeFramePreview(); disposeFrameGizmo(); disposePositionGizmo(); disposePositionLeader(); overlayScene = null; // dispose the clip/frame/position gizmo + leader + preview THREE resources before dropping the scene (Codex)
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)
7897
8405
  clips = []; workArea = null; clipMode = null; selectedClipIds.clear(); clipBoxDraft = null; // clips live on the renderer; drop them with the renderer
7898
8406
  if (renderer) renderer.dispose();
7899
8407
  renderer = scene = camera = perspCam = orthoCam = controls = root = api = canvasEl = ro = null; built = false;
@@ -8060,9 +8568,16 @@ window.Steel3DView = {
8060
8568
  setProjection, projection, setDisplayMode, mode: () => displayMode, frameAll, frameSelection, applyView,
8061
8569
  setRefLine, refLine: () => refLineOn,
8062
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,
8063
8575
  refreshStatus: updateStatusChip, // editor-owned armed modes (Extend/Trim, Split) refresh the disclosure immediately
8064
8576
  setBasePickMode, basePickMode: basePickModeOn, // arm/query the Mode B column-base pick (level-snapped elevation)
8065
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,
8066
8581
  // Reference models (#278) — an editor-only layer. `setReferences` takes the geometry the editor
8067
8582
  // fetched from the reference route; nothing here ever passes through contractToScene, which is what
8068
8583
  // keeps borrowed geometry out of every export by construction rather than by filtering.
@@ -8132,7 +8647,7 @@ window.Steel3DView = {
8132
8647
  workAreaSetAll, workAreaFromSelection, workAreaToggle, workAreaSetWhole, clearWorkArea, workAreaState,
8133
8648
  armWorkPlanePick, setWorkPlanePrincipal, clearWorkPlane, toggleWorkPlaneVisible, workPlaneInfo,
8134
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)
8135
- setPositionGizmoVisible, positionGizmoHandlesScreen, memberWorldTransform, setPositionTyping, positionLeaderVisible, frameGizmoVisible, // Profile Position gizmo (slice 3a/3b): ⋯ Display toggle + E2E grab-point + world-transform/leader/frame-gizmo probes + typed-HUD camera freeze
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
8136
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)
8137
8652
  cmEscape, cmHasBase, cmClear3d, setCmAxis, cmLastClient, cmHudApply,
8138
8653
  drHudApply, pointEntryBegin, pointEntryEnd, drHasStart: () => !!drDraft, // UCS stage 3: shared typed point-entry HUD (Move/Copy + Add)