@floless/app 0.100.1 → 0.101.0

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.
@@ -53106,7 +53106,7 @@ function appVersion() {
53106
53106
  return resolveVersion({
53107
53107
  isSea: isSea2(),
53108
53108
  sqVersionXml: readSqVersionXml(),
53109
- define: true ? "0.100.1" : void 0,
53109
+ define: true ? "0.101.0" : void 0,
53110
53110
  pkgVersion: readPkgVersion()
53111
53111
  });
53112
53112
  }
@@ -53116,7 +53116,7 @@ function resolveChannel(s) {
53116
53116
  return "dev";
53117
53117
  }
53118
53118
  function appChannel() {
53119
- return resolveChannel({ isSea: isSea2(), define: true ? "0.100.1" : void 0 });
53119
+ return resolveChannel({ isSea: isSea2(), define: true ? "0.101.0" : void 0 });
53120
53120
  }
53121
53121
 
53122
53122
  // workflow-update.ts
@@ -54233,6 +54233,20 @@ function walk(value, node, root, path, errors) {
54233
54233
  walk(value, target, root, path, errors);
54234
54234
  return;
54235
54235
  }
54236
+ if (node.oneOf) {
54237
+ let matches = 0;
54238
+ let closest = null;
54239
+ for (const candidate of node.oneOf) {
54240
+ const candidateErrors = [];
54241
+ walk(value, candidate, root, path, candidateErrors);
54242
+ if (candidateErrors.length === 0) matches++;
54243
+ else if (!closest || candidateErrors.length < closest.length) closest = candidateErrors;
54244
+ }
54245
+ if (matches !== 1) {
54246
+ errors.push({ path, message: `must match exactly one oneOf branch (matched ${matches})` });
54247
+ if (matches === 0 && closest) errors.push(...closest);
54248
+ }
54249
+ }
54236
54250
  if ("const" in node && !deepEqual(value, node.const)) {
54237
54251
  errors.push({ path, message: `must equal ${JSON.stringify(node.const)}` });
54238
54252
  }
@@ -54246,6 +54260,12 @@ function walk(value, node, root, path, errors) {
54246
54260
  return;
54247
54261
  }
54248
54262
  }
54263
+ if (typeof value === "number" && Number.isFinite(value)) {
54264
+ if (typeof node.minimum === "number" && value < node.minimum) errors.push({ path, message: `must be >= ${node.minimum}` });
54265
+ if (typeof node.maximum === "number" && value > node.maximum) errors.push({ path, message: `must be <= ${node.maximum}` });
54266
+ if (typeof node.exclusiveMinimum === "number" && value <= node.exclusiveMinimum) errors.push({ path, message: `must be > ${node.exclusiveMinimum}` });
54267
+ if (typeof node.exclusiveMaximum === "number" && value >= node.exclusiveMaximum) errors.push({ path, message: `must be < ${node.exclusiveMaximum}` });
54268
+ }
54249
54269
  if (isPlainObject(value)) {
54250
54270
  for (const r of node.required ?? []) {
54251
54271
  if (!Object.hasOwn(value, r)) errors.push({ path: `${path}.${r}`, message: "required" });
@@ -58658,6 +58678,7 @@ function bakeContractIntoApp(sourcePath, contract) {
58658
58678
  delete baked.detail_placements;
58659
58679
  delete baked.prop_labels;
58660
58680
  delete baked.member_styles;
58681
+ delete baked.views;
58661
58682
  if (Array.isArray(contract.plans)) {
58662
58683
  baked.plans = contract.plans.map((p) => {
58663
58684
  if (p && typeof p === "object") {
@@ -48,7 +48,7 @@
48
48
  "joints": { "type": "array", "items": { "$ref": "#/$defs/joint" }, "description": "Placed connections (base plates, …) the connection engine expands into real 3D parts (plate/bolt/weld/cut) bound to their members. A joint may cite a `connections[]` row via `conn` for its type/detail identity; `params` carries the geometry settings (engine defaults when absent)." },
49
49
  "dims3d": { "type": "array", "items": { "$ref": "#/$defs/dim3" }, "description": "Draft-only 3D dimensions (editor annotations, model-global). World-scene mm. NOT baked into the lock / 3D scene / IFC / BOM." },
50
50
  "detail_placements": { "type": "array", "items": { "$ref": "#/$defs/detailPlacement" }, "description": "Draft-only placed 2D detail images (Slice 4 — insert a vectored detail into the model). Flat image planes the editor renders client-side against the model; metadata only — the image bytes live in custom_details. Model-global. NOT baked into the lock / 3D scene / IFC / BOM." },
51
- "views": { "type": "array", "description": "Draft-only saved views (Views Organizer — up to 10 per model): each a named snapshot of the 3D viewpoint (camera + projection + display mode + clip boxes/planes + work area + the objects-list pane's persistent visibility/isolate state). Editor state, model-global. NOT baked into the lock / 3D scene / IFC / BOM.", "items": { "type": "object", "additionalProperties": true, "required": ["id", "name"], "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "order": { "type": "number" }, "camera": { "type": "object", "additionalProperties": true }, "projection": { "enum": ["persp", "ortho"] }, "mode": { "enum": ["solid", "wire", "xray"] }, "clips": { "type": "object", "additionalProperties": true }, "objects": { "type": "object", "additionalProperties": true } } } },
51
+ "views": { "type": "array", "description": "Draft-only saved views (Views Organizer, unlimited saved entries): each a named snapshot of the 3D viewpoint (camera + projection + display mode + clip boxes/planes + work area + the objects-list pane's persistent visibility/isolate state). F11-generated grid elevations and level plans also carry closed `generated` provenance so their cut depths remain editable. Editor state, model-global. NOT baked into the lock / 3D scene / IFC / BOM.", "items": { "type": "object", "additionalProperties": true, "required": ["id", "name"], "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "order": { "type": "number" }, "camera": { "type": "object", "additionalProperties": true }, "projection": { "enum": ["persp", "ortho"] }, "mode": { "enum": ["solid", "wire", "xray"] }, "clips": { "type": "object", "additionalProperties": true }, "objects": { "type": "object", "additionalProperties": true }, "generated": { "oneOf": [{ "type": "object", "additionalProperties": false, "required": ["v", "kind", "sheet", "label", "at", "look", "ahead", "behind"], "properties": { "v": { "const": 1 }, "kind": { "enum": ["grid-x", "grid-y"] }, "sheet": { "type": "string" }, "label": { "type": "string" }, "at": { "type": "number" }, "look": { "enum": ["positive", "negative"] }, "ahead": { "type": "number", "exclusiveMinimum": 0 }, "behind": { "type": "number", "exclusiveMinimum": 0 } } }, { "type": "object", "additionalProperties": false, "required": ["v", "kind", "sheet", "label", "at", "look", "above", "below"], "properties": { "v": { "const": 1 }, "kind": { "const": "level" }, "sheet": { "type": "string" }, "label": { "type": "string" }, "at": { "type": "number" }, "look": { "const": "down" }, "above": { "type": "number", "exclusiveMinimum": 0 }, "below": { "type": "number", "exclusiveMinimum": 0 } } }] } } } },
52
52
  "prop_labels": {
53
53
  "type": "object",
54
54
  "additionalProperties": true,
@@ -1000,8 +1000,11 @@ function reframeOrtho() {
1000
1000
  orthoCam.updateProjectionMatrix();
1001
1001
  }
1002
1002
 
1003
- function fitCamera(box, dir) {
1004
- if (box.isEmpty()) return;
1003
+ // Calculate a fitted camera as plain values without touching the live cameras/controls. F11 uses this
1004
+ // to create a whole batch of saved section views without visibly teleporting the current viewport;
1005
+ // fitCamera below applies the exact same result for ordinary Fit/ViewCube actions.
1006
+ function cameraFitForBox(box, dir) {
1007
+ if (!box || box.isEmpty()) return null;
1005
1008
  const c = box.getCenter(new THREE.Vector3());
1006
1009
  const d = dir ? dir.clone().normalize() : new THREE.Vector3(0.55, -0.8, 0.5).normalize(); // default 3/4 iso
1007
1010
  // Build the camera's right/up axes for this view direction, then size the distance so the WIDEST
@@ -1023,6 +1026,13 @@ function fitCamera(box, dir) {
1023
1026
  need = Math.max(need, cd + Math.max(cr / tanH, cu / tanV));
1024
1027
  }
1025
1028
  const dist = need * 1.15; // small margin
1029
+ return { center: c, direction: d, dist, orthoH: Math.max(extU, extR / aspect) * 1.15 };
1030
+ }
1031
+
1032
+ function fitCamera(box, dir) {
1033
+ const fit = cameraFitForBox(box, dir);
1034
+ if (!fit) return;
1035
+ const { center: c, direction: d, dist } = fit;
1026
1036
  controls.target.copy(c);
1027
1037
  perspCam.position.copy(c).addScaledVector(d, dist);
1028
1038
  orthoCam.position.copy(c).addScaledVector(d, dist);
@@ -1035,7 +1045,7 @@ function fitCamera(box, dir) {
1035
1045
  const far = Math.max(dist + r * 4, perspCam.position.distanceTo(sceneSph.center) + sceneSph.radius) * 1.02;
1036
1046
  perspCam.near = near; perspCam.far = far; perspCam.updateProjectionMatrix();
1037
1047
  orthoCam.near = near; orthoCam.far = far; orthoCam.zoom = 1;
1038
- orthoBaseH = Math.max(extU, extR / aspect) * 1.15; // tight, aspect-preserving box fit (no ortho under-frame)
1048
+ orthoBaseH = fit.orthoH; // tight, aspect-preserving box fit (no ortho under-frame)
1039
1049
  if (camera === orthoCam) reframeOrtho();
1040
1050
  controls.update();
1041
1051
  }
@@ -1541,6 +1551,45 @@ function setCameraState(s) {
1541
1551
  controls.update();
1542
1552
  }
1543
1553
 
1554
+ // F11: build one clean orthographic camera + clip snapshot from an explicit world-mm cut box,
1555
+ // WITHOUT changing the live camera, projection, clips, selection, or visibility. The editor calls
1556
+ // this repeatedly for a batch. A cut that reaches no rendered model mesh returns null — never save
1557
+ // a blank view that only happens to overlap the coarse whole-scene envelope.
1558
+ function sectionViewState(boxData, direction, label) {
1559
+ const finite3 = (a) => Array.isArray(a) && a.length === 3 && a.every((n) => typeof n === 'number' && Number.isFinite(n));
1560
+ if (!boxData || !finite3(boxData.min) || !finite3(boxData.max) || !finite3(direction)) return null;
1561
+ if (!boxData.min.every((n, i) => n < boxData.max[i])) return null;
1562
+ const dl = Math.hypot(direction[0], direction[1], direction[2]);
1563
+ if (!(dl > 1e-9)) return null;
1564
+ const cut = new THREE.Box3(new THREE.Vector3(...boxData.min), new THREE.Vector3(...boxData.max));
1565
+ const framed = new THREE.Box3(), mb = new THREE.Box3();
1566
+ if (root) root.updateMatrixWorld(true);
1567
+ for (const mesh of meshById.values()) {
1568
+ mb.setFromObject(mesh);
1569
+ if (mb.isEmpty() || !mb.intersectsBox(cut)) continue;
1570
+ const clipped = mb.clone().intersect(cut);
1571
+ if (!clipped.isEmpty()) framed.union(clipped);
1572
+ }
1573
+ if (framed.isEmpty()) return null;
1574
+ const fit = cameraFitForBox(framed, new THREE.Vector3(...direction));
1575
+ if (!fit) return null;
1576
+ const pos = fit.center.clone().addScaledVector(fit.direction, fit.dist).toArray();
1577
+ const clipLabel = (typeof label === 'string' && label.trim()) ? label.trim().slice(0, 80) : 'Generated cut';
1578
+ return {
1579
+ camera: { v: 1, pos, target: fit.center.toArray(), proj: 'ortho', orthoH: fit.orthoH, zoom: 1 },
1580
+ clips: {
1581
+ clips: [{ id: 'generated-cut', kind: 'box', enabled: true, label: clipLabel,
1582
+ box: { min: boxData.min.slice(), max: boxData.max.slice() } }],
1583
+ workArea: null, selected: [], seq: 1,
1584
+ },
1585
+ };
1586
+ }
1587
+
1588
+ function sceneBounds() {
1589
+ if (!sceneBox || sceneBox.isEmpty()) return null;
1590
+ return { min: sceneBox.min.toArray(), max: sceneBox.max.toArray() };
1591
+ }
1592
+
1544
1593
  function frameAll() { fitCamera(sceneBox); }
1545
1594
  const VIEWS = { top: [0, 0, 1], bottom: [0, 0, -1], front: [0, -1, 0], back: [0, 1, 0], right: [1, 0, 0], left: [-1, 0, 0], iso: [0.55, -0.8, 0.5] };
1546
1595
  function applyView(name) { const d = VIEWS[name]; if (d) fitCamera(sceneBox, new THREE.Vector3(d[0], d[1], d[2])); }
@@ -3726,7 +3775,7 @@ window.Steel3DView = {
3726
3775
  toggleGroup, setGroupsHidden, setIdsHidden, connHiddenIds: () => [...connHidden], soloToggle, setSoloGroups, showAllGroups, groupState, getGroups,
3727
3776
  setClipMode, clipMode: clipModeOn, addClipBox, toggleClip, removeClip, clearClips, getClips, renameClip, selectClip, setSelectedClips, selectedClips, deleteSelectedClips, clipState, setClipState,
3728
3777
  isolateSelected, clearIsolation, isIsolated,
3729
- cameraState, setCameraState, objectsPaneState, applyObjectsPaneState, // saved-view snapshot surface (Views Organizer)
3778
+ cameraState, setCameraState, sectionViewState, sceneBounds, objectsPaneState, applyObjectsPaneState, // saved-view snapshot surface (Views Organizer + F11 generated cuts)
3730
3779
  workAreaSetAll, workAreaFromSelection, workAreaToggle, workAreaSetWhole, clearWorkArea, workAreaState,
3731
3780
  armWorkPlanePick, setWorkPlanePrincipal, clearWorkPlane, toggleWorkPlaneVisible, workPlaneInfo,
3732
3781
  armFrame3d, disarmFrame3d, repickFrame3d, setFrame3d, setFrameBasis, setFrameAngle, setFrameOrigin, clearFrame3d, frameInfo, frameArmed: () => frameMode, framePicking, framePickStep, frameHandlesScreen, // 3D local drawing frame (UCS stage 1)
@@ -149,7 +149,7 @@
149
149
  g.pdfvec path{fill:none;stroke:#334155;stroke-width:.7;vector-effect:non-scaling-stroke;opacity:.82;stroke-linecap:round;stroke-linejoin:round}
150
150
  g.pdfvec circle{fill:none;stroke:#334155;stroke-width:.7;vector-effect:non-scaling-stroke;opacity:.55}
151
151
  g.cohot:hover text.cotx{opacity:1}
152
- #detailsModal,#framesModal,#rfiModal,#confModal,#askAiModal,#connModal,#connImportModal,#favConnModal{position:fixed;inset:0;z-index:20;display:none;align-items:center;justify-content:center}
152
+ #detailsModal,#framesModal,#rfiModal,#confModal,#askAiModal,#connModal,#connImportModal,#favConnModal,#viewGenModal{position:fixed;inset:0;z-index:20;display:none;align-items:center;justify-content:center}
153
153
  #askAiDrop:hover{border-color:var(--brand);color:var(--text)} #askAiDrop.has{border-style:solid;border-color:var(--brand)}
154
154
  .aithumb{position:relative;display:inline-flex} .aithumb img{height:60px;border-radius:4px;border:1px solid var(--line);background:#fff;display:block}
155
155
  .aithumb button{position:absolute;top:-5px;right:-5px;width:16px;height:16px;padding:0;border-radius:8px;font-size:10px;line-height:16px;text-align:center;background:#7f1d1d;border-color:#991b1b;color:#fecaca}
@@ -423,6 +423,36 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
423
423
  .gbtns{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px} .gbtns button{margin:0}
424
424
  .gck{display:flex;align-items:center;gap:8px;color:var(--text);cursor:pointer;font-size:12px;padding:2px 0}
425
425
  .gck input{accent-color:var(--brand);cursor:pointer;margin:0;width:14px;height:14px;flex:none} /* beat the panel's generic full-width input rule */
426
+ /* F11 generated views modal — baseline modal/tabs/inputs, sized for batch selection without crowding the 240px Views pane. */
427
+ #viewGenModal .mpanel{width:min(640px,92vw)}
428
+ #vgBody{display:flex;flex-direction:column;min-height:0}
429
+ #vgContext{padding:10px 14px;color:var(--mut);font-size:12px;border-bottom:1px solid var(--line)}
430
+ #vgTabs{display:flex;gap:4px;padding:10px 14px 0}
431
+ #vgTabs button{border:0;border-radius:5px;background:transparent;color:var(--mut);padding:6px 10px;box-shadow:none}
432
+ #vgTabs button[aria-selected=true]{background:rgba(59,130,246,.16);color:var(--text);box-shadow:inset 0 -2px 0 var(--brand)}
433
+ #vgTools{display:flex;align-items:center;gap:8px;padding:8px 14px}
434
+ #vgTools button{padding:4px 8px;background:transparent;box-shadow:none}
435
+ #vgCount{margin-left:auto;color:var(--mut);font-size:11px;font-variant-numeric:tabular-nums}
436
+ #vgList{margin:0 14px;min-height:120px;max-height:260px;overflow:auto;border:1px solid var(--line);border-radius:7px;background:var(--bg);padding:5px}
437
+ #vgList .vggroup{padding:5px 7px 3px;color:var(--mut);font-size:10px;text-transform:uppercase;letter-spacing:.07em}
438
+ #vgList .vgrow{display:flex;align-items:center;gap:9px;padding:6px 8px;border-radius:5px;cursor:pointer}
439
+ #vgList .vgrow:hover{background:#33415580}
440
+ #vgList .vgrow input{accent-color:var(--brand);width:14px;height:14px;margin:0;flex:none}
441
+ #vgList .vgaxis{width:18px;color:var(--mut);font-size:10px;font-weight:700}
442
+ #vgList .vgname{color:var(--text);font-size:12px}
443
+ #vgList .vgempty{padding:28px 16px;text-align:center;color:var(--mut);font-size:12px;line-height:1.5}
444
+ #vgSettings{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 12px;padding:12px 14px}
445
+ #vgSettings .vgfield label{display:block;color:var(--mut);font-size:10px;text-transform:uppercase;letter-spacing:.06em;margin-bottom:3px}
446
+ #vgSettings input{width:100%;height:30px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:6px;padding:0 8px;font:12px ui-monospace,Consolas,monospace}
447
+ #vgSettings input:focus{outline:none;border-color:var(--brand)}
448
+ #vgSettings input[aria-invalid=true]{border-color:#fca5a5}
449
+ #vgDirection{grid-column:1/-1;display:flex;align-items:center;gap:10px}
450
+ #vgDirection .grp{display:inline-flex;border:1px solid var(--line);border-radius:6px;overflow:hidden}
451
+ #vgDirection .grp button{border:0;border-radius:0;background:transparent;color:var(--mut);padding:5px 10px;box-shadow:none}
452
+ #vgDirection .grp button.on{background:var(--brand);color:#fff}
453
+ #vgError{grid-column:1/-1;min-height:15px;color:#fca5a5;font-size:11px}
454
+ #vgFoot{display:flex;align-items:center;justify-content:flex-end;gap:8px;padding:10px 14px;border-top:1px solid var(--line)}
455
+ #vgCreate:disabled{opacity:.45;cursor:default}
426
456
  body.dimsplit #svg,body.dimsplit line.member,body.dimsplit line.seg,body.dimsplit line.dim,body.dimsplit line.dimwit,body.dimsplit image{cursor:crosshair} /* whole-canvas crosshair while the split/extend tool is armed — you can click anywhere, not just on a line (B8) */
427
457
  .dimprev{opacity:.85} line.dim.dimprev{stroke-dasharray:7 4}
428
458
  body.dimon #svg,body.dimon line.member,body.dimon line.seg,body.dimon image,body.add #svg,body.add line.member,body.add line.seg,body.add image,body.add polygon.member,body.add rect.pdfsheet{cursor:crosshair} /* Add-member is click-to-place like the Dimension tool → the whole canvas shows the crosshair */
@@ -665,17 +695,9 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
665
695
  #vwSaveBtn{flex:1;min-width:0;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
666
696
  #vwSaveMore{flex:none;width:24px;padding:0;border-left:1px solid rgba(255,255,255,.28)!important}
667
697
  #vwSaveSplit button:disabled{opacity:.45;cursor:default;background:var(--brand)}
668
- /* the split, disabled at the cap — a muted, non-branded look so it reads clearly as unavailable */
669
- #vwSaveSplit.capped{border-color:var(--line)}
670
- #vwSaveSplit.capped button{background:#334155;color:var(--mut)}
671
- #vwSaveSplit.capped #vwSaveMore{border-left-color:rgba(148,163,184,.28)!important}
672
698
  #vwSearchTog{flex:none;width:30px;padding:0;display:inline-flex;align-items:center;justify-content:center;color:var(--mut)}
673
699
  #vwSearchTog.on{color:var(--brand);border-color:var(--brand)}
674
700
  #vwSearchTog svg{display:block}
675
- /* the cap counter ("8/10") + the disabled reason line — visible, quiet, inline (not tooltip-only) */
676
- #vwCount{flex:none;font-size:10px;color:var(--mut);text-align:right;font-variant-numeric:tabular-nums;margin-bottom:4px;display:none}
677
- #vwCap{flex:none;font-size:10px;color:#fbbf24;line-height:1.4;margin-bottom:6px;display:none}
678
- #vwCap.show{display:block} #vwCount.show{display:block}
679
701
  /* search box — reuses the objects-list .lsearch recipe; hidden until the 🔍 toggle opens it */
680
702
  #vwSearch{display:none;align-items:center;gap:6px;height:26px;margin-bottom:6px;padding:0 8px;background:var(--bg);border:1px solid var(--line);border-radius:6px;flex:none}
681
703
  #vwSearch.show{display:flex}
@@ -958,6 +980,25 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
958
980
  <datalist id=conntypes><option>moment</option><option>drag</option><option>shear</option><option>braced</option><option>pinned</option><option>fixed</option></datalist>
959
981
  <datalist id=profiles></datalist>
960
982
  <datalist id=details></datalist>
983
+ <div id=viewGenModal role=dialog aria-modal=true aria-labelledby=vgTitle>
984
+ <div class=mbackdrop id=vgBackdrop></div>
985
+ <div class=mpanel>
986
+ <div class=mhead><b id=vgTitle>Generate views from grids or levels</b><button id=vgClose data-tip="Close">✕</button></div>
987
+ <div id=vgBody>
988
+ <div id=vgContext></div>
989
+ <div id=vgTabs role=tablist aria-label="View source"><button id=vgGridTab role=tab aria-selected=true>Grid lines</button><button id=vgLevelTab role=tab aria-selected=false>Levels</button></div>
990
+ <div id=vgTools><button id=vgAll>Select all</button><button id=vgClear>Clear</button><span id=vgCount aria-live=polite>0 selected</span></div>
991
+ <div id=vgList role=tabpanel aria-label="Grid lines"></div>
992
+ <div id=vgSettings>
993
+ <div id=vgDirection><span class=elab style="margin:0">Look direction</span><div class=grp role=group aria-label="Grid look direction"><button id=vgPositive class=on aria-pressed=true data-tip="Look toward increasing world X or Y">Positive</button><button id=vgNegative aria-pressed=false data-tip="Flip the section to look toward decreasing world X or Y">Flipped</button></div></div>
994
+ <div class=vgfield id=vgFieldA><label for=vgDepthA>Ahead</label><input id=vgDepthA value='24"' inputmode=decimal autocomplete=off></div>
995
+ <div class=vgfield id=vgFieldB><label for=vgDepthB>Behind</label><input id=vgDepthB value='24"' inputmode=decimal autocomplete=off></div>
996
+ <div id=vgError role=status aria-live=polite></div>
997
+ </div>
998
+ </div>
999
+ <div id=vgFoot><button id=vgCancel class=ghost>Cancel</button><button id=vgCreate disabled>Create 0 views</button></div>
1000
+ </div>
1001
+ </div>
961
1002
  <div id=detailsModal><div class=mbackdrop id=detailsBackdrop></div>
962
1003
  <div class=mpanel><div class=mhead><b>Connection details</b><div style="display:flex;gap:8px;align-items:center"><button id=detailNew>+ New detail</button><button id=detailsClose>✕</button></div></div>
963
1004
  <div id=detailNewForm style="display:none;padding:14px;border-bottom:1px solid var(--line)">
@@ -1057,6 +1098,7 @@ const PROJECT = new URLSearchParams(location.search).get('project') || '';
1057
1098
  const PROJECT_QS = PROJECT ? ('?project=' + encodeURIComponent(PROJECT)) : '';
1058
1099
  let C, PAL, WT;
1059
1100
  let SteelCore = null; // steel-3d-core.js module namespace — boot() awaits its dynamic import before main() so the classic script can call its pure helpers (sanitizeDims3d) at load
1101
+ let ViewGen = null; // steel-view-generation.js pure F11 helpers — loaded before saved views are sanitised
1060
1102
  let TARGET_CONF = null; // the app's target_confidence input default (%), or null when undeclared — drives the chip's "· target N%" goal
1061
1103
  let view3d = false, view3dReady = false; // 2D|3D toggle state; view3dReady once Steel3DView.init has run
1062
1104
  // Fallback palette (colorFor indexes this array by profile order) when a contract ships no `palette`
@@ -1076,7 +1118,7 @@ function showEmpty(icon, headline, bodyText, appIdText) {
1076
1118
  }
1077
1119
  async function boot() {
1078
1120
  if (!APP_ID) { showEmpty('⊞', 'No workflow selected', 'Open a workflow in the FloLess canvas, then open the contract editor from that workflow’s node.'); return; }
1079
- SteelCore = await import('./steel-3d-core.js'); // await BEFORE main()/restoreSaved() so the mandatory dims3d sanitizer is loaded (no deferred-module race — a passive window shim could be undefined here)
1121
+ [SteelCore, ViewGen] = await Promise.all([import('./steel-3d-core.js'), import('./steel-view-generation.js')]); // await BEFORE main()/restoreSaved(): both draft-state sanitisers must exist at the load boundary
1080
1122
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS);
1081
1123
  if (!res.ok) {
1082
1124
  if (res.status === 404) {
@@ -1500,8 +1542,8 @@ function setSaved(state,msg){const el=document.getElementById('saveStat');if(!el
1500
1542
  // partial/stale server or localStorage draft (same discipline as dim_overlays): drops non-objects, mints a
1501
1543
  // missing id/name, clamps the display mode/projection to known values, keeps the opaque camera/clips/objects
1502
1544
  // snapshots as-is (activateView applies each defensively — a malformed sub-snapshot is caught, not fatal —
1503
- // since the engine's setClipState does NOT re-sanitise its input), and caps the list at 10.
1504
- function sanitizeViews(arr){if(!Array.isArray(arr))return [];const out=[];for(const v of arr){if(!v||typeof v!=='object')continue;const id=(typeof v.id==='string'&&v.id)?v.id:('v'+Math.random().toString(36).slice(2,9));const name=(typeof v.name==='string'&&v.name.trim())?v.name.slice(0,80):'View';out.push({v:1,id,name,order:typeof v.order==='number'?v.order:out.length,camera:(v.camera&&typeof v.camera==='object')?v.camera:null,projection:v.projection==='ortho'?'ortho':'persp',mode:['solid','wire','xray'].includes(v.mode)?v.mode:'solid',clips:(v.clips&&typeof v.clips==='object')?v.clips:null,objects:(v.objects&&typeof v.objects==='object')?v.objects:null});if(out.length>=10)break;}return out;}
1545
+ // since the engine's setClipState does NOT re-sanitise its input). The saved-view library is unlimited.
1546
+ function sanitizeViews(arr){return ViewGen.sanitizeViews(arr);}
1505
1547
  // B9: do NOT flip to 'Saved ✓' here. localStorage is the instant per-browser draft; the durable copy is the
1506
1548
  // async persistServer() PUT (or flushContract()), which resolves later and OWNS the 'ok'/'err' transition — so
1507
1549
  // green means the server truly has it. Every persist() caller is paired with such a server write (before or
@@ -1553,7 +1595,7 @@ function restoreSaved(){try{const raw=localStorage.getItem(LSKEY);if(!raw)return
1553
1595
  if('dim_style' in d){C.dim_style=d.dim_style;sanitizeDimStyle();} // restore the model-global dimension-style defaults — sanitised to the three known keys
1554
1596
  if('prop_labels' in d)C.prop_labels=sanitizePropLabels(d.prop_labels); // restore canvas property-label display state (sanitised to known keys/placement)
1555
1597
  if(Array.isArray(d.joints))C.joints=d.joints; // restore model-global connection joints (base plates) from the local draft
1556
- if(Array.isArray(d.views))C.views=sanitizeViews(d.views); // restore saved views (Views Organizer) from the local draft — sanitised to clean, capped entries
1598
+ if(Array.isArray(d.views))C.views=sanitizeViews(d.views); // restore the unlimited saved-view library from the local draft; malformed generated provenance is dropped
1557
1599
  if(d.active!=null)C.active=d.active;return true;}catch(e){console.warn('discarding corrupt local draft',e);return false;}}
1558
1600
  function updUR(){document.getElementById('undoB').disabled=!undo.length;document.getElementById('redoB').disabled=!redo.length;}
1559
1601
  // Canonical, model-global palette rank (B2): EVERY plan's non-blank member profiles ∪ weight-table keys,
@@ -4960,15 +5002,17 @@ function wireLegendTabs(){if(legendTabsWired)return;legendTabsWired=true;
4960
5002
  document.querySelectorAll('#m3dTabs .m3dtab').forEach(b=>b.addEventListener('click',()=>setLegendTab(b.dataset.tab)));
4961
5003
  }
4962
5004
  // ── Views state ──────────────────────────────────────────────────────────────────────────────────────────────
4963
- const VIEWS_MAX=10;
4964
5005
  let viewsQuery=''; // transient Views-tab search filter — NOT persisted
4965
5006
  let viewsSearchOpen=false; // is the search input revealed?
4966
5007
  let activeViewId=null; // the view whose snapshot was last applied (persistent active affordance) — transient
5008
+ let viewGenState=null; // transient F11 modal state; generated views themselves persist in C.views
5009
+ let viewGenLauncher=null;
4967
5010
  function viewsSorted(){return (C.views||[]).slice().sort((a,b)=>(a.order||0)-(b.order||0));}
4968
5011
  // Glyph: a small cube-face pictogram for the 6 direction presets (recognised by the view's name — the source of
4969
5012
  // truth that survives sanitizeViews), a generic camera otherwise. Muted, a recognition aid only.
4970
5013
  const VIEW_DIRS={top:1,bottom:1,front:1,back:1,left:1,right:1,iso:1};
4971
- function viewDirOf(v){const n=((v&&v.name)||'').trim().toLowerCase();return VIEW_DIRS[n]?n:null;}
5014
+ function viewDirOf(v){const g=v&&v.generated;if(g){if(g.kind==='level')return 'top';if(g.kind==='grid-x')return g.look==='negative'?'right':'left';if(g.kind==='grid-y')return g.look==='negative'?'back':'front';}
5015
+ const n=((v&&v.name)||'').trim().toLowerCase();return VIEW_DIRS[n]?n:null;}
4972
5016
  function viewGlyph(v){const NS='http://www.w3.org/2000/svg',dir=viewDirOf(v);
4973
5017
  const svg=document.createElementNS(NS,'svg');svg.setAttribute('viewBox','0 0 16 16');svg.setAttribute('width','12');svg.setAttribute('height','12');svg.setAttribute('fill','none');svg.setAttribute('stroke','currentColor');svg.setAttribute('stroke-width','1.3');svg.setAttribute('stroke-linejoin','round');svg.setAttribute('aria-hidden','true');
4974
5018
  if(dir){ // a small cube with the active face tinted — a direction pictogram (top/front/side highlighted)
@@ -4994,12 +5038,12 @@ function captureView(name){const V=window.Steel3DView;
4994
5038
  return {v:1,id:'v'+Math.random().toString(36).slice(2,9),name:name||('View '+((C.views||[]).length+1)),order:0,
4995
5039
  camera:V.cameraState?V.cameraState():null,projection:V.projection?V.projection():'persp',mode:V.mode?V.mode():'solid',
4996
5040
  clips:V.clipState?V.clipState():null,objects:V.objectsPaneState?V.objectsPaneState():null};}
4997
- // Push a captured view to the TOP (order 0; bump the rest), cap-guarded, then persist + re-render + inline-rename it.
4998
- function addView(v,{rename=true}={}){if(!Array.isArray(C.views))C.views=[];if(C.views.length>=VIEWS_MAX)return null;
5041
+ // Push a captured view to the TOP (order 0; bump the rest), then persist + re-render + inline-rename it.
5042
+ function addView(v,{rename=true}={}){if(!Array.isArray(C.views))C.views=[];
4999
5043
  for(const x of C.views)x.order=(x.order||0)+1;v.order=0;C.views.push(v);activeViewId=v.id;scheduleSave();renderViewsTab();
5000
5044
  if(rename){const row=document.querySelector('#m3dViewsBody .vwrow[data-id="'+v.id+'"]');if(row)startViewRename(v,row);}
5001
5045
  return v;}
5002
- function saveCurrentView(){if((C.views||[]).length>=VIEWS_MAX)return;addView(captureView());}
5046
+ function saveCurrentView(){addView(captureView());}
5003
5047
  // New from a direction preset: apply the clean preset camera, then capture (current mode; no clips/isolate baked —
5004
5048
  // captureView reads clipState/objectsPaneState, but from a clean preset these carry the current scene; the spec's
5005
5049
  // intent is a clean viewpoint, so we snapshot right after applyView which only moved the camera).
@@ -5039,8 +5083,8 @@ function startViewRename(v,row){const nameEl=row.querySelector('.vwname');if(!na
5039
5083
  inp.addEventListener('blur',()=>finish(true));
5040
5084
  }
5041
5085
  // ── Row ⋯ menu: Rename / Duplicate / Update to current ──────────────────────────────────────────────────────────
5042
- function updateViewToCurrent(v){const snap=captureView(v.name);snap.id=v.id;snap.order=v.order;v.camera=snap.camera;v.projection=snap.projection;v.mode=snap.mode;v.clips=snap.clips;v.objects=snap.objects;activeViewId=v.id;scheduleSave();renderViewsTab();toast('Updated “'+v.name+'” to the current view');}
5043
- function duplicateView(v){if((C.views||[]).length>=VIEWS_MAX){toast(VIEWS_MAX+' of '+VIEWS_MAX+' views — delete one to duplicate');return;}
5086
+ function updateViewToCurrent(v){const snap=captureView(v.name);snap.id=v.id;snap.order=v.order;v.camera=snap.camera;v.projection=snap.projection;v.mode=snap.mode;v.clips=snap.clips;v.objects=snap.objects;delete v.generated;v.v=1;activeViewId=v.id;scheduleSave();renderViewsTab();toast('Updated “'+v.name+'” to the current view');}
5087
+ function duplicateView(v){
5044
5088
  const copy=JSON.parse(JSON.stringify(v));copy.id='v'+Math.random().toString(36).slice(2,9);copy.name=uniqueViewName(v.name+' copy');
5045
5089
  // insert right after the source in order
5046
5090
  for(const x of C.views)if((x.order||0)>(v.order||0))x.order=(x.order||0)+1;copy.order=(v.order||0)+1;C.views.push(copy);activeViewId=copy.id;scheduleSave();renderViewsTab();}
@@ -5061,9 +5105,7 @@ function closeViewRowMenu(){const m=document.getElementById('vwRowMenu');if(m)m.
5061
5105
  // ── Delete (immediate + undo toast that re-inserts at the original order) ────────────────────────────────────────
5062
5106
  function deleteView(v){const idx=(C.views||[]).findIndex(x=>x.id===v.id);if(idx<0)return;const removed=C.views[idx];const order=removed.order;
5063
5107
  C.views.splice(idx,1);if(activeViewId===v.id)activeViewId=null;scheduleSave();renderViewsTab();
5064
- // Undo takes precedence over the soft 10-cap: restoring a view the user just deleted is them reversing their
5065
- // own action, so re-add unconditionally (a transient 11th is fine — the cap only gates NEW saves). Refusing
5066
- // here would make the Undo affordance silently destroy data it promised to restore.
5108
+ // Re-add unconditionally: Undo must restore the exact saved entry and its original order.
5067
5109
  undoToast('Deleted “'+removed.name+'”',()=>{if(!Array.isArray(C.views))C.views=[];removed.order=order;C.views.push(removed);scheduleSave();renderViewsTab();});
5068
5110
  }
5069
5111
  // ── Reorder (pointer-drag a row; the drag-handle is the initiator — same recipe as the objects-list rows) ─────────
@@ -5088,18 +5130,15 @@ function toggleViewsSearch(){viewsSearchOpen=!viewsSearchOpen;if(!viewsSearchOpe
5088
5130
  if(viewsSearchOpen){const inp=document.getElementById('vwSearchInput');if(inp)inp.focus();}}
5089
5131
  // ── Render the Views tab body from C.views[] ────────────────────────────────────────────────────────────────────
5090
5132
  function renderViewsTab(){const host=document.getElementById('m3dViewsBody');if(!host)return;host.replaceChildren();
5091
- const all=viewsSorted();const atMax=all.length>=VIEWS_MAX;
5133
+ const all=viewsSorted();
5092
5134
  // Header row: Save-current-view split (main + ▾) · search toggle
5093
5135
  const head=document.createElement('div');head.id='vwHeadRow';
5094
- const split=document.createElement('div');split.id='vwSaveSplit';if(atMax)split.classList.add('capped');
5095
- const saveBtn=document.createElement('button');saveBtn.type='button';saveBtn.id='vwSaveBtn';saveBtn.textContent='+ Save current view';saveBtn.dataset.tip=atMax?(VIEWS_MAX+' of '+VIEWS_MAX+' views — delete one to add'):'Save the current camera, display mode, clips and object visibility as a named view';saveBtn.disabled=atMax;saveBtn.addEventListener('click',saveCurrentView);
5096
- const moreBtn=document.createElement('button');moreBtn.type='button';moreBtn.id='vwSaveMore';moreBtn.textContent='▾';moreBtn.setAttribute('aria-haspopup','menu');moreBtn.dataset.tip='New view from a direction (Top, Front, Iso, …)';moreBtn.disabled=atMax;moreBtn.addEventListener('click',e=>{e.stopPropagation();openNewFromDirectionMenu(moreBtn);});
5136
+ const split=document.createElement('div');split.id='vwSaveSplit';
5137
+ const saveBtn=document.createElement('button');saveBtn.type='button';saveBtn.id='vwSaveBtn';saveBtn.textContent='+ Save current view';saveBtn.dataset.tip='Save the current camera, display mode, clips and object visibility as a named view';saveBtn.addEventListener('click',saveCurrentView);
5138
+ const moreBtn=document.createElement('button');moreBtn.type='button';moreBtn.id='vwSaveMore';moreBtn.textContent='▾';moreBtn.setAttribute('aria-haspopup','menu');moreBtn.dataset.tip='Create a view from a direction, grid line, or level';moreBtn.addEventListener('click',e=>{e.stopPropagation();openNewFromDirectionMenu(moreBtn);});
5097
5139
  split.append(saveBtn,moreBtn);
5098
5140
  const searchTog=document.createElement('button');searchTog.type='button';searchTog.id='vwSearchTog';searchTog.setAttribute('aria-label','Search views');searchTog.dataset.tip='Search views by name';if(viewsSearchOpen)searchTog.classList.add('on');searchTog.appendChild(magnifierSvg());searchTog.addEventListener('click',toggleViewsSearch);
5099
5141
  head.append(split,searchTog);host.appendChild(head);
5100
- // Cap counter (N/10 when N≥8) + the disabled reason (at 10)
5101
- const cnt=document.createElement('div');cnt.id='vwCount';cnt.textContent=all.length+'/'+VIEWS_MAX;if(all.length>=8)cnt.classList.add('show');host.appendChild(cnt);
5102
- if(atMax){const cap=document.createElement('div');cap.id='vwCap';cap.className='show';cap.textContent=VIEWS_MAX+' of '+VIEWS_MAX+' views — delete one to add.';host.appendChild(cap);}
5103
5142
  // Search box (revealed on demand)
5104
5143
  if(viewsSearchOpen){const sb=document.createElement('div');sb.id='vwSearch';sb.className='show'+(viewsQuery?' has':'');
5105
5144
  const ico=Object.assign(document.createElement('span'),{className:'lsico'});ico.setAttribute('aria-hidden','true');ico.appendChild(magnifierSvg());
@@ -5144,12 +5183,73 @@ function openNewFromDirectionMenu(anchorEl){closeViewRowMenu();
5144
5183
  const DIRS=[['top','Top'],['front','Front'],['back','Back'],['left','Left'],['right','Right'],['iso','Iso']];
5145
5184
  const lab=Object.assign(document.createElement('div'),{className:'mlabel',textContent:'New from direction'});m.appendChild(lab);
5146
5185
  for(const [dir,label] of DIRS){const b=document.createElement('button');b.type='button';b.textContent=label;b.setAttribute('role','menuitem');b.addEventListener('click',()=>{closeViewRowMenu();saveViewFromDirection(dir);});m.appendChild(b);}
5186
+ const hr=document.createElement('hr');m.appendChild(hr);
5187
+ const generated=document.createElement('button');generated.type='button';generated.textContent='Generate from grid or level…';generated.setAttribute('role','menuitem');generated.addEventListener('click',()=>{closeViewRowMenu();openViewGenerator(anchorEl);});m.appendChild(generated);
5147
5188
  document.body.appendChild(m);
5148
- const r=anchorEl.getBoundingClientRect();const mw=m.offsetWidth||160,mh=m.offsetHeight||210;
5189
+ const r=anchorEl.getBoundingClientRect();const mw=m.offsetWidth||190,mh=m.offsetHeight||250;
5149
5190
  let x=r.right-mw,y=r.bottom+4;if(x<6)x=6;if(y+mh>innerHeight-6)y=r.top-mh-4;if(y<6)y=6;
5150
5191
  m.style.left=x+'px';m.style.top=y+'px';
5151
5192
  setTimeout(()=>document.addEventListener('mousedown',viewRowMenuOutside,true),0);
5152
5193
  }
5194
+
5195
+ // ── F11: batch-generate orthographic saved views from the active plan's regular X/Y grids or Z levels. ──
5196
+ function viewGenOpen(){return document.getElementById('viewGenModal').style.display==='flex';}
5197
+ function viewGenCurrentSources(){if(!viewGenState)return [];return viewGenState.tab==='levels'?viewGenState.sources.levels:[...viewGenState.sources.x,...viewGenState.sources.y];}
5198
+ function viewGenKey(s){return s.kind+':'+s.index;}
5199
+ function closeViewGenerator(){const modal=document.getElementById('viewGenModal');if(modal)modal.style.display='none';viewGenState=null;
5200
+ const target=viewGenLauncher&&viewGenLauncher.isConnected?viewGenLauncher:document.getElementById('vwSaveMore');viewGenLauncher=null;if(target)target.focus();}
5201
+ function openViewGenerator(launcher){const geo=gridGeo(),gc=GC();if(!geo||!gc){toast('This plan has no usable structural grid');return;}
5202
+ const sources=ViewGen.sourcesFromGrid(geo,gc.mmPerPx(P.pt_per_ft),P.sheet);
5203
+ viewGenLauncher=launcher||document.activeElement;viewGenState={tab:'grid',look:'positive',selected:new Set(),sources,
5204
+ depths:{grid:{ahead:'24"',behind:'24"'},levels:{above:'24"',below:'24"'}}};
5205
+ document.getElementById('vgContext').textContent='Active plan · '+(P.sheet||'Untitled sheet');
5206
+ document.getElementById('viewGenModal').style.display='flex';renderViewGenerator();document.getElementById('vgGridTab').focus();}
5207
+ function viewGenSetTab(tab){if(!viewGenState)return;viewGenState.tab=tab;renderViewGenerator();}
5208
+ function viewGenSyncInputs(){if(!viewGenState)return;const level=viewGenState.tab==='levels',raw=viewGenState.depths[viewGenState.tab];
5209
+ document.querySelector('#vgFieldA label').textContent=level?'Above':'Ahead';document.querySelector('#vgFieldB label').textContent=level?'Below':'Behind';
5210
+ document.getElementById('vgDepthA').value=level?raw.above:raw.ahead;document.getElementById('vgDepthB').value=level?raw.below:raw.behind;
5211
+ document.getElementById('vgDirection').style.display=level?'none':'flex';}
5212
+ function viewGenValidate(){if(!viewGenState)return null;const level=viewGenState.tab==='levels',raw=viewGenState.depths[viewGenState.tab];
5213
+ const parsed=ViewGen.parseDepths(level?'level':'grid',raw),a=document.getElementById('vgDepthA'),b=document.getElementById('vgDepthB');a.setAttribute('aria-invalid','false');b.setAttribute('aria-invalid','false');
5214
+ const err=document.getElementById('vgError');err.textContent=parsed.ok?'':parsed.error.charAt(0).toUpperCase()+parsed.error.slice(1)+'. Use ft-in, inches, metres, or mm.';
5215
+ if(!parsed.ok){if(parsed.error.startsWith(level?'above':'ahead'))a.setAttribute('aria-invalid','true');else b.setAttribute('aria-invalid','true');}
5216
+ const n=viewGenCurrentSources().filter(s=>viewGenState.selected.has(viewGenKey(s))).length,create=document.getElementById('vgCreate');create.textContent='Create '+n+' view'+(n===1?'':'s');create.disabled=!parsed.ok||n===0;return parsed;}
5217
+ function viewGenInput(){if(!viewGenState)return;const level=viewGenState.tab==='levels',a=document.getElementById('vgDepthA').value,b=document.getElementById('vgDepthB').value;
5218
+ viewGenState.depths[viewGenState.tab]=level?{above:a,below:b}:{ahead:a,behind:b};viewGenValidate();}
5219
+ function renderViewGenerator(){if(!viewGenState)return;const level=viewGenState.tab==='levels',gridTab=document.getElementById('vgGridTab'),levelTab=document.getElementById('vgLevelTab');
5220
+ gridTab.setAttribute('aria-selected',String(!level));levelTab.setAttribute('aria-selected',String(level));
5221
+ const list=document.getElementById('vgList');list.replaceChildren();list.setAttribute('aria-label',level?'Levels':'Grid lines');
5222
+ const addGroup=(title,axis,sources)=>{if(!sources.length)return;const gh=Object.assign(document.createElement('div'),{className:'vggroup',textContent:title});list.appendChild(gh);
5223
+ for(const s of sources){const row=document.createElement('label');row.className='vgrow';const ck=document.createElement('input');ck.type='checkbox';ck.checked=viewGenState.selected.has(viewGenKey(s));ck.dataset.source=viewGenKey(s);
5224
+ ck.addEventListener('change',()=>{if(ck.checked)viewGenState.selected.add(viewGenKey(s));else viewGenState.selected.delete(viewGenKey(s));viewGenReflectSelection();});
5225
+ const ax=Object.assign(document.createElement('span'),{className:'vgaxis',textContent:axis});const nm=Object.assign(document.createElement('span'),{className:'vgname',textContent:s.label});row.append(ck,ax,nm);list.appendChild(row);}};
5226
+ if(level)addGroup('Z elevations','Z',viewGenState.sources.levels);else{addGroup('X grids','X',viewGenState.sources.x);addGroup('Y grids','Y',viewGenState.sources.y);}
5227
+ if(!list.children.length){const empty=Object.assign(document.createElement('div'),{className:'vgempty',textContent:level?'This active plan has no Z levels. Add levels in Grid lines, then reopen this dialog.':'This active plan has no regular X or Y grid lines. Add grid spacings, then reopen this dialog.'});list.appendChild(empty);}
5228
+ document.getElementById('vgPositive').classList.toggle('on',viewGenState.look==='positive');document.getElementById('vgPositive').setAttribute('aria-pressed',String(viewGenState.look==='positive'));
5229
+ document.getElementById('vgNegative').classList.toggle('on',viewGenState.look==='negative');document.getElementById('vgNegative').setAttribute('aria-pressed',String(viewGenState.look==='negative'));
5230
+ viewGenSyncInputs();viewGenReflectSelection();}
5231
+ function viewGenReflectSelection(){if(!viewGenState)return;const current=viewGenCurrentSources(),n=current.filter(s=>viewGenState.selected.has(viewGenKey(s))).length;document.getElementById('vgCount').textContent=n+' of '+current.length+' selected';viewGenValidate();}
5232
+ function viewGenSelectAll(on){if(!viewGenState)return;for(const s of viewGenCurrentSources()){const k=viewGenKey(s);if(on)viewGenState.selected.add(k);else viewGenState.selected.delete(k);}renderViewGenerator();}
5233
+ function createGeneratedViews(){if(!viewGenState)return;const parsed=viewGenValidate();if(!parsed||!parsed.ok)return;const V=window.Steel3DView,bounds=V&&V.sceneBounds?V.sceneBounds():null;
5234
+ if(!bounds){document.getElementById('vgError').textContent='The 3D model is not ready. Close this dialog and try again.';return;}
5235
+ const selected=viewGenCurrentSources().filter(s=>viewGenState.selected.has(viewGenKey(s))),made=[],skipped=[],taken=new Set((C.views||[]).map(v=>v.name));
5236
+ const freshName=base=>{let name=base,i=2;while(taken.has(name))name=base+' '+i++;taken.add(name);return name;};
5237
+ for(const source of selected){const base=ViewGen.nameForSource(source),name=freshName(base),cut=ViewGen.cutForSource(source,parsed.values,viewGenState.look,bounds),snap=cut&&V.sectionViewState?V.sectionViewState(cut.box,cut.direction,name):null;
5238
+ if(!cut||!snap){taken.delete(name);skipped.push(base);continue;}made.push({v:2,id:'v'+Math.random().toString(36).slice(2,9),name,order:made.length,camera:snap.camera,projection:'ortho',mode:'solid',clips:snap.clips,objects:{v:1,hidden:[],solo:[],isolated:null,connHidden:[]},generated:cut.generated});}
5239
+ if(!made.length){document.getElementById('vgError').textContent=skipped.length?'No selected cut intersects the model. Increase the cut depths or choose another source.':'No views were created.';return;}
5240
+ if(!Array.isArray(C.views))C.views=[];for(const old of C.views)old.order=(old.order||0)+made.length;C.views.push(...made);scheduleSave();closeViewGenerator();renderViewsTab();
5241
+ setTimeout(()=>{for(const v of made){const row=document.querySelector('#m3dViewsBody .vwrow[data-id="'+v.id+'"]');if(row){row.classList.add('flash');setTimeout(()=>row.classList.remove('flash'),650);}}},0);
5242
+ const skippedMsg=skipped.length?' · skipped '+skipped.length+' empty: '+skipped.slice(0,3).join(', ')+(skipped.length>3?' +'+(skipped.length-3)+' more':''):'';
5243
+ toast('Created '+made.length+' view'+(made.length===1?'':'s')+skippedMsg);}
5244
+
5245
+ document.getElementById('vgGridTab').addEventListener('click',()=>viewGenSetTab('grid'));
5246
+ document.getElementById('vgLevelTab').addEventListener('click',()=>viewGenSetTab('levels'));
5247
+ document.getElementById('vgAll').addEventListener('click',()=>viewGenSelectAll(true));document.getElementById('vgClear').addEventListener('click',()=>viewGenSelectAll(false));
5248
+ document.getElementById('vgPositive').addEventListener('click',()=>{if(viewGenState){viewGenState.look='positive';renderViewGenerator();}});document.getElementById('vgNegative').addEventListener('click',()=>{if(viewGenState){viewGenState.look='negative';renderViewGenerator();}});
5249
+ document.getElementById('vgDepthA').addEventListener('input',viewGenInput);document.getElementById('vgDepthB').addEventListener('input',viewGenInput);
5250
+ document.getElementById('vgCreate').addEventListener('click',createGeneratedViews);document.getElementById('vgCancel').addEventListener('click',closeViewGenerator);document.getElementById('vgClose').addEventListener('click',closeViewGenerator);document.getElementById('vgBackdrop').addEventListener('click',closeViewGenerator);
5251
+ document.getElementById('viewGenModal').addEventListener('keydown',e=>{e.stopPropagation();if(e.key==='Escape'){e.preventDefault();closeViewGenerator();return;}if(e.key!=='Tab')return;
5252
+ const focusable=[...document.querySelectorAll('#viewGenModal button:not(:disabled),#viewGenModal input:not(:disabled)')].filter(el=>el.offsetParent!==null);if(!focusable.length)return;const first=focusable[0],last=focusable[focusable.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus();}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus();}});
5153
5253
  // A themed undo toast (extends toast(): an inline "Undo" action + a ~5s window). Baseline tokens only.
5154
5254
  function undoToast(msg,onUndo){let t=document.getElementById('undoToast');
5155
5255
  if(!t){t=document.createElement('div');t.id='undoToast';t.style.cssText='position:fixed;left:50%;bottom:18px;transform:translateX(-50%);display:flex;align-items:center;gap:12px;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:8px;padding:8px 14px;box-shadow:0 6px 20px rgba(0,0,0,.5);z-index:60;font:13px system-ui;opacity:0;transition:opacity .2s';document.body.appendChild(t);}
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Pure helpers for F11 generated 3D views.
3
+ *
4
+ * This module deliberately owns no DOM and no Three.js state. grid-core resolves the authored
5
+ * per-plan grid; this file turns that geometry into world-mm datum sources, finite cut boxes, and
6
+ * sanitised draft-only saved-view records. steel-editor.html owns the modal/persistence and
7
+ * steel-3d-view.js owns the camera/mesh intersection.
8
+ */
9
+ import { parseLen } from './grid-core.js';
10
+
11
+ export const DEFAULT_CUT_MM = 24 * 25.4;
12
+
13
+ const finite = (n) => typeof n === 'number' && Number.isFinite(n);
14
+ const positive = (n) => finite(n) && n > 0;
15
+ const vec3 = (v) => Array.isArray(v) && v.length === 3 && v.every(finite);
16
+
17
+ /** Convert resolved display-space grid geometry to world-mm sources. */
18
+ export function sourcesFromGrid(geo, mmPerDisplayPx, sheet) {
19
+ if (!geo || !positive(mmPerDisplayPx)) return { x: [], y: [], levels: [] };
20
+ const sh = typeof sheet === 'string' ? sheet : '';
21
+ const x = Array.isArray(geo.v) ? geo.v.map((line, index) => ({
22
+ kind: 'grid-x', sheet: sh, index, label: String(line?.label ?? index + 1),
23
+ at: Number(line?.x) * mmPerDisplayPx,
24
+ })).filter((s) => finite(s.at)) : [];
25
+ // Display Y grows down the sheet; the 3D scene is Z-up with +Y up the plan.
26
+ const y = Array.isArray(geo.h) ? geo.h.map((line, index) => ({
27
+ kind: 'grid-y', sheet: sh, index, label: String(line?.label ?? index + 1),
28
+ at: -Number(line?.y) * mmPerDisplayPx,
29
+ })).filter((s) => finite(s.at)) : [];
30
+ const levels = Array.isArray(geo.zs) ? geo.zs.map((level, index) => ({
31
+ kind: 'level', sheet: sh, index, label: String(level?.label ?? ''), at: Number(level?.mm),
32
+ })).filter((s) => finite(s.at)).sort((a, b) => a.at - b.at) : [];
33
+ return { x, y, levels };
34
+ }
35
+
36
+ /** Parse the modal's authored ft-in depth values into positive world mm. */
37
+ export function parseDepths(kind, raw) {
38
+ const keys = kind === 'level' ? ['above', 'below'] : ['ahead', 'behind'];
39
+ const values = {};
40
+ for (const key of keys) {
41
+ const mm = parseLen(String(raw?.[key] ?? '').trim());
42
+ if (!positive(mm)) return { ok: false, error: `${key} must be greater than 0`, values: null };
43
+ values[key] = mm;
44
+ }
45
+ return { ok: true, error: '', values };
46
+ }
47
+
48
+ function saneBounds(bounds) {
49
+ return !!(bounds && vec3(bounds.min) && vec3(bounds.max)
50
+ && bounds.min.every((n, i) => n < bounds.max[i]));
51
+ }
52
+
53
+ /**
54
+ * Resolve one datum + directional depths into an axis-aligned clip box and camera direction.
55
+ * `direction` points FROM the target TO the camera, matching steel-3d-view fitCamera().
56
+ */
57
+ export function cutForSource(source, depths, look, sceneBounds) {
58
+ if (!source || !finite(source.at) || !saneBounds(sceneBounds)) return null;
59
+ const min = sceneBounds.min.slice(), max = sceneBounds.max.slice();
60
+ const diag = Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]);
61
+ const pad = Math.max(1, diag * 1e-6);
62
+ let direction, generated;
63
+ if (source.kind === 'grid-x' || source.kind === 'grid-y') {
64
+ if (!positive(depths?.ahead) || !positive(depths?.behind)) return null;
65
+ const axis = source.kind === 'grid-x' ? 0 : 1;
66
+ const positiveLook = look !== 'negative';
67
+ min[axis] = source.at - (positiveLook ? depths.behind : depths.ahead);
68
+ max[axis] = source.at + (positiveLook ? depths.ahead : depths.behind);
69
+ direction = axis === 0 ? [positiveLook ? -1 : 1, 0, 0] : [0, positiveLook ? -1 : 1, 0];
70
+ generated = {
71
+ v: 1, kind: source.kind, sheet: String(source.sheet || ''), label: String(source.label || ''),
72
+ at: source.at, look: positiveLook ? 'positive' : 'negative',
73
+ ahead: depths.ahead, behind: depths.behind,
74
+ };
75
+ } else if (source.kind === 'level') {
76
+ if (!positive(depths?.above) || !positive(depths?.below)) return null;
77
+ min[2] = source.at - depths.below;
78
+ max[2] = source.at + depths.above;
79
+ direction = [0, 0, 1];
80
+ generated = {
81
+ v: 1, kind: 'level', sheet: String(source.sheet || ''), label: String(source.label || ''),
82
+ at: source.at, look: 'down', above: depths.above, below: depths.below,
83
+ };
84
+ } else return null;
85
+ // Only non-cut axes span the complete model. The pad prevents floating-point fragments exactly on
86
+ // the scene envelope from being discarded by Three.js clipping.
87
+ const cutAxis = source.kind === 'grid-x' ? 0 : source.kind === 'grid-y' ? 1 : 2;
88
+ for (let i = 0; i < 3; i++) if (i !== cutAxis) { min[i] -= pad; max[i] += pad; }
89
+ if (!min.every((n, i) => finite(n) && n < max[i])) return null;
90
+ return { box: { min, max }, direction, generated };
91
+ }
92
+
93
+ export function nameForSource(source) {
94
+ if (!source) return 'View';
95
+ return source.kind === 'level'
96
+ ? `Plan — ${String(source.label || '')}`
97
+ : `Elevation — Grid ${String(source.label || '')}`;
98
+ }
99
+
100
+ export function sanitizeGenerated(value) {
101
+ if (!value || typeof value !== 'object' || value.v !== 1 || !finite(value.at)
102
+ || typeof value.sheet !== 'string' || typeof value.label !== 'string') return null;
103
+ const kind = value.kind;
104
+ const base = {
105
+ v: 1, kind, sheet: value.sheet.slice(0, 120), label: value.label.slice(0, 80), at: value.at,
106
+ };
107
+ if ((kind === 'grid-x' || kind === 'grid-y')
108
+ && (value.look === 'positive' || value.look === 'negative')
109
+ && positive(value.ahead) && positive(value.behind)) {
110
+ return { ...base, look: value.look, ahead: value.ahead, behind: value.behind };
111
+ }
112
+ if (kind === 'level' && value.look === 'down' && positive(value.above) && positive(value.below)) {
113
+ return { ...base, look: 'down', above: value.above, below: value.below };
114
+ }
115
+ return null;
116
+ }
117
+
118
+ /** Normalise the unlimited draft-only saved-view library. */
119
+ export function sanitizeViews(value, makeId = () => `v${Math.random().toString(36).slice(2, 9)}`) {
120
+ if (!Array.isArray(value)) return [];
121
+ const out = [];
122
+ for (const raw of value) {
123
+ if (!raw || typeof raw !== 'object') continue;
124
+ const generated = sanitizeGenerated(raw.generated);
125
+ const view = {
126
+ v: generated ? 2 : 1,
127
+ id: typeof raw.id === 'string' && raw.id ? raw.id : makeId(),
128
+ name: typeof raw.name === 'string' && raw.name.trim() ? raw.name.trim().slice(0, 80) : 'View',
129
+ order: finite(raw.order) ? raw.order : out.length,
130
+ camera: raw.camera && typeof raw.camera === 'object' ? raw.camera : null,
131
+ projection: raw.projection === 'ortho' ? 'ortho' : 'persp',
132
+ mode: ['solid', 'wire', 'xray'].includes(raw.mode) ? raw.mode : 'solid',
133
+ clips: raw.clips && typeof raw.clips === 'object' ? raw.clips : null,
134
+ objects: raw.objects && typeof raw.objects === 'object' ? raw.objects : null,
135
+ };
136
+ if (generated) view.generated = generated;
137
+ out.push(view);
138
+ }
139
+ return out;
140
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floless/app",
3
- "version": "0.100.1",
3
+ "version": "0.101.0",
4
4
  "type": "module",
5
5
  "description": "Thin localhost host for floless.app — serves web/ and shells the aware CLI. No engine, no LLM.",
6
6
  "bin": {