@floless/app 0.138.2 → 0.139.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.
Files changed (109) hide show
  1. package/autostart.mjs +6 -2
  2. package/desktop-access-production-manifest.mjs +7 -0
  3. package/dist/floless-server.cjs +157202 -70901
  4. package/dist/schemas/model.continuation.v1.schema.json +19 -0
  5. package/dist/schemas/model.continuation.v2.schema.json +19 -0
  6. package/dist/schemas/model.query-response.v1.schema.json +95 -0
  7. package/dist/schemas/model.query-response.v2.schema.json +80 -0
  8. package/dist/schemas/model.query.v1.schema.json +87 -0
  9. package/dist/schemas/model.query.v2.schema.json +87 -0
  10. package/dist/schemas/model.snap-candidate.v1.schema.json +48 -0
  11. package/dist/schemas/model.snap-constraint.v1.schema.json +18 -0
  12. package/dist/schemas/model.snap-query.v1.schema.json +24 -0
  13. package/dist/schemas/model.snap-result.v1.schema.json +33 -0
  14. package/dist/schemas/model.snapshot.v1.schema.json +136 -0
  15. package/dist/schemas/revit.model.v1.schema.json +24 -0
  16. package/dist/schemas/steel.model.v2.schema.json +45 -6
  17. package/dist/skills/floless-app-approval/SKILL.md +19 -5
  18. package/dist/skills/floless-app-bridge/SKILL.md +19 -6
  19. package/dist/skills/floless-app-knowledge/SKILL.md +22 -1
  20. package/dist/skills/floless-app-new-workflow/SKILL.md +31 -27
  21. package/dist/skills/floless-app-new-workflow/references/build-and-verify.md +13 -12
  22. package/dist/skills/floless-app-onboarding/SKILL.md +3 -3
  23. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +16 -9
  24. package/dist/skills/floless-app-steel-model/SKILL.md +11 -2
  25. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +95 -0
  26. package/dist/skills/floless-app-steel-takeoff/SKILL.md +142 -21
  27. package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +19 -0
  28. package/dist/skills/floless-app-tweak-contract/SKILL.md +42 -8
  29. package/dist/skills/floless-app-vectorize/SKILL.md +19 -6
  30. package/dist/skills/floless-app-workflows/SKILL.md +30 -3
  31. package/dist/skills/floless-app-workflows/references/workspace-data.md +77 -4
  32. package/dist/templates/floless-workspace-model-report.flo +77 -0
  33. package/dist/templates/revit-model.flo +111 -0
  34. package/dist/web/app.css +415 -177
  35. package/dist/web/app.js +302 -51
  36. package/dist/web/aware.js +1357 -1032
  37. package/dist/web/chat.css +692 -0
  38. package/dist/web/chat.js +2651 -0
  39. package/dist/web/commands-revit.js +42 -0
  40. package/dist/web/commands-shell.js +531 -70
  41. package/dist/web/commands-steel.js +344 -146
  42. package/dist/web/commands.js +1 -1
  43. package/dist/web/index.html +283 -77
  44. package/dist/web/instructor.js +217 -36
  45. package/dist/web/left-pane.js +636 -0
  46. package/dist/web/model-artifact-loader.js +75 -0
  47. package/dist/web/model-authoring-gestures.js +141 -0
  48. package/dist/web/model-cad-tools.js +20 -0
  49. package/dist/web/model-clip-gesture.js +148 -0
  50. package/dist/web/model-clip-list.js +156 -0
  51. package/dist/web/model-clip-session.js +274 -0
  52. package/dist/web/model-clip-three-overlay.js +295 -0
  53. package/dist/web/model-clip-three-preview.js +59 -0
  54. package/dist/web/model-editor-contract.js +519 -0
  55. package/dist/web/model-editor-revit-adapter.js +139 -0
  56. package/dist/web/model-editor-shell.js +271 -0
  57. package/dist/web/model-editor-state-recovery.js +44 -0
  58. package/dist/web/model-editor-steel-adapter.js +410 -0
  59. package/dist/web/model-editor.css +268 -0
  60. package/dist/web/model-frame.js +192 -0
  61. package/dist/web/model-inspector.js +128 -0
  62. package/dist/web/model-measure.js +390 -0
  63. package/dist/web/model-navigation-controls.js +246 -0
  64. package/dist/web/model-orientation-overlay.js +217 -0
  65. package/dist/web/model-panel-bridge.js +230 -0
  66. package/dist/web/model-pointer-dock.js +164 -0
  67. package/dist/web/model-revit-module.js +83 -0
  68. package/dist/web/model-selection-coordinator.js +151 -0
  69. package/dist/web/model-selection-tools.js +290 -0
  70. package/dist/web/model-snap-contract.js +267 -0
  71. package/dist/web/model-snapping.js +497 -0
  72. package/dist/web/model-spatial-panel.js +294 -0
  73. package/dist/web/model-spatial-tools.js +249 -0
  74. package/dist/web/model-tree.js +47 -0
  75. package/dist/web/model-viewport-lighting.js +166 -0
  76. package/dist/web/model-viewport-revit-adapter.js +1224 -0
  77. package/dist/web/model-viewport-state.js +505 -0
  78. package/dist/web/model-viewport-steel-adapter.js +150 -0
  79. package/dist/web/model-viewport-toolbar.js +516 -0
  80. package/dist/web/model-viewport.js +717 -0
  81. package/dist/web/panels.js +8 -15
  82. package/dist/web/renderers.js +3 -0
  83. package/dist/web/revit-editor.css +35 -0
  84. package/dist/web/revit-editor.html +74 -0
  85. package/dist/web/revit-editor.js +845 -0
  86. package/dist/web/steel-3d-core.js +16 -44
  87. package/dist/web/steel-3d-view.js +1384 -633
  88. package/dist/web/steel-canvas-guidance.js +3 -1
  89. package/dist/web/steel-editor.html +2121 -1253
  90. package/dist/web/steel-filter.html +5 -1
  91. package/dist/web/steel-model-v2-commands.js +72 -1
  92. package/dist/web/steel-split-view.js +5 -39
  93. package/dist/web/steel-view-generation.js +107 -17
  94. package/dist/web/vector-3d.html +12 -0
  95. package/dist/web/workspaces.js +2154 -283
  96. package/distribution-profile-active.mjs +2 -0
  97. package/distribution-profile-production.mjs +47 -0
  98. package/distribution-profile-shared.mjs +8 -0
  99. package/distribution-profile.mjs +18 -0
  100. package/distribution-resource-inventory.mjs +81 -0
  101. package/launch.mjs +18 -10
  102. package/log.mjs +2 -1
  103. package/managed-runtime-policy.mjs +104 -0
  104. package/model-reader-policy-active.mjs +7 -0
  105. package/network-policy-active.mjs +6 -0
  106. package/package.json +17 -2
  107. package/post-update-marker.mjs +3 -1
  108. package/rvt-production-uat-authority.mjs +60 -0
  109. package/teardown.mjs +4 -3
@@ -0,0 +1,75 @@
1
+ // Match the authenticated snapshot boundary enforced by the server. Snowdon's measured property
2
+ // shard is 48,248,289 bytes / 180,004 rows, so these bounded limits leave well over 2× headroom.
3
+ export const MODEL_VIEWER_MAX_JSON_BYTES = 128 * 1024 * 1024;
4
+ export const MODEL_VIEWER_MAX_ROWS = 5_000_000;
5
+ export const MODEL_EXPLORER_ENTITY_CAP = 300;
6
+ export const MODEL_EXPLORER_GROUP_CAP = 200;
7
+
8
+ const hex = (bytes) => [...bytes].map((value) => value.toString(16).padStart(2, '0')).join('');
9
+ const SHA256 = /^[0-9a-f]{64}$/;
10
+
11
+ async function readBoundedBytes(response, receipt, hardLimit) {
12
+ const declared = Number(response.headers?.get?.('content-length'));
13
+ if (Number.isFinite(declared) && (declared > receipt.bytes || declared > hardLimit)) throw new Error('The model artifact response exceeds its signed byte limit.');
14
+ if (!response.body?.getReader) {
15
+ const bytes = new Uint8Array(await response.arrayBuffer());
16
+ if (bytes.byteLength > receipt.bytes || bytes.byteLength > hardLimit) throw new Error('The model artifact response exceeds its signed byte limit.');
17
+ return bytes;
18
+ }
19
+ const reader = response.body.getReader(); const chunks = []; let total = 0;
20
+ try {
21
+ while (true) {
22
+ const { done, value } = await reader.read(); if (done) break;
23
+ total += value.byteLength;
24
+ if (total > receipt.bytes || total > hardLimit) { await reader.cancel(); throw new Error('The model artifact response exceeds its signed byte limit.'); }
25
+ chunks.push(value);
26
+ }
27
+ } finally { reader.releaseLock?.(); }
28
+ const bytes = new Uint8Array(total); let offset = 0;
29
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
30
+ return bytes;
31
+ }
32
+
33
+ /** Fetch and authenticate one signed JSON shard before parsing/materializing its rows. */
34
+ export function preflightModelJsonReceipt(receipt) {
35
+ if (!receipt || !Number.isSafeInteger(receipt.bytes) || receipt.bytes < 0 || !SHA256.test(receipt.digest)
36
+ || !Number.isSafeInteger(receipt.items) || receipt.items < 0) throw new Error('The model shard has no complete signed receipt.');
37
+ if (receipt.bytes > MODEL_VIEWER_MAX_JSON_BYTES) throw new Error('This model shard exceeds the 128 MiB viewer safety limit.');
38
+ if (Number.isSafeInteger(receipt.items) && receipt.items > MODEL_VIEWER_MAX_ROWS) throw new Error('This model shard exceeds the 5,000,000-row viewer safety limit.');
39
+ return receipt;
40
+ }
41
+
42
+ export async function readModelJsonArtifact({ url, receipt, rowKey, expectedItems = null, fetchImpl = fetch, cryptoImpl = crypto, signal = undefined }) {
43
+ preflightModelJsonReceipt(receipt);
44
+ const response = await fetchImpl(url, { credentials: 'same-origin', signal });
45
+ if (!response.ok) throw new Error(`Model shard request failed (${response.status}).`);
46
+ const bytes = await readBoundedBytes(response, receipt, MODEL_VIEWER_MAX_JSON_BYTES);
47
+ if (bytes.byteLength !== receipt.bytes) throw new Error('The model shard byte length does not match its signed receipt.');
48
+ const digest = hex(new Uint8Array(await cryptoImpl.subtle.digest('SHA-256', bytes)));
49
+ if (digest !== receipt.digest) throw new Error('The model shard digest does not match its signed receipt.');
50
+ let document;
51
+ try { document = JSON.parse(new TextDecoder().decode(bytes)); } catch { throw new Error('The authenticated model shard is not valid JSON.'); }
52
+ const rows = document?.[rowKey]; if (!Array.isArray(rows)) throw new Error(`The authenticated model shard has no ${rowKey} rows.`);
53
+ if (rows.length > MODEL_VIEWER_MAX_ROWS) throw new Error('This model shard exceeds the 5,000,000-row viewer safety limit.');
54
+ const signedItems = Number.isSafeInteger(receipt.items) ? receipt.items : expectedItems;
55
+ if (Number.isSafeInteger(signedItems) && rows.length !== signedItems) throw new Error('The model shard row count does not match its signed receipt.');
56
+ return { document, rows, bytes: bytes.byteLength };
57
+ }
58
+
59
+ /** Fetch and authenticate one signed binary model artifact without exceeding its bounded receipt. */
60
+ export async function readModelBinaryArtifact({ url, receipt, maxBytes, fetchImpl = fetch, cryptoImpl = crypto, signal = undefined }) {
61
+ if (!receipt || !Number.isSafeInteger(receipt.bytes) || receipt.bytes < 0 || receipt.bytes > maxBytes || !SHA256.test(receipt.digest)) throw new Error('The model artifact has no safe signed byte receipt.');
62
+ const response = await fetchImpl(url, { credentials: 'same-origin', signal });
63
+ if (!response.ok) throw new Error(`Model artifact request failed (${response.status}).`);
64
+ const bytes = await readBoundedBytes(response, receipt, maxBytes);
65
+ if (bytes.byteLength !== receipt.bytes) throw new Error('The model artifact byte length does not match its signed receipt.');
66
+ const digest = hex(new Uint8Array(await cryptoImpl.subtle.digest('SHA-256', bytes)));
67
+ if (digest !== receipt.digest) throw new Error('The model artifact digest does not match its signed receipt.');
68
+ return bytes.buffer;
69
+ }
70
+
71
+ export function assertModelViewerRowBudget(...rowSets) {
72
+ const count = rowSets.reduce((total, rows) => total + (Array.isArray(rows) ? rows.length : 0), 0);
73
+ if (count > MODEL_VIEWER_MAX_ROWS) throw new Error('This model contains more than 5,000,000 browser-visible rows. Narrow it before opening the viewer.');
74
+ return count;
75
+ }
@@ -0,0 +1,141 @@
1
+ /*
2
+ * Shared authoring GESTURES, never shared domain mutations.
3
+ *
4
+ * Providers declare the operations they can truthfully transact and receive immutable intents after
5
+ * common snapped-point, drag, preview, numeric-entry and Escape behavior completes. Structural rules,
6
+ * validation, clash checks, undo journals and commits stay provider-owned.
7
+ */
8
+
9
+ export const MODEL_AUTHORING_GESTURE_SCHEMA = 'floless.model-authoring-gesture/v1';
10
+ const BUILTIN_OPERATION_DEFINITIONS = Object.freeze({
11
+ add: Object.freeze({ id: 'add', label: 'Add', mode: 'points', pointCount: 2 }),
12
+ move: Object.freeze({ id: 'move', label: 'Move', mode: 'points', pointCount: 2 }),
13
+ copy: Object.freeze({ id: 'copy', label: 'Copy', mode: 'points', pointCount: 2 }),
14
+ array: Object.freeze({ id: 'array', label: 'Copy array', mode: 'points', pointCount: 2 }),
15
+ 'move-to-level': Object.freeze({ id: 'move-to-level', label: 'Move or copy to level', mode: 'numeric', pointCount: 0 }),
16
+ stretch: Object.freeze({ id: 'stretch', label: 'Stretch', mode: 'points', pointCount: 2 }),
17
+ transform: Object.freeze({ id: 'transform', label: 'Transform', mode: 'numeric', pointCount: 0 }),
18
+ delete: Object.freeze({ id: 'delete', label: 'Delete', mode: 'immediate', pointCount: 0 }),
19
+ });
20
+
21
+ const freeze = (value) => {
22
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
23
+ for (const child of Object.values(value)) freeze(child);
24
+ return Object.freeze(value);
25
+ };
26
+ const cloneFreeze = (value) => freeze(globalThis.structuredClone ? globalThis.structuredClone(value) : JSON.parse(JSON.stringify(value)));
27
+ const finite3 = (value) => Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);
28
+
29
+ function acquired(value) {
30
+ if (value?.schema !== 'floless.model-snap-result/v1' || value?.status !== 'acquired' || !finite3(value.pointMm)) {
31
+ throw Object.assign(new Error('Authoring points require a real acquired snap result.'), { code: 'E_MODEL_AUTHORING_SNAP_REQUIRED' });
32
+ }
33
+ return cloneFreeze({ pointMm: value.pointMm, providerRef: value.providerRef, kind: value.kind, candidateId: value.candidateId, generation: value.generation });
34
+ }
35
+
36
+ function exactNumber(text, label) {
37
+ const value = typeof text === 'number' ? text : Number(String(text ?? '').trim());
38
+ if (!Number.isFinite(value)) throw Object.assign(new TypeError(`${label} must be a finite number.`), { code: 'E_MODEL_AUTHORING_NUMBER' });
39
+ return value;
40
+ }
41
+
42
+ export function parseModelTransformEntry(value) {
43
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Transform entry must be an object.');
44
+ const allowed = new Set(['xMm', 'yMm', 'zMm', 'angleDeg', 'copies', 'levelMm']);
45
+ for (const key of Object.keys(value)) if (!allowed.has(key)) throw new TypeError(`Unknown transform field ${key}.`);
46
+ const out = {};
47
+ for (const key of ['xMm', 'yMm', 'zMm', 'angleDeg', 'levelMm']) if (value[key] !== undefined && value[key] !== '') out[key] = exactNumber(value[key], key);
48
+ if (value.copies !== undefined && value.copies !== '') {
49
+ const copies = exactNumber(value.copies, 'copies');
50
+ if (!Number.isInteger(copies) || copies < 1 || copies > 1000) throw Object.assign(new TypeError('copies must be an integer from 1 to 1000.'), { code: 'E_MODEL_AUTHORING_NUMBER' });
51
+ out.copies = copies;
52
+ }
53
+ if (!Object.keys(out).length) throw Object.assign(new TypeError('Enter at least one transform value.'), { code: 'E_MODEL_AUTHORING_NUMBER' });
54
+ return cloneFreeze(out);
55
+ }
56
+
57
+ /**
58
+ * @param {{ capabilities:Record<string,boolean>, pointCounts?:Record<string,number>,
59
+ * providerOperations?:Array<{id:string,label:string,mode:string,pointCount:number}>,
60
+ * onIntent:(intent:any)=>unknown, onPreview?:(preview:any)=>void, onState?:(state:any)=>void }} options
61
+ */
62
+ export function createModelAuthoringGestures({ capabilities = {}, pointCounts = {}, providerOperations = [], onIntent, onPreview = () => {}, onState = () => {} }) {
63
+ if (typeof onIntent !== 'function') throw new TypeError('Authoring gestures need an onIntent transaction port.');
64
+ if (!Array.isArray(providerOperations) || providerOperations.length > 64) throw new TypeError('providerOperations must contain at most 64 operation descriptors.');
65
+ const definitions = new Map(Object.entries(BUILTIN_OPERATION_DEFINITIONS));
66
+ for (const descriptor of providerOperations) {
67
+ const keys = Object.keys(descriptor ?? {}); const allowed = ['id', 'label', 'mode', 'pointCount'];
68
+ if (keys.some((key) => !allowed.includes(key)) || !/^provider:[a-z0-9][a-z0-9._-]*$/.test(descriptor?.id ?? '')
69
+ || typeof descriptor?.label !== 'string' || !descriptor.label.trim() || !['points', 'numeric', 'immediate'].includes(descriptor?.mode)
70
+ || !Number.isInteger(descriptor?.pointCount) || descriptor.pointCount < 0 || descriptor.pointCount > 8
71
+ || (descriptor.mode === 'points') !== (descriptor.pointCount > 0)) {
72
+ throw Object.assign(new TypeError('Provider operations need a provider:* id, label, mode, and a compatible pointCount from 0 to 8.'), { code: 'E_MODEL_AUTHORING_PROVIDER_OPERATION' });
73
+ }
74
+ if (definitions.has(descriptor.id)) throw Object.assign(new TypeError(`Duplicate authoring operation ${descriptor.id}.`), { code: 'E_MODEL_AUTHORING_PROVIDER_OPERATION' });
75
+ definitions.set(descriptor.id, cloneFreeze({ ...descriptor, label: descriptor.label.trim() }));
76
+ }
77
+ const supported = new Set([...definitions.keys()].filter((kind) => capabilities[kind] === true));
78
+ let active = null; let sequence = 0; let disposed = false;
79
+ const countFor = (kind) => Number.isInteger(pointCounts[kind]) ? pointCounts[kind] : definitions.get(kind)?.pointCount ?? 0;
80
+ const publicState = () => cloneFreeze({ schema: MODEL_AUTHORING_GESTURE_SCHEMA, active: active ? { kind: active.kind, stage: active.stage, points: active.points, numeric: active.numeric, dragging: !!active.drag } : null, supported: [...supported] });
81
+ const publish = () => { const state = publicState(); try { onState(state); } catch (_) {} return state; };
82
+ const live = () => { if (disposed) throw Object.assign(new Error('Authoring gesture coordinator is disposed.'), { code: 'E_MODEL_AUTHORING_DISPOSED' }); };
83
+ const cancelActive = (reason) => { if (!active) return false; const previous = active; active = null; try { onPreview(cloneFreeze({ kind: 'clear', operation: previous.kind, reason })); } catch (_) {} publish(); return true; };
84
+ const issue = (payload) => {
85
+ const intent = cloneFreeze({ schema: MODEL_AUTHORING_GESTURE_SCHEMA, id: `model-authoring.${++sequence}`, ...payload });
86
+ const result = onIntent(intent);
87
+ return { intent, result };
88
+ };
89
+ const ensureOperation = (kind) => {
90
+ if (!definitions.has(kind)) throw Object.assign(new Error(`Unknown authoring operation ${kind}.`), { code: 'E_MODEL_AUTHORING_UNKNOWN' });
91
+ if (!supported.has(kind)) throw Object.assign(new Error(`${kind} is not supported by this provider.`), { code: 'E_MODEL_AUTHORING_UNSUPPORTED' });
92
+ };
93
+
94
+ return Object.freeze({
95
+ state() { live(); return publicState(); },
96
+ supports(kind) { return supported.has(kind); },
97
+ operations() { live(); return [...definitions.values()].filter((item) => supported.has(item.id)).map(cloneFreeze); },
98
+ arm(kind, context = {}) {
99
+ live(); ensureOperation(kind); cancelActive('replaced');
100
+ const definition = definitions.get(kind);
101
+ if (definition.mode === 'immediate') return issue({ operation: kind, context });
102
+ active = { kind, context: cloneFreeze(context), stage: definition.mode === 'points' ? 'point-1' : 'numeric', points: [], numeric: null, drag: null, generation: null };
103
+ publish(); return publicState();
104
+ },
105
+ acquire(result) {
106
+ live(); if (!active) throw Object.assign(new Error('No authoring operation is armed.'), { code: 'E_MODEL_AUTHORING_INACTIVE' });
107
+ const point = acquired(result);
108
+ if (active.generation && JSON.stringify(active.generation) !== JSON.stringify(point.generation)) throw Object.assign(new Error('The acquired point belongs to another model generation.'), { code: 'E_MODEL_AUTHORING_STALE' });
109
+ active.generation ??= point.generation; active.points.push(point);
110
+ const required = countFor(active.kind);
111
+ if (active.points.length < required) { active.stage = `point-${active.points.length + 1}`; try { onPreview(cloneFreeze({ kind: 'points', operation: active.kind, points: active.points })); } catch (_) {} publish(); return { complete: false, state: publicState() }; }
112
+ const operation = active; active = null; try { onPreview(cloneFreeze({ kind: 'clear', operation: operation.kind, reason: 'commit' })); } catch (_) {}
113
+ const committed = issue({ operation: operation.kind, context: operation.context, points: operation.points, numeric: operation.numeric, generation: operation.generation }); publish(); return { complete: true, ...committed };
114
+ },
115
+ setNumeric(value) { live(); if (!active) throw Object.assign(new Error('No authoring operation is armed.'), { code: 'E_MODEL_AUTHORING_INACTIVE' }); active.numeric = parseModelTransformEntry(value); try { onPreview(cloneFreeze({ kind: 'numeric', operation: active.kind, value: active.numeric, points: active.points })); } catch (_) {} return publish(); },
116
+ commitNumeric() { live(); if (!active?.numeric) throw Object.assign(new Error('No numeric transform is ready.'), { code: 'E_MODEL_AUTHORING_NUMBER' }); const operation = active; active = null; const committed = issue({ operation: operation.kind, context: operation.context, points: operation.points, numeric: operation.numeric, generation: operation.generation }); publish(); return committed; },
117
+ beginDrag({ pointerId, origin, selection, copy = false }) {
118
+ live(); const kind = copy ? 'copy' : 'move'; ensureOperation(kind); cancelActive('replaced');
119
+ if (!Number.isInteger(pointerId) || !finite3(origin) || !Array.isArray(selection) || selection.some((key) => typeof key !== 'string')) throw new TypeError('Drag needs pointerId, origin and selection keys.');
120
+ active = { kind, context: cloneFreeze({ selection }), stage: 'drag', points: [], numeric: null, generation: null, drag: { pointerId, origin: [...origin], current: [...origin] } }; publish(); return publicState();
121
+ },
122
+ updateDrag({ pointerId, point }) { live(); if (!active?.drag || active.drag.pointerId !== pointerId) return false; active.drag.current = vec(point); try { onPreview(cloneFreeze({ kind: 'drag', operation: active.kind, from: active.drag.origin, to: active.drag.current, context: active.context })); } catch (_) {} publish(); return true; },
123
+ endDrag({ pointerId, snapResult = null }) { live(); if (!active?.drag || active.drag.pointerId !== pointerId) return null; const operation = active; const target = snapResult ? acquired(snapResult).pointMm : operation.drag.current; active = null; try { onPreview(cloneFreeze({ kind: 'clear', operation: operation.kind, reason: 'commit' })); } catch (_) {} const committed = issue({ operation: operation.kind, context: operation.context, drag: { from: operation.drag.origin, to: target } }); publish(); return committed; },
124
+ cancelDrag(pointerId) { live(); if (!active?.drag || active.drag.pointerId !== pointerId) return false; return cancelActive('pointer-cancel'); },
125
+ escape() {
126
+ live(); if (!active) return 'pass';
127
+ if (active.numeric) { active.numeric = null; active.stage = active.points.length ? `point-${active.points.length + 1}` : (countFor(active.kind) ? 'point-1' : 'numeric'); publish(); return 'numeric'; }
128
+ if (active.points.length) { active.points.pop(); active.stage = `point-${active.points.length + 1}`; try { onPreview(cloneFreeze({ kind: 'points', operation: active.kind, points: active.points })); } catch (_) {} publish(); return 'point'; }
129
+ cancelActive('escape'); return 'tool';
130
+ },
131
+ cancel() { live(); return cancelActive('cancel'); },
132
+ undo() { live(); if (!capabilities.undo) throw Object.assign(new Error('Undo is not supported by this provider.'), { code: 'E_MODEL_AUTHORING_UNSUPPORTED' }); return issue({ operation: 'undo' }); },
133
+ redo() { live(); if (!capabilities.redo) throw Object.assign(new Error('Redo is not supported by this provider.'), { code: 'E_MODEL_AUTHORING_UNSUPPORTED' }); return issue({ operation: 'redo' }); },
134
+ dispose() { if (disposed) return; cancelActive('dispose'); disposed = true; },
135
+ });
136
+ }
137
+
138
+ function vec(value) {
139
+ if (!finite3(value)) throw new TypeError('Drag point must be a finite 3D point.');
140
+ return [...value];
141
+ }
@@ -0,0 +1,20 @@
1
+ // Shared lifecycle/command seam for model measurement and snapping. A provider may draw with SVG
2
+ // (Revit) or richer Three geometry (Steel), but arming, clearing, snap commands and state flow through
3
+ // this one controller instead of each module exposing an unrelated tool API.
4
+ export function createModelCadToolController({ provider }) {
5
+ const required = ['measureState', 'setMeasureArmed', 'setSnapMode', 'snapState'];
6
+ const missing = required.filter((name) => typeof provider?.[name] !== 'function');
7
+ if (missing.length) throw new Error(`CAD tool provider is missing ${missing.join(', ')}.`);
8
+ let disposed = false;
9
+ const live = () => { if (disposed) throw new Error('CAD tool controller is disposed.'); };
10
+ return Object.freeze({
11
+ measureState() { live(); return provider.measureState(); },
12
+ toggleMeasure() { live(); const next = !provider.measureState().armed; provider.setMeasureArmed(next); return provider.measureState(); },
13
+ setMeasureArmed(value) { live(); provider.setMeasureArmed(value === true); return provider.measureState(); },
14
+ setMeasureAxisLock(kind) { live(); provider.setMeasureAxisLock?.(kind); return provider.measureState(); },
15
+ clearMeasures() { live(); if (typeof provider.clearMeasures !== 'function') return false; provider.clearMeasures(); return provider.measureState(); },
16
+ setSnapMode(kind, value) { live(); provider.setSnapMode(kind, value); return provider.snapState(); },
17
+ snapState() { live(); return provider.snapState(); },
18
+ dispose() { if (disposed) return; disposed = true; provider.dispose?.(); },
19
+ });
20
+ }
@@ -0,0 +1,148 @@
1
+ /* Provider-neutral clipping gesture lifecycle shared by every 3D model viewport. */
2
+
3
+ export const MODEL_CLIP_GESTURE_SCHEMA = 'floless.model-clip-gesture/v1';
4
+ export const MODEL_CLIP_MIN_EXTENT_MM = 1;
5
+
6
+ const finite3 = (value) => Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);
7
+ const clone = (value) => globalThis.structuredClone ? globalThis.structuredClone(value) : JSON.parse(JSON.stringify(value));
8
+ const frozen = (value) => Object.freeze(clone(value));
9
+
10
+ /** Orient a surface normal along the camera ray, keeping the far side of the picked face. */
11
+ export function orientClipNormalAwayFromCamera(normal, rayDirection) {
12
+ if (!finite3(normal) || !finite3(rayDirection)) throw new TypeError('Clip orientation needs finite normal and ray vectors.');
13
+ const magnitude = Math.hypot(...normal); const rayMagnitude = Math.hypot(...rayDirection);
14
+ if (!(magnitude > 0) || !(rayMagnitude > 0)) throw new TypeError('Clip orientation vectors must be non-zero.');
15
+ const next = normal.map((value) => value / magnitude);
16
+ const direction = rayDirection.map((value) => value / rayMagnitude);
17
+ if (next.reduce((sum, value, axis) => sum + value * direction[axis], 0) < 0) return next.map((value) => -value);
18
+ return next;
19
+ }
20
+
21
+ function boxFrom(a, b, floorZ, topZ) {
22
+ return frozen({
23
+ min: [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.min(floorZ, topZ)],
24
+ max: [Math.max(a[0], b[0]), Math.max(a[1], b[1]), Math.max(floorZ, topZ)],
25
+ });
26
+ }
27
+
28
+ /**
29
+ * Own the exact plane-pick and corner/corner/height interaction. Geometry resolution and drawing
30
+ * stay provider callbacks, so Steel and Revit cannot drift in step, cancel, or commit behavior.
31
+ * @param {{
32
+ * visibleBounds: () => ({min:number[],max:number[]}|null),
33
+ * resolvePlane: (at:{clientX:number,clientY:number}) => ({point:number[],normal:number[]}|null),
34
+ * resolveFloor: (at:{clientX:number,clientY:number}, floorZ:number) => ({point:number[],snap?:any}|null),
35
+ * resolveHeight: (at:{clientX:number,clientY:number}, draft:{a:number[],b:number[],floorZ:number}) => ({z:number,point?:number[]|null,snap?:any}|null),
36
+ * preview?: (value:any) => void,
37
+ * commitPlane: (value:{point:number[],normal:number[]}) => void,
38
+ * commitBox: (value:{min:number[],max:number[]}) => void,
39
+ * onState?: (value:any) => void,
40
+ * onCursor?: (value:string) => void,
41
+ * minimumExtentMm?: number,
42
+ * }} options
43
+ */
44
+ export function createModelClipGesture({
45
+ visibleBounds, resolvePlane, resolveFloor, resolveHeight, preview = (_value) => {}, commitPlane, commitBox,
46
+ onState = (_value) => {}, onCursor = (_value) => {}, minimumExtentMm = MODEL_CLIP_MIN_EXTENT_MM,
47
+ } = {}) {
48
+ if (typeof visibleBounds !== 'function' || typeof resolvePlane !== 'function' || typeof resolveFloor !== 'function'
49
+ || typeof resolveHeight !== 'function' || typeof commitPlane !== 'function' || typeof commitBox !== 'function') {
50
+ throw new TypeError('Model clipping needs bounds, pick, preview, and commit provider callbacks.');
51
+ }
52
+ let active = null; let disposed = false; let lastPlane = null;
53
+ const ensureLive = () => { if (disposed) throw Object.assign(new Error('Model clip gesture is disposed.'), { code: 'E_MODEL_CLIP_DISPOSED' }); };
54
+ const state = () => frozen({ schema: MODEL_CLIP_GESTURE_SCHEMA, active: active ? {
55
+ mode: active.mode, step: active.mode === 'plane' ? 0 : active.b ? 2 : active.a ? 1 : 0,
56
+ floorZ: active.floorZ, draft: active.a ? { a: active.a, b: active.b } : null,
57
+ } : null });
58
+ const publish = () => { const next = state(); try { onState(next); } catch (_) {} return next; };
59
+ const clearPreview = (reason) => { lastPlane = null; try { preview(frozen({ kind: 'clear', reason })); } catch (_) {} };
60
+ const disarm = (reason) => {
61
+ if (!active) return false;
62
+ active = null; clearPreview(reason); try { onCursor('default'); } catch (_) {} publish(); return true;
63
+ };
64
+ const pointer = (event) => ({ clientX: Number(event?.clientX), clientY: Number(event?.clientY) });
65
+
66
+ const api = {
67
+ state() { ensureLive(); return state(); },
68
+ arm(mode) {
69
+ ensureLive(); if (!['plane', 'box'].includes(mode)) throw new TypeError('Clip mode must be plane or box.');
70
+ disarm('replaced');
71
+ const bounds = visibleBounds();
72
+ if (!bounds || !finite3(bounds.min) || !finite3(bounds.max)) throw new Error('No visible model bounds are available.');
73
+ active = { mode, floorZ: mode === 'box' ? bounds.min[2] : null, a: null, b: null };
74
+ try { onCursor('crosshair'); } catch (_) {} publish(); return state();
75
+ },
76
+ cancel(reason = 'cancel') { ensureLive(); return disarm(reason); },
77
+ pointerMove(event) {
78
+ ensureLive(); if (!active) return false;
79
+ const at = pointer(event);
80
+ if (active.mode === 'plane') {
81
+ const resolved = resolvePlane(at); lastPlane = resolved && finite3(resolved.point) && finite3(resolved.normal) ? frozen({ at, point: resolved.point, normal: resolved.normal }) : null;
82
+ preview(lastPlane ? frozen({ kind: 'plane', point: lastPlane.point, normal: lastPlane.normal }) : frozen({ kind: 'clear', reason: 'miss' }));
83
+ return true;
84
+ }
85
+ if (!active.b) {
86
+ const resolved = resolveFloor(at, active.floorZ);
87
+ if (!resolved || !finite3(resolved.point)) { preview(frozen({ kind: 'clear', reason: 'miss' })); return true; }
88
+ if (!active.a) { preview(frozen({ kind: 'point', point: resolved.point, snap: resolved.snap ?? null })); return true; }
89
+ preview(frozen({ kind: 'box', box: boxFrom(active.a, resolved.point, active.floorZ, active.floorZ), point: resolved.point, snap: resolved.snap ?? null })); return true;
90
+ }
91
+ const resolved = resolveHeight(at, frozen({ a: active.a, b: active.b, floorZ: active.floorZ }));
92
+ if (!resolved || !Number.isFinite(resolved.z)) { preview(frozen({ kind: 'clear', reason: 'miss' })); return true; }
93
+ preview(frozen({ kind: 'box', box: boxFrom(active.a, active.b, active.floorZ, resolved.z), point: resolved.point ?? null, snap: resolved.snap ?? null })); return true;
94
+ },
95
+ click(event) {
96
+ ensureLive(); if (!active) return false;
97
+ const at = pointer(event);
98
+ if (active.mode === 'plane') {
99
+ const same = lastPlane && lastPlane.at.clientX === at.clientX && lastPlane.at.clientY === at.clientY;
100
+ const resolved = same ? lastPlane : resolvePlane(at);
101
+ if (!resolved || !finite3(resolved.point) || !finite3(resolved.normal)) { lastPlane = null; clearPreview('miss'); return true; }
102
+ commitPlane(frozen({ point: resolved.point, normal: resolved.normal })); disarm('commit'); return true;
103
+ }
104
+ if (!active.a) {
105
+ const resolved = resolveFloor(at, active.floorZ); if (!resolved || !finite3(resolved.point)) { clearPreview('miss'); return true; }
106
+ active.a = [...resolved.point]; publish(); return true;
107
+ }
108
+ if (!active.b) {
109
+ const resolved = resolveFloor(at, active.floorZ); if (!resolved || !finite3(resolved.point)) { clearPreview('miss'); return true; }
110
+ if (Math.abs(resolved.point[0] - active.a[0]) < minimumExtentMm && Math.abs(resolved.point[1] - active.a[1]) < minimumExtentMm) return true;
111
+ active.b = [...resolved.point]; publish(); return true;
112
+ }
113
+ const resolved = resolveHeight(at, frozen({ a: active.a, b: active.b, floorZ: active.floorZ }));
114
+ if (!resolved || !Number.isFinite(resolved.z)) { clearPreview('miss'); return true; }
115
+ const top = Math.abs(resolved.z - active.floorZ) < minimumExtentMm ? active.floorZ + minimumExtentMm : resolved.z;
116
+ commitBox(boxFrom(active.a, active.b, active.floorZ, top)); disarm('commit'); return true;
117
+ },
118
+ escape() {
119
+ ensureLive(); if (!active) return 'pass';
120
+ if (active.mode === 'box' && active.b) { active.b = null; clearPreview('step-back'); publish(); return 'height'; }
121
+ if (active.mode === 'box' && active.a) { active.a = null; clearPreview('step-back'); publish(); return 'footprint'; }
122
+ disarm('escape'); return 'tool';
123
+ },
124
+ inputPlugin() {
125
+ return Object.freeze({
126
+ pointerDown(event) { return !!active && event.button === 0; },
127
+ pointerMove(event) {
128
+ if (!active) return false;
129
+ const buttons = Number(event?.buttons) || 0;
130
+ // Placement owns the left button only. A right/middle drag is CAD navigation even while
131
+ // the tool is armed, and must reach OrbitControls without a preventDefault on its move.
132
+ if (buttons & 6) return false;
133
+ api.pointerMove(event);
134
+ // Hover updates the preview but is observational; only a held left button is consumed.
135
+ return (buttons & 1) !== 0;
136
+ },
137
+ pointerLeave() { if (!active) return false; clearPreview('leave'); return true; },
138
+ pointerCancel() { return disarm('pointer-cancel'); },
139
+ click(event) { return api.click(event); },
140
+ keyDown(event) { if (!active || event.key !== 'Escape') return false; api.escape(); return true; },
141
+ windowBlur() { return disarm('blur'); },
142
+ cancel() { return disarm('exclusive-tool'); },
143
+ });
144
+ },
145
+ dispose() { if (disposed) return; disarm('dispose'); disposed = true; },
146
+ };
147
+ return Object.freeze(api);
148
+ }
@@ -0,0 +1,156 @@
1
+ /*
2
+ * Shared clip list for every model viewer. It renders a model-clip-session and contains no provider
3
+ * knowledge; providers render and manipulate the corresponding geometry through their own adapters.
4
+ */
5
+
6
+ // Builds a clip-list button. It deliberately sets NO class: `action` is the behavioural hook
7
+ // (`data-action`, read by the delegated click and dblclick handlers) and is not a style name.
8
+ // Deriving `model-clip-${action}` doubled the prefix on every one of them, since each action id
9
+ // already starts with `clip-` — `clip-remove` became `model-clip-clip-remove`, matching no rule — and
10
+ // even the de-doubled `model-${action}` would match for only the two actions whose ids happen to
11
+ // equal their class names; the enable, enable-all and select controls are styled under different
12
+ // names entirely. Each caller states its own class instead, so the styling hook is visible where it
13
+ // is used. `server/model-clip-list.test.ts` pins every one of them — that is the record, not this
14
+ // comment. See #1453.
15
+ function button(documentRef, { label, action, tip, ariaLabel = null, pressed = null, text = label }) {
16
+ const value = documentRef.createElement('button'); value.type = 'button';
17
+ value.dataset.action = action; value.dataset.tip = tip; value.textContent = text;
18
+ if (ariaLabel) value.setAttribute('aria-label', ariaLabel);
19
+ if (pressed !== null) value.setAttribute('aria-pressed', String(pressed));
20
+ return value;
21
+ }
22
+
23
+ /** @param {{session:any, host:HTMLElement, documentRef?:Document, onError?:(message:string)=>void}} options */
24
+ export function mountModelClipList({ session, host, documentRef = document, onError = () => {} } = {}) {
25
+ if (!session?.state || !session?.subscribe || !session?.select || !session?.rename) throw new TypeError('Clip list requires a model clip session.');
26
+ if (!host?.replaceChildren || !host?.addEventListener) throw new TypeError('Clip list requires a host element.');
27
+ let editingId = null, editingValue = '', destroyed = false;
28
+
29
+ const report = (message) => { try { onError(message); } catch (_) { /* reporting cannot break the list */ } };
30
+ const selectedSingle = () => session.selected().length === 1 ? session.selected()[0] : null;
31
+ const rowFor = (id) => [...host.querySelectorAll('[data-clip-id]')].find((row) => row.dataset.clipId === id) ?? null;
32
+
33
+ function startRename(id) {
34
+ const clip = session.clips().find((item) => item.id === id); if (!clip) return false;
35
+ editingId = id; editingValue = clip.label; paint();
36
+ const input = rowFor(id)?.querySelector('[data-clip-rename]');
37
+ input?.focus?.(); input?.select?.(); return true;
38
+ }
39
+
40
+ function finishRename(input, save) {
41
+ if (!input || editingId === null) return;
42
+ const id = editingId;
43
+ if (save && !session.rename(id, input.value)) {
44
+ input.setAttribute('aria-invalid', 'true');
45
+ const message = 'Use a unique, non-empty clip name.'; input.dataset.tip = message; report(message);
46
+ queueMicrotask(() => { input.focus?.(); input.select?.(); }); return;
47
+ }
48
+ editingId = null; editingValue = ''; paint();
49
+ }
50
+
51
+ function clipRow(clip) {
52
+ const row = documentRef.createElement('div'); row.className = 'model-clip-row'; row.dataset.clipId = clip.id;
53
+ row.setAttribute('role', 'option'); row.setAttribute('aria-selected', String(session.isSelected(clip.id)));
54
+ if (session.isSelected(clip.id)) row.classList.add('is-selected');
55
+
56
+ const enabled = button(documentRef, {
57
+ label: clip.enabled === false ? 'Enable clip' : 'Disable clip', action: 'clip-enabled',
58
+ tip: clip.enabled === false ? `Enable ${clip.label}` : `Disable ${clip.label}`,
59
+ ariaLabel: clip.enabled === false ? `Enable ${clip.label}` : `Disable ${clip.label}`,
60
+ pressed: clip.enabled !== false, text: clip.enabled === false ? '' : '✓',
61
+ });
62
+ enabled.classList.add('model-clip-enable');
63
+
64
+ let label;
65
+ if (editingId === clip.id) {
66
+ label = documentRef.createElement('input'); label.type = 'text'; label.value = editingValue;
67
+ label.className = 'model-clip-rename'; label.dataset.clipRename = ''; label.setAttribute('aria-label', `Rename ${clip.label}`);
68
+ } else {
69
+ label = button(documentRef, { label: clip.label, action: 'clip-select', tip: `Select ${clip.label}` });
70
+ label.classList.add('model-clip-label');
71
+ }
72
+ const remove = button(documentRef, { label: 'Remove', action: 'clip-remove', tip: `Remove ${clip.label}`, ariaLabel: `Remove ${clip.label}`, text: '×' });
73
+ remove.classList.add('model-clip-remove');
74
+ row.append(enabled, label, remove); return row;
75
+ }
76
+
77
+ function paint(state = session.state()) {
78
+ if (destroyed) return;
79
+ const header = documentRef.createElement('div'); header.className = 'model-clip-list-header';
80
+ const heading = documentRef.createElement('strong'); heading.textContent = 'Clips';
81
+ const count = documentRef.createElement('span'); count.className = 'model-clip-count'; count.dataset.clipCount = ''; count.textContent = String(state.clips.length);
82
+ header.append(heading, count);
83
+ if (state.clips.length) {
84
+ const enabledState = session.enabledState();
85
+ const enableAll = button(documentRef, {
86
+ label: enabledState === 'on' ? 'Disable all clips' : 'Enable all clips', action: 'clip-enabled-all',
87
+ tip: enabledState === 'on' ? 'Disable all clips' : 'Enable all clips',
88
+ ariaLabel: 'All clips enabled', text: '',
89
+ });
90
+ const enabledGlyph = documentRef.createElement('span'); enabledGlyph.setAttribute('aria-hidden', 'true');
91
+ enabledGlyph.textContent = enabledState === 'on' ? '■' : enabledState === 'off' ? '□' : '◪';
92
+ enableAll.append(enabledGlyph);
93
+ enableAll.classList.add('model-clip-enable-all'); enableAll.setAttribute('role', 'checkbox');
94
+ enableAll.setAttribute('aria-checked', enabledState === 'mixed' ? 'mixed' : String(enabledState === 'on'));
95
+ enableAll.dataset.state = enabledState; header.append(enableAll);
96
+ const clear = button(documentRef, { label: 'Clear all', action: 'clip-clear', tip: 'Remove all clips' });
97
+ clear.classList.add('model-clip-clear'); header.append(clear);
98
+ }
99
+ const rows = documentRef.createElement('div'); rows.className = 'model-clip-list-rows'; rows.setAttribute('role', 'listbox'); rows.setAttribute('aria-multiselectable', 'true');
100
+ if (!state.clips.length) {
101
+ const empty = documentRef.createElement('div'); empty.className = 'model-clip-list-empty'; empty.textContent = 'No clips yet. Add a clip plane or box from the toolbar.'; rows.append(empty);
102
+ } else for (const clip of state.clips) rows.append(clipRow(clip));
103
+ host.replaceChildren(header, rows);
104
+ }
105
+
106
+ function click(event) {
107
+ const control = event.target.closest?.('[data-action]'); if (!control || !host.contains(control)) return;
108
+ const row = control.closest('[data-clip-id]'); const id = row?.dataset.clipId;
109
+ if (control.dataset.action === 'clip-select') session.select(id, event);
110
+ else if (control.dataset.action === 'clip-enabled') session.toggle(id);
111
+ else if (control.dataset.action === 'clip-enabled-all') session.toggleAllEnabled();
112
+ else if (control.dataset.action === 'clip-remove') session.remove(id);
113
+ else if (control.dataset.action === 'clip-clear') session.clear();
114
+ }
115
+ function doubleClick(event) {
116
+ const label = event.target.closest?.('[data-action="clip-select"]'); const row = label?.closest('[data-clip-id]');
117
+ if (row) {
118
+ event.preventDefault?.();
119
+ session.setSelected([row.dataset.clipId], { anchorId: row.dataset.clipId });
120
+ startRename(row.dataset.clipId);
121
+ }
122
+ }
123
+ function keydown(event) {
124
+ const input = event.target.closest?.('[data-clip-rename]');
125
+ if (input) {
126
+ if (event.key === 'Enter') { event.preventDefault(); event.stopPropagation(); finishRename(input, true); }
127
+ else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); finishRename(input, false); }
128
+ return;
129
+ }
130
+ if (event.key === 'F2') {
131
+ const id = selectedSingle(); if (!id) return;
132
+ event.preventDefault(); event.stopPropagation(); startRename(id);
133
+ }
134
+ }
135
+ function focusOut(event) {
136
+ const input = event.target.closest?.('[data-clip-rename]');
137
+ if (input) finishRename(input, true);
138
+ }
139
+ function input(event) {
140
+ const control = event.target.closest?.('[data-clip-rename]');
141
+ if (control) editingValue = control.value;
142
+ }
143
+
144
+ host.classList.add('model-clip-list');
145
+ host.addEventListener('click', click); host.addEventListener('dblclick', doubleClick); host.addEventListener('keydown', keydown); host.addEventListener('focusout', focusOut); host.addEventListener('input', input);
146
+ const unsubscribe = session.subscribe((state) => paint(state));
147
+
148
+ return Object.freeze({
149
+ paint, startRename,
150
+ destroy() {
151
+ if (destroyed) return; destroyed = true; unsubscribe();
152
+ host.removeEventListener('click', click); host.removeEventListener('dblclick', doubleClick); host.removeEventListener('keydown', keydown); host.removeEventListener('focusout', focusOut); host.removeEventListener('input', input);
153
+ host.classList.remove('model-clip-list'); host.replaceChildren();
154
+ },
155
+ });
156
+ }