@floless/app 0.100.1 → 0.101.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50770,7 +50770,7 @@ var require_dist6 = __commonJS({
50770
50770
 
50771
50771
  // install-path.mjs
50772
50772
  var import_node_fs = require("node:fs");
50773
- function resolveRealInstallExePure(execPath, localAppData, exists, readdir3, realpath2) {
50773
+ function resolveRealInstallExePure(execPath, localAppData, exists, readdir4, realpath2) {
50774
50774
  if (!execPath) return execPath;
50775
50775
  let resolved = execPath;
50776
50776
  try {
@@ -50789,7 +50789,7 @@ function resolveRealInstallExePure(execPath, localAppData, exists, readdir3, rea
50789
50789
  const packagesDir2 = `${laRoot}\\Packages`;
50790
50790
  let packages;
50791
50791
  try {
50792
- packages = readdir3(packagesDir2);
50792
+ packages = readdir4(packagesDir2);
50793
50793
  } catch {
50794
50794
  return execPath;
50795
50795
  }
@@ -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.1" : 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.1" : 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" });
@@ -54377,6 +54397,7 @@ function readContractForApp(appId, readAppFn = readApp) {
54377
54397
 
54378
54398
  // projects-store.ts
54379
54399
  var import_node_fs20 = require("node:fs");
54400
+ var import_promises = require("node:fs/promises");
54380
54401
  var import_node_path18 = require("node:path");
54381
54402
  var import_node_os13 = require("node:os");
54382
54403
  var import_node_crypto6 = require("node:crypto");
@@ -55331,19 +55352,6 @@ function deflateSync(data, opts) {
55331
55352
  function inflateSync(data, opts) {
55332
55353
  return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
55333
55354
  }
55334
- var fltn = function(d, p, t, o) {
55335
- for (var k in d) {
55336
- var val = d[k], n = p + k, op = o;
55337
- if (Array.isArray(val))
55338
- op = mrg(o, val[1]), val = val[0];
55339
- if (ArrayBuffer.isView(val))
55340
- t[n] = [val, op];
55341
- else {
55342
- t[n += "/"] = [new u8(0), op];
55343
- fltn(val, n, t, o);
55344
- }
55345
- }
55346
- };
55347
55355
  var te = typeof TextEncoder != "undefined" && /* @__PURE__ */ new TextEncoder();
55348
55356
  var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
55349
55357
  var tds = 0;
@@ -55694,49 +55702,6 @@ var Zip = /* @__PURE__ */ (function() {
55694
55702
  };
55695
55703
  return Zip2;
55696
55704
  })();
55697
- function zipSync(data, opts) {
55698
- if (!opts)
55699
- opts = {};
55700
- var r = {};
55701
- var files2 = [];
55702
- fltn(data, "", r, opts);
55703
- var o = 0;
55704
- var tot = 0;
55705
- for (var fn in r) {
55706
- var _a2 = r[fn], file = _a2[0], p = _a2[1];
55707
- var compression = p.level == 0 ? 0 : 8;
55708
- var f = strToU8(fn), s = f.length;
55709
- var com = p.comment, m = com && strToU8(com), ms = m && m.length;
55710
- var exl = exfl(p.extra);
55711
- if (s > 65535)
55712
- err(11);
55713
- var d = compression ? deflateSync(file, p) : file, l = d.length;
55714
- var c = crc();
55715
- c.p(file);
55716
- files2.push(mrg(p, {
55717
- size: file.length,
55718
- crc: c.d(),
55719
- c: d,
55720
- f,
55721
- m,
55722
- u: s != fn.length || m && com.length != ms,
55723
- o,
55724
- compression
55725
- }));
55726
- o += 30 + s + exl + l;
55727
- tot += 76 + 2 * (s + exl) + (ms || 0) + l;
55728
- }
55729
- var out = new u8(tot + 22), oe = o, cdl = tot - o;
55730
- for (var i = 0; i < files2.length; ++i) {
55731
- var f = files2[i];
55732
- wzh(out, f.o, f, f.f, f.u, f.c.length);
55733
- var badd = 30 + f.f.length + exfl(f.extra);
55734
- out.set(f.c, f.o + badd);
55735
- wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
55736
- }
55737
- wzf(out, o, files2.length, cdl, oe);
55738
- return out;
55739
- }
55740
55705
  function unzipSync(data, opts) {
55741
55706
  var files2 = {};
55742
55707
  var e = data.length - 22;
@@ -55852,9 +55817,27 @@ function renameProject(id, name) {
55852
55817
  const meta = readMeta(safeProjectId(id));
55853
55818
  if (!meta) throw new ProjectError(`unknown project: ${id}`);
55854
55819
  if (typeof name !== "string" || !name.trim()) throw new ProjectError("project name required");
55855
- const next = { ...meta, name: name.trim(), updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
55856
- writeMeta(next);
55857
- return next;
55820
+ const nextName = name.trim();
55821
+ if (nextName === meta.name) return meta;
55822
+ let newId = `${slugify(nextName)}-${(0, import_node_crypto6.randomBytes)(3).toString("hex")}`;
55823
+ while ((0, import_node_fs20.existsSync)(projectDir(newId)) || (0, import_node_fs20.existsSync)((0, import_node_path18.join)(ARCHIVE, newId))) newId = `${slugify(nextName)}-${(0, import_node_crypto6.randomBytes)(3).toString("hex")}`;
55824
+ const from = projectDir(id), to = projectDir(newId);
55825
+ try {
55826
+ (0, import_node_fs20.renameSync)(from, to);
55827
+ } catch {
55828
+ throw new ProjectError("couldn\u2019t rename the project folder \u2014 it may be open or in use. Close the project and try again.");
55829
+ }
55830
+ try {
55831
+ const next = { ...meta, id: newId, name: nextName, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
55832
+ writeMeta(next);
55833
+ return next;
55834
+ } catch (e) {
55835
+ try {
55836
+ (0, import_node_fs20.renameSync)(to, from);
55837
+ } catch {
55838
+ }
55839
+ throw e;
55840
+ }
55858
55841
  }
55859
55842
  function markApproved(id) {
55860
55843
  const meta = readMeta(safeProjectId(id));
@@ -55922,21 +55905,50 @@ function exportFilename(name) {
55922
55905
  const clean = name.replace(/[^a-z0-9\-_. ]+/gi, " ").replace(/\s+/g, " ").trim().slice(0, 60);
55923
55906
  return clean || "project";
55924
55907
  }
55925
- function exportProjectZip(id) {
55908
+ var ZIP_SLICE = 1024 * 1024;
55909
+ var yieldToLoop = () => new Promise((r) => setImmediate(r));
55910
+ async function zipYielding(files2, level) {
55911
+ const parts = [];
55912
+ let failed = null;
55913
+ const zipper = new Zip((err2, chunk) => {
55914
+ if (err2) failed = err2;
55915
+ else parts.push(chunk);
55916
+ });
55917
+ for (const [name, bytes] of Object.entries(files2)) {
55918
+ if (failed) break;
55919
+ const file = new ZipDeflate(name, { level });
55920
+ zipper.add(file);
55921
+ if (bytes.length === 0) {
55922
+ file.push(new Uint8Array(0), true);
55923
+ continue;
55924
+ }
55925
+ for (let off = 0; off < bytes.length && !failed; off += ZIP_SLICE) {
55926
+ const end = Math.min(off + ZIP_SLICE, bytes.length);
55927
+ file.push(bytes.subarray(off, end), end >= bytes.length);
55928
+ await yieldToLoop();
55929
+ }
55930
+ }
55931
+ zipper.end();
55932
+ if (failed) throw failed;
55933
+ return Buffer.concat(parts);
55934
+ }
55935
+ async function exportProjectZip(id) {
55926
55936
  const meta = readMeta(safeProjectId(id));
55927
55937
  if (!meta) throw new ProjectError(`unknown project: ${id}`);
55928
55938
  const root = projectDir(id);
55929
55939
  const files2 = {};
55930
- const walk2 = (abs, rel) => {
55931
- for (const e of (0, import_node_fs20.readdirSync)(abs, { withFileTypes: true })) {
55940
+ const walk2 = async (abs, rel) => {
55941
+ const entries = await (0, import_promises.readdir)(abs, { withFileTypes: true });
55942
+ await Promise.all(entries.map(async (e) => {
55932
55943
  const childAbs = (0, import_node_path18.join)(abs, e.name);
55933
55944
  const childRel = rel ? `${rel}/${e.name}` : e.name;
55934
- if (e.isDirectory()) walk2(childAbs, childRel);
55935
- else if (e.isFile()) files2[`${id}/${childRel}`] = (0, import_node_fs20.readFileSync)(childAbs);
55936
- }
55945
+ if (e.isDirectory()) await walk2(childAbs, childRel);
55946
+ else if (e.isFile()) files2[`${id}/${childRel}`] = await (0, import_promises.readFile)(childAbs);
55947
+ }));
55937
55948
  };
55938
- walk2(root, "");
55939
- return { data: zipSync(files2, { level: 6 }), filename: `${exportFilename(meta.name)}.zip` };
55949
+ await walk2(root, "");
55950
+ const data = await zipYielding(files2, 6);
55951
+ return { data, filename: `${exportFilename(meta.name)}.zip` };
55940
55952
  }
55941
55953
  var IMPORT_MAX_FILES = 1e4;
55942
55954
  var IMPORT_MAX_UNCOMPRESSED = 2 * 1024 * 1024 * 1024;
@@ -55968,7 +55980,10 @@ function importProjectZip(data) {
55968
55980
  } catch {
55969
55981
  throw new ProjectError("archive project.json is unreadable");
55970
55982
  }
55971
- const name = typeof srcMeta.name === "string" && srcMeta.name.trim() ? srcMeta.name.trim() : "Imported project";
55983
+ const rawName = typeof srcMeta.name === "string" && srcMeta.name.trim() ? srcMeta.name.trim() : "Imported project";
55984
+ const takenNames = new Set(listProjects().map((p) => p.name));
55985
+ let name = rawName;
55986
+ for (let n = 1; takenNames.has(name); n++) name = n === 1 ? `${rawName} (imported)` : `${rawName} (imported ${n})`;
55972
55987
  const app = typeof srcMeta.app === "string" ? srcMeta.app.trim() : "";
55973
55988
  if (!/^[a-z0-9][a-z0-9._-]*$/i.test(app)) throw new ProjectError(`archive names an invalid app id: ${app || "(empty)"}`);
55974
55989
  let id = `${slugify(name)}-${(0, import_node_crypto6.randomBytes)(3).toString("hex")}`;
@@ -58658,6 +58673,7 @@ function bakeContractIntoApp(sourcePath, contract) {
58658
58673
  delete baked.detail_placements;
58659
58674
  delete baked.prop_labels;
58660
58675
  delete baked.member_styles;
58676
+ delete baked.views;
58661
58677
  if (Array.isArray(contract.plans)) {
58662
58678
  baked.plans = contract.plans.map((p) => {
58663
58679
  if (p && typeof p === "object") {
@@ -61848,7 +61864,7 @@ function generateXlsxFileContents(arg1, arg2, arg3) {
61848
61864
  sheetsOptions = setConditionalFormattingRulesGlobalIndexes(sheetsOptions);
61849
61865
  var features = getFeatures(options.features);
61850
61866
  var files2 = {};
61851
- var readFile = function readFile2(path) {
61867
+ var readFile2 = function readFile3(path) {
61852
61868
  return files2[path];
61853
61869
  };
61854
61870
  var writeFiles = function writeFiles2(filesToWrite) {
@@ -61915,7 +61931,7 @@ function generateXlsxFileContents(arg1, arg2, arg3) {
61915
61931
  sheetIndex++;
61916
61932
  }
61917
61933
  writeFiles(getWrittenFiles(features, sheetsOptions, {
61918
- read: readFile
61934
+ read: readFile2
61919
61935
  }));
61920
61936
  files2["xl/styles.xml"] = generateStylesXml(getCellStyles(), sheetsOptions, features);
61921
61937
  files2["xl/sharedStrings.xml"] = generateSharedStringsXml(getSharedStrings());
@@ -63934,7 +63950,7 @@ var import_node_child_process6 = require("node:child_process");
63934
63950
  var import_node_crypto11 = require("node:crypto");
63935
63951
  var import_node_fs36 = require("node:fs");
63936
63952
  var import_node_stream3 = require("node:stream");
63937
- var import_promises = require("node:stream/promises");
63953
+ var import_promises2 = require("node:stream/promises");
63938
63954
  var import_node_path32 = require("node:path");
63939
63955
 
63940
63956
  // post-update-marker.mjs
@@ -64091,7 +64107,7 @@ async function checkForUpdate() {
64091
64107
  }
64092
64108
  async function sha1OfFile(path) {
64093
64109
  const hash = (0, import_node_crypto11.createHash)("sha1");
64094
- await (0, import_promises.pipeline)((0, import_node_fs36.createReadStream)(path), hash);
64110
+ await (0, import_promises2.pipeline)((0, import_node_fs36.createReadStream)(path), hash);
64095
64111
  return hash.digest("hex").toUpperCase();
64096
64112
  }
64097
64113
  async function downloadPackage(asset) {
@@ -64106,7 +64122,7 @@ async function downloadPackage(asset) {
64106
64122
  signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS)
64107
64123
  });
64108
64124
  if (!res.ok || !res.body) throw new Error(`download failed: HTTP ${res.status} for ${asset.FileName}`);
64109
- await (0, import_promises.pipeline)(import_node_stream3.Readable.fromWeb(res.body), (0, import_node_fs36.createWriteStream)(dest));
64125
+ await (0, import_promises2.pipeline)(import_node_stream3.Readable.fromWeb(res.body), (0, import_node_fs36.createWriteStream)(dest));
64110
64126
  const got = await sha1OfFile(dest);
64111
64127
  if (got !== want) throw new Error(`SHA1 mismatch for ${asset.FileName}: feed=${want} got=${got}`);
64112
64128
  return dest;
@@ -65005,12 +65021,12 @@ var import_node_fs39 = require("node:fs");
65005
65021
 
65006
65022
  // node_modules/chokidar/esm/index.js
65007
65023
  var import_fs2 = require("fs");
65008
- var import_promises4 = require("fs/promises");
65024
+ var import_promises5 = require("fs/promises");
65009
65025
  var import_events = require("events");
65010
65026
  var sysPath2 = __toESM(require("path"), 1);
65011
65027
 
65012
65028
  // node_modules/readdirp/esm/index.js
65013
- var import_promises2 = require("node:fs/promises");
65029
+ var import_promises3 = require("node:fs/promises");
65014
65030
  var import_node_stream4 = require("node:stream");
65015
65031
  var import_node_path35 = require("node:path");
65016
65032
  var EntryTypes = {
@@ -65077,7 +65093,7 @@ var ReaddirpStream = class extends import_node_stream4.Readable {
65077
65093
  const { root, type } = opts;
65078
65094
  this._fileFilter = normalizeFilter(opts.fileFilter);
65079
65095
  this._directoryFilter = normalizeFilter(opts.directoryFilter);
65080
- const statMethod = opts.lstat ? import_promises2.lstat : import_promises2.stat;
65096
+ const statMethod = opts.lstat ? import_promises3.lstat : import_promises3.stat;
65081
65097
  if (wantBigintFsStats) {
65082
65098
  this._stat = (path) => statMethod(path, { bigint: true });
65083
65099
  } else {
@@ -65148,7 +65164,7 @@ var ReaddirpStream = class extends import_node_stream4.Readable {
65148
65164
  async _exploreDir(path, depth) {
65149
65165
  let files2;
65150
65166
  try {
65151
- files2 = await (0, import_promises2.readdir)(path, this._rdOptions);
65167
+ files2 = await (0, import_promises3.readdir)(path, this._rdOptions);
65152
65168
  } catch (error) {
65153
65169
  this._onError(error);
65154
65170
  }
@@ -65186,8 +65202,8 @@ var ReaddirpStream = class extends import_node_stream4.Readable {
65186
65202
  if (stats && stats.isSymbolicLink()) {
65187
65203
  const full = entry2.fullPath;
65188
65204
  try {
65189
- const entryRealPath = await (0, import_promises2.realpath)(full);
65190
- const entryRealPathStats = await (0, import_promises2.lstat)(entryRealPath);
65205
+ const entryRealPath = await (0, import_promises3.realpath)(full);
65206
+ const entryRealPathStats = await (0, import_promises3.lstat)(entryRealPath);
65191
65207
  if (entryRealPathStats.isFile()) {
65192
65208
  return "file";
65193
65209
  }
@@ -65230,7 +65246,7 @@ function readdirp(root, options = {}) {
65230
65246
 
65231
65247
  // node_modules/chokidar/esm/handler.js
65232
65248
  var import_fs = require("fs");
65233
- var import_promises3 = require("fs/promises");
65249
+ var import_promises4 = require("fs/promises");
65234
65250
  var sysPath = __toESM(require("path"), 1);
65235
65251
  var import_os = require("os");
65236
65252
  var STR_DATA = "data";
@@ -65257,7 +65273,7 @@ var EVENTS = {
65257
65273
  };
65258
65274
  var EV = EVENTS;
65259
65275
  var THROTTLE_MODE_WATCH = "watch";
65260
- var statMethods = { lstat: import_promises3.lstat, stat: import_promises3.stat };
65276
+ var statMethods = { lstat: import_promises4.lstat, stat: import_promises4.stat };
65261
65277
  var KEY_LISTENERS = "listeners";
65262
65278
  var KEY_ERR = "errHandlers";
65263
65279
  var KEY_RAW = "rawEmitters";
@@ -65614,7 +65630,7 @@ var setFsWatchListener = (path, fullPath, options, handlers) => {
65614
65630
  cont.watcherUnusable = true;
65615
65631
  if (isWindows && error.code === "EPERM") {
65616
65632
  try {
65617
- const fd2 = await (0, import_promises3.open)(path, "r");
65633
+ const fd2 = await (0, import_promises4.open)(path, "r");
65618
65634
  await fd2.close();
65619
65635
  broadcastErr(error);
65620
65636
  } catch (err2) {
@@ -65743,7 +65759,7 @@ var NodeFsHandler = class {
65743
65759
  return;
65744
65760
  if (!newStats || newStats.mtimeMs === 0) {
65745
65761
  try {
65746
- const newStats2 = await (0, import_promises3.stat)(file);
65762
+ const newStats2 = await (0, import_promises4.stat)(file);
65747
65763
  if (this.fsw.closed)
65748
65764
  return;
65749
65765
  const at = newStats2.atimeMs;
@@ -65798,7 +65814,7 @@ var NodeFsHandler = class {
65798
65814
  this.fsw._incrReadyCount();
65799
65815
  let linkPath;
65800
65816
  try {
65801
- linkPath = await (0, import_promises3.realpath)(path);
65817
+ linkPath = await (0, import_promises4.realpath)(path);
65802
65818
  } catch (e) {
65803
65819
  this.fsw._emitReady();
65804
65820
  return true;
@@ -65946,7 +65962,7 @@ var NodeFsHandler = class {
65946
65962
  let closer;
65947
65963
  if (stats.isDirectory()) {
65948
65964
  const absPath = sysPath.resolve(path);
65949
- const targetPath = follow ? await (0, import_promises3.realpath)(path) : path;
65965
+ const targetPath = follow ? await (0, import_promises4.realpath)(path) : path;
65950
65966
  if (this.fsw.closed)
65951
65967
  return;
65952
65968
  closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
@@ -65956,7 +65972,7 @@ var NodeFsHandler = class {
65956
65972
  this.fsw._symlinkPaths.set(absPath, targetPath);
65957
65973
  }
65958
65974
  } else if (stats.isSymbolicLink()) {
65959
- const targetPath = follow ? await (0, import_promises3.realpath)(path) : path;
65975
+ const targetPath = follow ? await (0, import_promises4.realpath)(path) : path;
65960
65976
  if (this.fsw.closed)
65961
65977
  return;
65962
65978
  const parent = sysPath.dirname(wh.watchPath);
@@ -66117,7 +66133,7 @@ var DirEntry = class {
66117
66133
  return;
66118
66134
  const dir = this.path;
66119
66135
  try {
66120
- await (0, import_promises4.readdir)(dir);
66136
+ await (0, import_promises5.readdir)(dir);
66121
66137
  } catch (err2) {
66122
66138
  if (this._removeWatcher) {
66123
66139
  this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir));
@@ -66442,7 +66458,7 @@ var FSWatcher = class extends import_events.EventEmitter {
66442
66458
  const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path) : path;
66443
66459
  let stats2;
66444
66460
  try {
66445
- stats2 = await (0, import_promises4.stat)(fullPath);
66461
+ stats2 = await (0, import_promises5.stat)(fullPath);
66446
66462
  } catch (err2) {
66447
66463
  }
66448
66464
  if (!stats2 || this.closed)
@@ -67341,7 +67357,7 @@ async function startServer() {
67341
67357
  });
67342
67358
  app.get("/api/projects/:id/export.zip", async (req, reply) => {
67343
67359
  try {
67344
- const { data, filename } = exportProjectZip(req.params.id);
67360
+ const { data, filename } = await exportProjectZip(req.params.id);
67345
67361
  return reply.header("content-type", "application/zip").header("content-disposition", `attachment; filename="${filename.replace(/["\r\n]/g, "")}"`).send(Buffer.from(data));
67346
67362
  } catch (e) {
67347
67363
  if (e instanceof ProjectError) return reply.status(404).send({ ok: false, error: e.message });
@@ -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
+ }
@@ -2496,9 +2496,9 @@
2496
2496
  el.addEventListener('animationend', () => el.classList.remove('is-new'), { once: true });
2497
2497
  }
2498
2498
 
2499
- // Shared rename/duplicate/archive — used by both the kebab menu (one project, from the
2500
- // landing grid) and the header project-picker's inline row actions below (any project,
2501
- // from anywhere). Never switches projects itself — the caller decides navigation.
2499
+ // rename/duplicate/archive on ONE project — driven by the landing-grid card ⋯ menu (the header
2500
+ // project-picker is now a pure switcher with no inline actions). Never switches projects itself
2501
+ // except where a rename of the OPEN project must re-src its iframes — the caller decides navigation.
2502
2502
  // Each branch updates the local `projects` array from the endpoint's result (unshift a duplicate,
2503
2503
  // move a rename to the front, filter out an archive — the unshift mirrors createSeeded/
2504
2504
  // createFromDrawing) and repaints the grid IMMEDIATELY, so the change is on screen WITH the toast
@@ -2515,16 +2515,20 @@
2515
2515
  if (action === 'rename') {
2516
2516
  const name = await promptName('Rename project', 'New name', proj ? proj.name : '');
2517
2517
  if (!name) return;
2518
+ const wasCurrent = !!(current && current.id === id);
2518
2519
  const { project } = await api(`/api/projects/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ name }) });
2519
- if (current && current.id === id) { current = project; $projName.textContent = project.name; $crumbName.textContent = project.name; }
2520
- // Rename bumps updatedAt server-side and the grid is newest-activity-first, so the reconcile
2521
- // will move this card to the front regardless. Do that move now (not an in-place swap) so it
2522
- // happens once, with the flash, rather than as a jump a second later when loadProjects() lands.
2520
+ // Rename now also changes the on-disk id (the folder tracks the display name), so update the grid
2521
+ // BY THE OLD id and re-front the card — once, with the flash, rather than as a jump a second later
2522
+ // when loadProjects() reconciles. The unshift must land before any openProject(newId) below so it
2523
+ // can find the project in `projects`.
2523
2524
  const i = projects.findIndex((p) => p.id === id);
2524
2525
  if (i >= 0) projects.splice(i, 1);
2525
2526
  projects.unshift(project);
2526
2527
  renderLanding();
2527
2528
  flashCard(project.id, { scroll: true });
2529
+ // If the renamed project was the OPEN one, its editor iframes still carry ?project=<old id> —
2530
+ // re-open so they re-src to the new id (a stale id 404s the next contract read/write/autosave).
2531
+ if (wasCurrent) await openProject(project.id);
2528
2532
  showToast(`Renamed to "${project.name}"`, 'ok');
2529
2533
  } else if (action === 'duplicate') {
2530
2534
  const { project } = await api(`/api/projects/${encodeURIComponent(id)}/duplicate`, { method: 'POST', body: '{}' });
@@ -2649,13 +2653,15 @@
2649
2653
  const pid = escapeAttr(p.id);
2650
2654
  const displayApp = appDisplayName(p.app);
2651
2655
  const meta = `${escapeHtml(displayApp)} · ${escapeHtml(relAgo(p.updatedAt))}`;
2652
- return `<div class="wf-option" role="option" id="ws-proj-opt-${pid}" data-id="${pid}" data-search="${escapeAttr((p.name + ' ' + displayApp + ' ' + p.app).toLowerCase())}" tabindex="-1" aria-selected="${current && current.id === p.id ? 'true' : 'false'}">`
2653
- + `<span class="wf-option-name">${escapeHtml(p.name)}</span><span class="wf-option-meta">${meta}</span>`
2654
- + `<span class="wf-option-actions">`
2655
- + `<button type="button" class="wf-act act-edit" data-act="rename" data-id="${pid}" tabindex="-1" data-tip="Rename" aria-label="Rename ${escapeAttr(p.name)}">✎</button>`
2656
- + `<button type="button" class="wf-act act-dup" data-act="duplicate" data-id="${pid}" tabindex="-1" data-tip="Duplicate" aria-label="Duplicate ${escapeAttr(p.name)}">⧉</button>`
2657
- + `<button type="button" class="wf-act act-archive" data-act="archive" data-id="${pid}" tabindex="-1" data-tip="Archive — recoverable" aria-label="Archive ${escapeAttr(p.name)}">⏏</button>`
2658
- + `</span></div>`;
2656
+ // A PURE SWITCHER: no per-row Rename/Duplicate/Archive icons — project MANAGEMENT lives only on
2657
+ // the landing cards' ⋯ menu (a picker that only lets you switch has one predictable affordance
2658
+ // per row; a lone kept icon would have no rule a user could guess). Clicking a row switches.
2659
+ // The current project carries `.selected` (not just aria-selected) so the accent "you are here"
2660
+ // marker (.wf-option.selected in app.css) actually shows — mirrors the workflow picker (aware.js).
2661
+ // It matters more now the action icons are gone: without it the open row is visually unmarked.
2662
+ const here = current && current.id === p.id;
2663
+ return `<div class="wf-option${here ? ' selected' : ''}" role="option" id="ws-proj-opt-${pid}" data-id="${pid}" data-search="${escapeAttr((p.name + ' ' + displayApp + ' ' + p.app).toLowerCase())}" tabindex="-1" aria-selected="${here ? 'true' : 'false'}">`
2664
+ + `<span class="wf-option-name">${escapeHtml(p.name)}</span><span class="wf-option-meta">${meta}</span></div>`;
2659
2665
  }).join('');
2660
2666
  html += `<div class="wf-empty-search" hidden>No projects match '<span class="wf-empty-term"></span>'</div>`;
2661
2667
  $projList.innerHTML = html;
@@ -2737,8 +2743,8 @@
2737
2743
  }
2738
2744
  if ($projList) {
2739
2745
  $projList.addEventListener('click', (e) => {
2740
- const act = e.target.closest('[data-act]');
2741
- if (act) { closeProjCombo(false); doProjectAction(act.dataset.act, act.dataset.id); return; }
2746
+ // Pure switcher: a row click switches projects. Management (rename/duplicate/archive) is on the
2747
+ // landing cards only, so there are no inline action icons to hit-test around here anymore.
2742
2748
  const o = e.target.closest('.wf-option');
2743
2749
  if (o) selectProjById(o.dataset.id);
2744
2750
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floless/app",
3
- "version": "0.100.1",
3
+ "version": "0.101.1",
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": {