@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,294 @@
1
+ /*
2
+ * Provider-neutral spatial controls for model editors.
3
+ *
4
+ * The panel is deliberately a view over createModelSpatialTools: it owns no spatial state and never
5
+ * reaches into a provider. Optional ports are rendered only when the provider can actually perform
6
+ * the authenticated object/face operation.
7
+ */
8
+
9
+ let panelSequence = 0;
10
+ const finite = (value, label) => {
11
+ const next = Number(value);
12
+ if (!Number.isFinite(next)) throw new TypeError(`${label} must be a finite number.`);
13
+ return next;
14
+ };
15
+ const degrees = (radians) => radians * 180 / Math.PI;
16
+ const radians = (value) => value * Math.PI / 180;
17
+ const rounded = (value) => String(Math.abs(value) < 1e-10 ? 0 : Number(value.toFixed(6)));
18
+
19
+ function axesFromEulerDegrees(rx, ry, rz) {
20
+ const x = radians(rx), y = radians(ry), z = radians(rz);
21
+ const sx = Math.sin(x), cx = Math.cos(x), sy = Math.sin(y), cy = Math.cos(y), sz = Math.sin(z), cz = Math.cos(z);
22
+ return {
23
+ xAxis: [cy * cz, cy * sz, -sy],
24
+ yAxis: [sx * sy * cz - cx * sz, sx * sy * sz + cx * cz, sx * cy],
25
+ };
26
+ }
27
+
28
+ function eulerDegreesFromFrame(frame) {
29
+ const ry = Math.asin(Math.max(-1, Math.min(1, -frame.xAxis[2])));
30
+ const cy = Math.cos(ry);
31
+ const rx = Math.abs(cy) > 1e-8 ? Math.atan2(frame.yAxis[2], frame.zAxis[2]) : 0;
32
+ const rz = Math.abs(cy) > 1e-8 ? Math.atan2(frame.xAxis[1], frame.xAxis[0]) : Math.atan2(-frame.yAxis[0], frame.yAxis[1]);
33
+ return [degrees(rx), degrees(ry), degrees(rz)];
34
+ }
35
+
36
+ function button(doc, label, { action, tip, pressed = null, disabled = false } = {}) {
37
+ const control = doc.createElement('button'); control.type = 'button'; control.textContent = label;
38
+ if (action) control.dataset.action = action;
39
+ if (tip) control.dataset.tip = tip;
40
+ if (pressed !== null) control.setAttribute('aria-pressed', String(pressed));
41
+ control.disabled = disabled;
42
+ return control;
43
+ }
44
+
45
+ function numberField(doc, label, value, name, step = '1') {
46
+ const field = doc.createElement('label'); field.className = 'model-spatial-number-field';
47
+ const caption = doc.createElement('span'); caption.textContent = label;
48
+ const input = doc.createElement('input'); input.type = 'number'; input.step = step; input.value = rounded(value); input.dataset.field = name;
49
+ input.setAttribute('aria-label', label); field.append(caption, input); return field;
50
+ }
51
+
52
+ function vectorFields(doc, host, prefix, values, names = ['X', 'Y', 'Z']) {
53
+ values.forEach((value, index) => host.append(numberField(doc, names[index], value, `${prefix}-${index}`)));
54
+ }
55
+
56
+ function valuesFrom(host, prefix, label) {
57
+ return [0, 1, 2].map((index) => finite(host.querySelector(`[data-field="${prefix}-${index}"]`)?.value, `${label} ${'XYZ'[index]}`));
58
+ }
59
+
60
+ function section(doc, title) {
61
+ const fieldset = doc.createElement('fieldset'); fieldset.className = 'model-spatial-section';
62
+ const legend = doc.createElement('legend'); legend.textContent = title; fieldset.append(legend); return fieldset;
63
+ }
64
+
65
+ function note(doc, text) { const value = doc.createElement('div'); value.className = 'model-dialog-note'; value.textContent = text; return value; }
66
+
67
+ function actionRow(doc) { const row = doc.createElement('div'); row.className = 'model-spatial-panel-actions'; return row; }
68
+
69
+ /**
70
+ * @param {{tools:any, trigger:HTMLElement, ports?:Record<string,Function>, documentRef?:Document,
71
+ * windowRef?:Window, onBeforeOpen?:()=>void, onError?:(error:Error)=>void}} options
72
+ */
73
+ export function mountModelSpatialPanel({
74
+ tools, trigger, ports = {}, documentRef = document, windowRef = window, onError = () => {},
75
+ onBeforeOpen = () => {},
76
+ }) {
77
+ if (!tools?.state || !tools?.subscribe || !tools?.activeFrame) throw new TypeError('Spatial panel requires createModelSpatialTools APIs.');
78
+ if (!trigger?.addEventListener) throw new TypeError('Spatial panel requires a trigger element.');
79
+ const panelId = `modelSpatialPanel-${++panelSequence}`;
80
+ let dialog = null, body = null, status = null, destroyed = false;
81
+
82
+ trigger.setAttribute('aria-haspopup', 'dialog'); trigger.setAttribute('aria-controls', panelId); trigger.setAttribute('aria-expanded', 'false');
83
+
84
+ const report = (error) => {
85
+ const value = error instanceof Error ? error : new Error(String(error));
86
+ if (status) { status.textContent = value.message; status.dataset.tone = 'error'; }
87
+ try { onError(value); } catch (_) { /* reporting cannot break the spatial interaction */ }
88
+ };
89
+ const run = (operation, success = '') => {
90
+ try {
91
+ const value = operation();
92
+ if (value?.then) value.then(() => { if (status && success) { status.textContent = success; delete status.dataset.tone; } }).catch(report);
93
+ else if (status && success) { status.textContent = success; delete status.dataset.tone; }
94
+ } catch (error) { report(error); }
95
+ };
96
+
97
+ function renderFrame(root, state) {
98
+ const frameSection = section(documentRef, 'Coordinate frame');
99
+ const summary = documentRef.createElement('div'); summary.className = 'model-spatial-panel-summary';
100
+ const active = tools.activeFrame(); const label = documentRef.createElement('strong'); label.textContent = active.label;
101
+ const origin = documentRef.createElement('span'); origin.textContent = `Origin ${active.origin.map((value) => rounded(value)).join(', ')} mm`;
102
+ summary.append(label, origin); frameSection.append(summary);
103
+
104
+ const frameActions = actionRow(documentRef);
105
+ const global = button(documentRef, 'Use Global', { action: 'frame-global', tip: 'Reset coordinates and dimensions to the global frame', pressed: state.activeFrameId === 'global' });
106
+ global.addEventListener('click', () => run(() => tools.resetGlobal(), 'Global frame active.'));
107
+ frameActions.append(global);
108
+ if (typeof ports.setLocalFromThreePoints === 'function') {
109
+ const points = button(documentRef, 'From 3 points', { action: 'frame-three-points', tip: 'Set local origin, X direction, and Y side from three snapped points' });
110
+ points.addEventListener('click', () => run(() => ports.setLocalFromThreePoints(tools), 'Local frame active.')); frameActions.append(points);
111
+ }
112
+ if (typeof ports.setLocalFromFace === 'function') {
113
+ const face = button(documentRef, 'From selected face', { action: 'frame-face', tip: 'Use authenticated axes from the selected face' });
114
+ face.addEventListener('click', () => run(() => ports.setLocalFromFace(tools), 'Local face frame active.')); frameActions.append(face);
115
+ }
116
+ if (typeof ports.setLocalFromObject === 'function') {
117
+ const object = button(documentRef, 'From selected object', { action: 'frame-object', tip: 'Use authenticated axes from the selected object' });
118
+ object.addEventListener('click', () => run(() => ports.setLocalFromObject(tools), 'Object frame active.')); frameActions.append(object);
119
+ }
120
+ frameSection.append(frameActions);
121
+
122
+ const local = state.frames.find((item) => item.id === 'local') || state.frames.find((item) => item.id === 'global');
123
+ const rotation = eulerDegreesFromFrame(local);
124
+ const localGrid = documentRef.createElement('div'); localGrid.className = 'model-spatial-panel-grid';
125
+ const originLabel = documentRef.createElement('div'); originLabel.className = 'model-spatial-panel-grid-label'; originLabel.textContent = 'Local origin · mm';
126
+ localGrid.append(originLabel); vectorFields(documentRef, localGrid, 'local-origin', local.origin);
127
+ const rotationLabel = documentRef.createElement('div'); rotationLabel.className = 'model-spatial-panel-grid-label'; rotationLabel.textContent = 'Rotation · degrees';
128
+ localGrid.append(rotationLabel); vectorFields(documentRef, localGrid, 'local-rotation', rotation, ['X°', 'Y°', 'Z°']);
129
+ frameSection.append(localGrid);
130
+ const localActions = actionRow(documentRef);
131
+ const apply = button(documentRef, 'Apply local frame', { action: 'frame-local-apply', tip: 'Create or update the local frame from these numeric values' });
132
+ apply.addEventListener('click', () => run(() => {
133
+ const nextOrigin = valuesFrom(frameSection, 'local-origin', 'Local origin');
134
+ const nextRotation = valuesFrom(frameSection, 'local-rotation', 'Local rotation');
135
+ tools.setLocalTransform({ origin: nextOrigin, ...axesFromEulerDegrees(...nextRotation) });
136
+ }, 'Local frame active.'));
137
+ localActions.append(apply); frameSection.append(localActions); root.append(frameSection);
138
+
139
+ if (typeof ports.acceptCoordinates === 'function') {
140
+ const coordinateSection = section(documentRef, 'Typed coordinates');
141
+ const coordinateRow = documentRef.createElement('div'); coordinateRow.className = 'model-spatial-coordinate-row';
142
+ const input = documentRef.createElement('input'); input.type = 'text'; input.dataset.field = 'typed-coordinates'; input.placeholder = 'X, Y, Z or @dX, dY, dZ'; input.setAttribute('aria-label', 'Absolute or relative coordinates in the active frame');
143
+ const accept = button(documentRef, 'Accept point', { action: 'coordinate-accept', tip: 'Accept absolute coordinates, or prefix with @ for a relative offset' });
144
+ accept.addEventListener('click', () => run(() => {
145
+ const basePoint = typeof ports.coordinateBasePoint === 'function' ? ports.coordinateBasePoint() : undefined;
146
+ const point = tools.parseCoordinates(input.value, basePoint);
147
+ return ports.acceptCoordinates(point, { relative: input.value.trim().startsWith('@'), frame: tools.activeFrame() });
148
+ }, 'Coordinate accepted.'));
149
+ input.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); accept.click(); } });
150
+ coordinateRow.append(input, accept); coordinateSection.append(coordinateRow); root.append(coordinateSection);
151
+ }
152
+ }
153
+
154
+ function renderWorkPlane(root, state) {
155
+ const planeSection = section(documentRef, 'Working plane');
156
+ const controls = documentRef.createElement('div'); controls.className = 'model-spatial-panel-inline';
157
+ const offset = numberField(documentRef, 'Offset · mm', state.workPlane?.offsetMm ?? 0, 'plane-offset'); controls.append(offset);
158
+ for (const plane of ['xy', 'xz', 'yz']) {
159
+ const control = button(documentRef, plane.toUpperCase(), { action: `plane-${plane}`, tip: `Set the principal ${plane.toUpperCase()} working plane`, pressed: state.workPlane?.principal === plane });
160
+ control.addEventListener('click', () => run(() => tools.setPrincipalWorkPlane({ plane, offsetMm: finite(offset.querySelector('input').value, 'Working-plane offset') }), `${plane.toUpperCase()} working plane active.`));
161
+ controls.append(control);
162
+ }
163
+ planeSection.append(controls);
164
+ const actions = actionRow(documentRef);
165
+ if (state.workPlane) {
166
+ const visible = button(documentRef, state.workPlane.visible ? 'Plane visible' : 'Plane hidden', { action: 'plane-visible', tip: 'Show or hide the working-plane grid', pressed: state.workPlane.visible });
167
+ visible.addEventListener('click', () => run(() => tools.setWorkPlaneVisible(!state.workPlane.visible)));
168
+ actions.append(visible);
169
+ }
170
+ const hasActiveLevel = typeof ports.activeLevelMm === 'function';
171
+ const reset = button(documentRef, hasActiveLevel ? 'Reset to active level' : 'Reset to level 0', { action: 'plane-reset', tip: hasActiveLevel ? 'Reset the working plane to the active model level' : 'Reset the working plane to the global XY plane at level zero' });
172
+ reset.addEventListener('click', () => run(() => {
173
+ const levelMm = hasActiveLevel ? finite(ports.activeLevelMm(), 'Active level') : 0;
174
+ return tools.resetWorkPlane({ levelMm });
175
+ }, 'Working plane reset.')); actions.append(reset);
176
+ if (typeof ports.setWorkPlaneFromFace === 'function') {
177
+ const face = button(documentRef, 'From selected face', { action: 'plane-face', tip: 'Set the working plane from an authenticated selected face' });
178
+ face.addEventListener('click', () => run(() => ports.setWorkPlaneFromFace(tools), 'Face working plane active.')); actions.append(face);
179
+ }
180
+ planeSection.append(actions); root.append(planeSection);
181
+ }
182
+
183
+ function renderClips(root, state) {
184
+ const clipSection = section(documentRef, `Clips · ${state.clips.length}`);
185
+ if (!state.clips.length) clipSection.append(note(documentRef, 'No active clips. Add a plane or box from the model toolbar.'));
186
+ for (const [index, clip] of state.clips.entries()) {
187
+ const card = documentRef.createElement('div'); card.className = 'model-spatial-clip'; card.dataset.clipId = clip.id;
188
+ const heading = documentRef.createElement('div'); heading.className = 'model-spatial-clip-heading';
189
+ const name = documentRef.createElement('strong'); name.textContent = `${clip.kind === 'plane' ? 'Plane' : 'Box'} ${index + 1}`;
190
+ const identity = documentRef.createElement('code'); identity.textContent = clip.id; heading.append(name, identity); card.append(heading);
191
+ const grid = documentRef.createElement('div'); grid.className = 'model-spatial-panel-grid';
192
+ if (clip.kind === 'plane') {
193
+ const a = documentRef.createElement('div'); a.className = 'model-spatial-panel-grid-label'; a.textContent = 'Origin · mm'; grid.append(a); vectorFields(documentRef, grid, 'clip-origin', clip.origin);
194
+ const b = documentRef.createElement('div'); b.className = 'model-spatial-panel-grid-label'; b.textContent = 'Normal'; grid.append(b); vectorFields(documentRef, grid, 'clip-normal', clip.normal);
195
+ } else {
196
+ const a = documentRef.createElement('div'); a.className = 'model-spatial-panel-grid-label'; a.textContent = 'Minimum · mm'; grid.append(a); vectorFields(documentRef, grid, 'clip-min', clip.min);
197
+ const b = documentRef.createElement('div'); b.className = 'model-spatial-panel-grid-label'; b.textContent = 'Maximum · mm'; grid.append(b); vectorFields(documentRef, grid, 'clip-max', clip.max);
198
+ }
199
+ card.append(grid); const actions = actionRow(documentRef);
200
+ const update = button(documentRef, 'Update', { action: 'clip-update', tip: `Apply edited values to ${name.textContent}` });
201
+ update.addEventListener('click', () => run(() => tools.updateClip(clip.id, clip.kind === 'plane'
202
+ ? { origin: valuesFrom(card, 'clip-origin', 'Clip origin'), normal: valuesFrom(card, 'clip-normal', 'Clip normal') }
203
+ : { min: valuesFrom(card, 'clip-min', 'Clip minimum'), max: valuesFrom(card, 'clip-max', 'Clip maximum') }), 'Clip updated.'));
204
+ const remove = button(documentRef, 'Remove', { action: 'clip-remove', tip: `Remove ${name.textContent}` });
205
+ remove.addEventListener('click', () => run(() => tools.removeClip(clip.id), 'Clip removed.'));
206
+ const enabled = button(documentRef, clip.enabled === false ? 'Disabled' : 'Enabled', { action: 'clip-enabled', tip: `Enable or disable ${name.textContent}`, pressed: clip.enabled !== false });
207
+ enabled.addEventListener('click', () => run(() => tools.updateClip(clip.id, { enabled: clip.enabled === false }), clip.enabled === false ? 'Clip enabled.' : 'Clip disabled.'));
208
+ actions.append(enabled, update, remove); card.append(actions); clipSection.append(card);
209
+ }
210
+ if (state.clips.length) {
211
+ const actions = actionRow(documentRef); const clear = button(documentRef, 'Clear all clips', { action: 'clip-clear', tip: 'Remove every active clip' });
212
+ clear.addEventListener('click', () => run(() => tools.clearClips(), 'All clips removed.')); actions.append(clear); clipSection.append(actions);
213
+ }
214
+ root.append(clipSection);
215
+ }
216
+
217
+ function renderWorkArea(root, state) {
218
+ const areaSection = section(documentRef, 'Work area'); const area = state.workArea;
219
+ if (!area) { areaSection.append(note(documentRef, 'No work area. Create one from the model or current selection in the toolbar.')); root.append(areaSection); return; }
220
+ const bounds = documentRef.createElement('div'); bounds.className = 'model-spatial-panel-summary';
221
+ const label = documentRef.createElement('strong'); label.textContent = area.wholeParts ? 'Whole intersecting parts' : 'Physical section cut';
222
+ const value = documentRef.createElement('span'); value.textContent = `${area.min.map(rounded).join(', ')} → ${area.max.map(rounded).join(', ')} mm`; bounds.append(label, value); areaSection.append(bounds);
223
+ const actions = actionRow(documentRef);
224
+ const whole = button(documentRef, 'Whole parts', { action: 'area-whole', tip: 'Show complete parts intersecting the work area', pressed: area.wholeParts });
225
+ whole.addEventListener('click', () => run(() => tools.setWorkAreaWhole(true)));
226
+ const cut = button(documentRef, 'Section cut', { action: 'area-cut', tip: 'Physically clip geometry at the work-area boundary', pressed: !area.wholeParts });
227
+ cut.addEventListener('click', () => run(() => tools.setWorkAreaWhole(false)));
228
+ const visible = button(documentRef, area.visible ? 'Area visible' : 'Area hidden', { action: 'area-visible', tip: 'Show or hide the active work area', pressed: area.visible });
229
+ visible.addEventListener('click', () => run(() => tools.setWorkAreaVisible(!area.visible)));
230
+ const clear = button(documentRef, 'Clear', { action: 'area-clear', tip: 'Remove the active work area' }); clear.addEventListener('click', () => run(() => tools.clearWorkArea(), 'Work area removed.'));
231
+ actions.append(whole, cut, visible, clear); areaSection.append(actions); root.append(areaSection);
232
+ }
233
+
234
+ function paint(state = tools.state()) {
235
+ const active = tools.activeFrame(); trigger.textContent = active.label; trigger.setAttribute('aria-label', `Spatial controls. Active frame: ${active.label}`);
236
+ if (!body) return;
237
+ body.replaceChildren(); renderFrame(body, state); renderWorkPlane(body, state); renderClips(body, state); renderWorkArea(body, state);
238
+ }
239
+
240
+ function position() {
241
+ if (!dialog) return;
242
+ const rect = trigger.getBoundingClientRect(); const width = dialog.offsetWidth || 420, height = dialog.offsetHeight || 560;
243
+ dialog.style.left = `${Math.max(8, Math.min(rect.left, windowRef.innerWidth - width - 8))}px`;
244
+ dialog.style.top = `${Math.max(8, rect.top - height - 7)}px`;
245
+ }
246
+
247
+ function close({ restoreFocus = true } = {}) {
248
+ if (!dialog) return;
249
+ dialog.remove(); dialog = null; body = null; status = null; trigger.setAttribute('aria-expanded', 'false');
250
+ if (restoreFocus) trigger.focus();
251
+ }
252
+
253
+ function trapKeys(event) {
254
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(); return; }
255
+ if (event.key !== 'Tab' || !dialog) return;
256
+ const focusable = [...dialog.querySelectorAll('button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex="-1"])')];
257
+ if (!focusable.length) { event.preventDefault(); dialog.focus(); return; }
258
+ const first = focusable[0], last = focusable.at(-1);
259
+ if (event.shiftKey && documentRef.activeElement === first) { event.preventDefault(); last.focus(); }
260
+ else if (!event.shiftKey && documentRef.activeElement === last) { event.preventDefault(); first.focus(); }
261
+ }
262
+
263
+ function open() {
264
+ if (destroyed || dialog) return;
265
+ try { onBeforeOpen(); } catch (_) { /* sibling popup cleanup cannot block this panel */ }
266
+ dialog = documentRef.createElement('section'); dialog.id = panelId; dialog.className = 'model-spatial-dialog model-spatial-panel';
267
+ dialog.setAttribute('role', 'dialog'); dialog.setAttribute('aria-modal', 'false'); dialog.setAttribute('tabindex', '-1');
268
+ const titleId = `${panelId}-title`; dialog.setAttribute('aria-labelledby', titleId);
269
+ const header = documentRef.createElement('div'); header.className = 'model-spatial-dialog-header';
270
+ const heading = documentRef.createElement('strong'); heading.id = titleId; heading.textContent = 'Spatial controls';
271
+ const dismiss = button(documentRef, '×', { action: 'close', tip: 'Close spatial controls' }); dismiss.setAttribute('aria-label', 'Close spatial controls'); dismiss.addEventListener('click', () => close());
272
+ header.append(heading, dismiss);
273
+ body = documentRef.createElement('div'); body.className = 'model-spatial-panel-body';
274
+ status = documentRef.createElement('div'); status.className = 'model-spatial-panel-status'; status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');
275
+ dialog.append(header, body, status); documentRef.body.append(dialog); trigger.setAttribute('aria-expanded', 'true');
276
+ dialog.addEventListener('keydown', trapKeys); paint(); position(); dialog.focus();
277
+ }
278
+
279
+ function toggle() { if (dialog) close(); else open(); }
280
+ const triggerClick = (event) => { event.stopPropagation(); toggle(); };
281
+ const outside = (event) => { if (dialog && !dialog.contains(event.target) && !trigger.contains(event.target)) close({ restoreFocus: false }); };
282
+ const resize = () => position();
283
+ trigger.addEventListener('click', triggerClick); documentRef.addEventListener('pointerdown', outside); windowRef.addEventListener?.('resize', resize);
284
+ const unsubscribe = tools.subscribe((state) => paint(state));
285
+
286
+ return Object.freeze({
287
+ open, close, toggle, isOpen: () => !!dialog,
288
+ destroy() {
289
+ if (destroyed) return; destroyed = true; close({ restoreFocus: false }); unsubscribe();
290
+ trigger.removeEventListener('click', triggerClick); documentRef.removeEventListener('pointerdown', outside); windowRef.removeEventListener?.('resize', resize);
291
+ trigger.removeAttribute('aria-haspopup'); trigger.removeAttribute('aria-controls'); trigger.removeAttribute('aria-expanded');
292
+ },
293
+ });
294
+ }
@@ -0,0 +1,249 @@
1
+ /*
2
+ * Provider-neutral spatial state for every model editor.
3
+ *
4
+ * This module owns only canonical millimetre geometry and serializable viewer state. It does not know
5
+ * Steel members, Revit categories, Three.js, or provider mutations. Providers authenticate object
6
+ * frames and apply clip/visibility effects; the shared layer keeps their interaction and persistence
7
+ * semantics identical.
8
+ */
9
+
10
+ export const MODEL_SPATIAL_STATE_SCHEMA = 'floless.model-spatial-state/v1';
11
+ export const MODEL_SPATIAL_LIMITS = Object.freeze({ savedViews: 256, frames: 128, clips: 64 });
12
+
13
+ const EPS = 1e-9;
14
+ const MAX_COORDINATE_MM = 1_000_000_000;
15
+ const clone = (value) => globalThis.structuredClone ? globalThis.structuredClone(value) : JSON.parse(JSON.stringify(value));
16
+ const freeze = (value) => {
17
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
18
+ for (const item of Object.values(value)) freeze(item);
19
+ return Object.freeze(value);
20
+ };
21
+ const snapshot = (value) => freeze(clone(value));
22
+ const finite = (value, label) => {
23
+ const next = Number(value);
24
+ if (!Number.isFinite(next)) throw new TypeError(`${label} must be finite.`);
25
+ return next;
26
+ };
27
+ const vec3 = (value, label) => {
28
+ if (!Array.isArray(value) || value.length !== 3) throw new TypeError(`${label} must be a 3D point.`);
29
+ const next = value.map((item, index) => finite(item, `${label}[${index}]`));
30
+ if (next.some((item) => Math.abs(item) > MAX_COORDINATE_MM)) throw new TypeError(`${label} exceeds the supported coordinate range.`);
31
+ return next;
32
+ };
33
+ const canonicalText = (value, label, maximum) => {
34
+ if (typeof value !== 'string' || !value || value.length > maximum || value.trim() !== value) throw new TypeError(`${label} must be trimmed and at most ${maximum} characters.`);
35
+ return value;
36
+ };
37
+ const add = (a, b) => a.map((value, index) => value + b[index]);
38
+ const sub = (a, b) => a.map((value, index) => value - b[index]);
39
+ const scale = (a, amount) => a.map((value) => value * amount);
40
+ const dot = (a, b) => a.reduce((total, value, index) => total + value * b[index], 0);
41
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
42
+ const length = (value) => Math.hypot(...value);
43
+ const unit = (value, label) => {
44
+ const magnitude = length(value);
45
+ if (!(magnitude > EPS)) throw new TypeError(`${label} is degenerate.`);
46
+ return scale(value, 1 / magnitude);
47
+ };
48
+
49
+ function canonicalFrame({ id, kind, label, origin, xAxis, yAxis, provenance = null }) {
50
+ const o = vec3(origin, `${id}.origin`);
51
+ const x = unit(vec3(xAxis, `${id}.xAxis`), `${id}.xAxis`);
52
+ const yInput = vec3(yAxis, `${id}.yAxis`);
53
+ const y = unit(sub(yInput, scale(x, dot(yInput, x))), `${id}.yAxis`);
54
+ const z = unit(cross(x, y), `${id}.zAxis`);
55
+ return snapshot({ id, kind, label, origin: o, xAxis: x, yAxis: y, zAxis: z, provenance });
56
+ }
57
+
58
+ export const GLOBAL_MODEL_FRAME = canonicalFrame({
59
+ id: 'global', kind: 'global', label: 'Global', origin: [0, 0, 0], xAxis: [1, 0, 0], yAxis: [0, 1, 0],
60
+ });
61
+
62
+ export function frameFromThreePoints({ id = 'local', kind = 'local', label = 'Local', origin, xPoint, ySide, provenance = null }) {
63
+ const o = vec3(origin, 'origin');
64
+ return canonicalFrame({ id, kind, label, origin: o, xAxis: sub(vec3(xPoint, 'xPoint'), o), yAxis: sub(vec3(ySide, 'ySide'), o), provenance });
65
+ }
66
+
67
+ export function frameCoordinates(frame, worldPoint) {
68
+ const delta = sub(vec3(worldPoint, 'worldPoint'), frame.origin);
69
+ return [dot(delta, frame.xAxis), dot(delta, frame.yAxis), dot(delta, frame.zAxis)];
70
+ }
71
+
72
+ export function framePoint(frame, coordinates) {
73
+ const local = vec3(coordinates, 'coordinates');
74
+ return [
75
+ frame.origin[0] + local[0] * frame.xAxis[0] + local[1] * frame.yAxis[0] + local[2] * frame.zAxis[0],
76
+ frame.origin[1] + local[0] * frame.xAxis[1] + local[1] * frame.yAxis[1] + local[2] * frame.zAxis[1],
77
+ frame.origin[2] + local[0] * frame.xAxis[2] + local[1] * frame.yAxis[2] + local[2] * frame.zAxis[2],
78
+ ];
79
+ }
80
+
81
+ export function parseModelCoordinates(text, { frame = GLOBAL_MODEL_FRAME, basePoint = frame.origin } = {}) {
82
+ const raw = String(text ?? '').trim();
83
+ const relative = raw.startsWith('@');
84
+ const parts = (relative ? raw.slice(1) : raw).split(',').map((item) => item.trim());
85
+ if (parts.length !== 3 || parts.some((item) => item === '' || !Number.isFinite(Number(item)))) {
86
+ throw Object.assign(new TypeError('Enter X, Y, Z as three finite millimetre values.'), { code: 'E_MODEL_COORDINATES' });
87
+ }
88
+ const local = parts.map(Number);
89
+ return relative ? add(vec3(basePoint, 'basePoint'), add(scale(frame.xAxis, local[0]), add(scale(frame.yAxis, local[1]), scale(frame.zAxis, local[2])))) : framePoint(frame, local);
90
+ }
91
+
92
+ function validatePlane(value, label = 'plane') {
93
+ if (!value || typeof value !== 'object') throw new TypeError(`${label} is required.`);
94
+ return snapshot({ origin: vec3(value.origin, `${label}.origin`), normal: unit(vec3(value.normal, `${label}.normal`), `${label}.normal`) });
95
+ }
96
+
97
+ function validateBox(value, label = 'box') {
98
+ const min = vec3(value?.min, `${label}.min`); const max = vec3(value?.max, `${label}.max`);
99
+ if (min.some((item, index) => item >= max[index])) throw new TypeError(`${label} must have positive extents.`);
100
+ return snapshot({ min, max });
101
+ }
102
+
103
+ function validateClip(value, label = 'clip') {
104
+ if (!value || typeof value !== 'object') throw new TypeError(`${label} is required.`);
105
+ const id = canonicalText(value.id, `${label}.id`, 128);
106
+ const common = { id, enabled: value.enabled, label: canonicalText(value.label, `${label}.label`, 256) };
107
+ if (typeof common.enabled !== 'boolean') throw new TypeError(`${label}.enabled must be a boolean.`);
108
+ return value.kind === 'plane'
109
+ ? snapshot({ ...common, kind: 'plane', ...validatePlane({ origin: value.origin, normal: value.normal }, label) })
110
+ : value.kind === 'box'
111
+ ? snapshot({ ...common, kind: 'box', ...validateBox({ min: value.min, max: value.max }, label) })
112
+ : (() => { throw new TypeError(`${label} kind must be plane or box.`); })();
113
+ }
114
+
115
+ function canonicalSections({ clips = [], workArea = null } = {}) {
116
+ if (!Array.isArray(clips) || clips.length > MODEL_SPATIAL_LIMITS.clips) throw Object.assign(new Error('The clip limit was reached.'), { code: 'E_MODEL_CLIP_LIMIT' });
117
+ const nextClips = clips.map((item, index) => validateClip(item, `clips[${index}]`));
118
+ if (new Set(nextClips.map((item) => item.id)).size !== nextClips.length) throw new TypeError('Clips need unique ids.');
119
+ if (new Set(nextClips.map((item) => item.label.toLocaleLowerCase('en-US'))).size !== nextClips.length) throw new TypeError('Clip labels need to be unique ignoring case.');
120
+ let nextArea = null;
121
+ if (workArea !== null) {
122
+ if (!workArea || typeof workArea !== 'object' || typeof workArea.wholeParts !== 'boolean' || typeof workArea.visible !== 'boolean') throw new TypeError('workArea must include boolean wholeParts and visible values.');
123
+ nextArea = snapshot({ ...validateBox(workArea, 'workArea'), wholeParts: workArea.wholeParts, visible: workArea.visible });
124
+ }
125
+ return { clips: nextClips, workArea: nextArea };
126
+ }
127
+
128
+ function initialState() {
129
+ return {
130
+ schema: MODEL_SPATIAL_STATE_SCHEMA,
131
+ revision: 0,
132
+ activeFrameId: 'global',
133
+ frames: [GLOBAL_MODEL_FRAME],
134
+ workPlane: null,
135
+ savedViews: [],
136
+ clips: [],
137
+ workArea: null,
138
+ visibility: { hidden: [], isolated: [] },
139
+ };
140
+ }
141
+
142
+ /** @param {{ initial?: any, onChange?: (state:any, reason:string)=>void }} options */
143
+ export function createModelSpatialTools({ initial = null, onChange = () => {} } = {}) {
144
+ /** @type {any} */
145
+ let state = initialState();
146
+ const listeners = new Set();
147
+ let disposed = false;
148
+ const ensureLive = () => { if (disposed) throw Object.assign(new Error('Model spatial tools are disposed.'), { code: 'E_MODEL_SPATIAL_DISPOSED' }); };
149
+ const emit = (reason) => {
150
+ state.revision += 1;
151
+ const value = snapshot(state);
152
+ for (const listener of listeners) { try { listener(value, reason); } catch (_) { /* subscribers cannot roll state back */ } }
153
+ try { onChange(value, reason); } catch (_) { /* persistence/reporting is isolated */ }
154
+ return value;
155
+ };
156
+ const frameIndex = (id) => state.frames.findIndex((frame) => frame.id === id);
157
+ const frame = (id = state.activeFrameId) => state.frames[frameIndex(id)] ?? GLOBAL_MODEL_FRAME;
158
+ const upsertFrame = (next, reason) => {
159
+ const at = frameIndex(next.id);
160
+ if (at >= 0) state.frames[at] = next; else {
161
+ if (state.frames.length >= MODEL_SPATIAL_LIMITS.frames) throw Object.assign(new Error('The saved frame limit was reached.'), { code: 'E_MODEL_FRAME_LIMIT' });
162
+ state.frames.push(next);
163
+ }
164
+ state.activeFrameId = next.id;
165
+ return emit(reason);
166
+ };
167
+
168
+ const api = {
169
+ state: () => snapshot(state),
170
+ subscribe(listener) { ensureLive(); if (typeof listener !== 'function') throw new TypeError('Subscriber must be a function.'); listeners.add(listener); try { listener(snapshot(state), 'replay'); } catch (_) { /* replay is isolated like later publications */ } let active = true; return () => { if (active) { active = false; listeners.delete(listener); } }; },
171
+ activeFrame: () => snapshot(frame()),
172
+ coordinates(point) { return frameCoordinates(frame(), point); },
173
+ point(coordinates) { return framePoint(frame(), coordinates); },
174
+ parseCoordinates(text, basePoint) { return parseModelCoordinates(text, { frame: frame(), basePoint }); },
175
+ activateFrame(id) { ensureLive(); if (frameIndex(id) < 0) throw Object.assign(new Error(`Frame ${id} is unavailable.`), { code: 'E_MODEL_FRAME_UNAVAILABLE' }); state.activeFrameId = id; return emit('frame-activate'); },
176
+ removeFrame(id) { ensureLive(); if (id === 'global') throw new TypeError('The global frame cannot be removed.'); const before = state.frames.length; state.frames = state.frames.filter((item) => item.id !== id); if (state.workPlane?.frameId === id) state.workPlane = null; if (state.activeFrameId === id) state.activeFrameId = frameIndex('local') >= 0 ? 'local' : 'global'; return before === state.frames.length ? snapshot(state) : emit('frame-remove'); },
177
+ setLocalFromThreePoints(points) { ensureLive(); return upsertFrame(frameFromThreePoints({ ...points, id: 'local', kind: 'local', label: 'Local' }), 'frame-local-three-points'); },
178
+ setLocalTransform({ origin, xAxis, yAxis }) { ensureLive(); return upsertFrame(canonicalFrame({ id: 'local', kind: 'local', label: 'Local', origin, xAxis, yAxis }), 'frame-local-edit'); },
179
+ setLocalOrigin(origin) { ensureLive(); const current = frame('local'); if (current.id !== 'local') throw Object.assign(new Error('Create the local frame first.'), { code: 'E_MODEL_FRAME_UNAVAILABLE' }); return upsertFrame(canonicalFrame({ ...current, origin }), 'frame-local-origin'); },
180
+ setObjectFrame(record) {
181
+ ensureLive();
182
+ if (record?.authenticated !== true || typeof record?.providerRef !== 'string' || !record.providerRef) {
183
+ throw Object.assign(new Error('An object frame requires an authenticated provider record.'), { code: 'E_MODEL_FRAME_UNAUTHENTICATED' });
184
+ }
185
+ return upsertFrame(canonicalFrame({ id: 'object', kind: 'object', label: 'Object', origin: record.origin, xAxis: record.xAxis, yAxis: record.yAxis, provenance: { providerRef: record.providerRef } }), 'frame-object');
186
+ },
187
+ resetGlobal() { ensureLive(); state.activeFrameId = 'global'; return emit('frame-global'); },
188
+ clearSessionFrames() { ensureLive(); state.frames = [GLOBAL_MODEL_FRAME]; state.activeFrameId = 'global'; state.workPlane = null; return emit('frames-clear'); },
189
+ setWorkPlaneFromThreePoints(points) {
190
+ ensureLive(); const next = frameFromThreePoints({ ...points, id: 'work-plane', kind: 'work-plane', label: 'Working plane' });
191
+ const at = frameIndex('work-plane'); if (at >= 0) state.frames[at] = next; else state.frames.push(next);
192
+ state.workPlane = { frameId: 'work-plane', visible: true, source: 'three-points', offsetMm: 0 }; state.activeFrameId = 'work-plane'; return emit('work-plane-three-points');
193
+ },
194
+ setWorkPlaneFromFace({ origin, normal, xHint = [1, 0, 0], providerRef = null }) {
195
+ ensureLive(); const plane = validatePlane({ origin, normal }); let x = sub(vec3(xHint, 'xHint'), scale(plane.normal, dot(xHint, plane.normal)));
196
+ if (length(x) <= EPS) x = Math.abs(plane.normal[2]) < .9 ? cross([0, 0, 1], plane.normal) : cross([0, 1, 0], plane.normal);
197
+ const y = cross(plane.normal, x); const next = canonicalFrame({ id: 'work-plane', kind: 'work-plane', label: 'Working plane', origin: plane.origin, xAxis: x, yAxis: y, provenance: providerRef ? { providerRef } : null });
198
+ const at = frameIndex('work-plane'); if (at >= 0) state.frames[at] = next; else state.frames.push(next);
199
+ state.workPlane = { frameId: 'work-plane', visible: true, source: 'face', offsetMm: 0 }; state.activeFrameId = 'work-plane'; return emit('work-plane-face');
200
+ },
201
+ setPrincipalWorkPlane({ plane, offsetMm = 0 }) {
202
+ ensureLive(); const offset = finite(offsetMm, 'offsetMm'); const bases = {
203
+ xy: { origin: [0, 0, offset], xAxis: [1, 0, 0], yAxis: [0, 1, 0] },
204
+ xz: { origin: [0, offset, 0], xAxis: [1, 0, 0], yAxis: [0, 0, 1] },
205
+ yz: { origin: [offset, 0, 0], xAxis: [0, 1, 0], yAxis: [0, 0, 1] },
206
+ };
207
+ if (!bases[plane]) throw new TypeError('Working plane must be xy, xz, or yz.');
208
+ const next = canonicalFrame({ id: 'work-plane', kind: 'work-plane', label: `Working plane ${plane.toUpperCase()}`, ...bases[plane] });
209
+ const at = frameIndex('work-plane'); if (at >= 0) state.frames[at] = next; else state.frames.push(next);
210
+ state.workPlane = { frameId: 'work-plane', visible: true, source: 'principal', principal: plane, offsetMm: offset }; state.activeFrameId = 'work-plane'; return emit('work-plane-principal');
211
+ },
212
+ setWorkPlaneVisible(visible) { ensureLive(); if (!state.workPlane) throw Object.assign(new Error('No working plane exists.'), { code: 'E_MODEL_WORK_PLANE_UNAVAILABLE' }); state.workPlane.visible = visible === true; return emit('work-plane-visible'); },
213
+ clearWorkPlane() { ensureLive(); const hadPlane = !!state.workPlane || frameIndex('work-plane') >= 0; state.workPlane = null; state.frames = state.frames.filter((item) => item.id !== 'work-plane'); if (state.activeFrameId === 'work-plane') state.activeFrameId = frameIndex('local') >= 0 ? 'local' : 'global'; return hadPlane ? emit('work-plane-clear') : snapshot(state); },
214
+ resetWorkPlane({ levelMm = 0 } = {}) { return api.setPrincipalWorkPlane({ plane: 'xy', offsetMm: finite(levelMm, 'levelMm') }); },
215
+ saveView(view) {
216
+ ensureLive(); if (state.savedViews.length >= MODEL_SPATIAL_LIMITS.savedViews) throw Object.assign(new Error('The saved view limit was reached.'), { code: 'E_MODEL_VIEW_LIMIT' });
217
+ const id = String(view?.id ?? '').trim(); const name = String(view?.name ?? '').trim();
218
+ if (!id || !name || state.savedViews.some((item) => item.id === id)) throw new TypeError('Saved views need a unique id and non-empty name.');
219
+ state.savedViews.push(snapshot({ ...clone(view), id, name, frameId: view.frameId ?? state.activeFrameId })); return emit('view-save');
220
+ },
221
+ updateView(id, patch) { ensureLive(); const at = state.savedViews.findIndex((item) => item.id === id); if (at < 0) throw Object.assign(new Error('Saved view not found.'), { code: 'E_MODEL_VIEW_NOT_FOUND' }); state.savedViews[at] = snapshot({ ...state.savedViews[at], ...clone(patch), id }); return emit('view-update'); },
222
+ deleteView(id) { ensureLive(); const before = state.savedViews.length; state.savedViews = state.savedViews.filter((item) => item.id !== id); return before === state.savedViews.length ? snapshot(state) : emit('view-delete'); },
223
+ addClipPlane({ id, origin, normal, enabled = true, label = id }) { ensureLive(); if (state.clips.length >= MODEL_SPATIAL_LIMITS.clips) throw Object.assign(new Error('The clip limit was reached.'), { code: 'E_MODEL_CLIP_LIMIT' }); if (!id || state.clips.some((item) => item.id === id)) throw new TypeError('Clip needs a unique id.'); state.clips.push(validateClip({ id, kind: 'plane', origin, normal, enabled, label })); return emit('clip-add'); },
224
+ addClipBox({ id, min, max, enabled = true, label = id }) { ensureLive(); if (state.clips.length >= MODEL_SPATIAL_LIMITS.clips) throw Object.assign(new Error('The clip limit was reached.'), { code: 'E_MODEL_CLIP_LIMIT' }); if (!id || state.clips.some((item) => item.id === id)) throw new TypeError('Clip needs a unique id.'); state.clips.push(validateClip({ id, kind: 'box', min, max, enabled, label })); return emit('clip-add'); },
225
+ updateClip(id, patch) { ensureLive(); const at = state.clips.findIndex((item) => item.id === id); if (at < 0) throw Object.assign(new Error('Clip not found.'), { code: 'E_MODEL_CLIP_NOT_FOUND' }); state.clips[at] = validateClip({ ...state.clips[at], ...clone(patch), id }, 'clip'); return emit('clip-update'); },
226
+ /** @param {{clips?:any[],workArea?:any}} sections */
227
+ replaceSections(sections = {}) { ensureLive(); const next = canonicalSections(sections); state.clips = next.clips; state.workArea = next.workArea; return emit('sections-replace'); },
228
+ removeClip(id) { ensureLive(); const before = state.clips.length; state.clips = state.clips.filter((item) => item.id !== id); return before === state.clips.length ? snapshot(state) : emit('clip-remove'); },
229
+ clearClips() { ensureLive(); state.clips = []; return emit('clip-clear'); },
230
+ setWorkArea({ min, max, wholeParts = true }) { ensureLive(); state.workArea = { ...validateBox({ min, max }, 'workArea'), wholeParts: wholeParts === true, visible: true }; return emit('work-area'); },
231
+ setWorkAreaVisible(visible) { ensureLive(); if (!state.workArea) throw Object.assign(new Error('No work area exists.'), { code: 'E_MODEL_WORK_AREA_UNAVAILABLE' }); state.workArea.visible = visible === true; return emit('work-area-visible'); },
232
+ setWorkAreaWhole(wholeParts) { ensureLive(); if (!state.workArea) throw Object.assign(new Error('No work area exists.'), { code: 'E_MODEL_WORK_AREA_UNAVAILABLE' }); state.workArea.wholeParts = wholeParts === true; return emit('work-area-whole'); },
233
+ clearWorkArea() { ensureLive(); state.workArea = null; return emit('work-area-clear'); },
234
+ setVisibility({ hidden = [], isolated = [] }) { ensureLive(); if (![hidden, isolated].every((items) => Array.isArray(items) && items.every((item) => typeof item === 'string'))) throw new TypeError('Visibility keys must be string arrays.'); state.visibility = { hidden: [...new Set(hidden)], isolated: [...new Set(isolated)] }; return emit('visibility'); },
235
+ showAll() { ensureLive(); state.visibility = { hidden: [], isolated: [] }; return emit('visibility-show-all'); },
236
+ serialize() { ensureLive(); return snapshot({ schema: MODEL_SPATIAL_STATE_SCHEMA, activeFrameId: state.activeFrameId, frames: state.frames, workPlane: state.workPlane, savedViews: state.savedViews, clips: state.clips, workArea: state.workArea, visibility: state.visibility }); },
237
+ dispose() { if (disposed) return; disposed = true; listeners.clear(); },
238
+ };
239
+
240
+ if (initial) {
241
+ if (initial.schema !== MODEL_SPATIAL_STATE_SCHEMA) throw new TypeError('Unsupported model spatial state schema.');
242
+ state = { ...initialState(), ...clone(initial), revision: 0 };
243
+ state.frames = [GLOBAL_MODEL_FRAME, ...(initial.frames ?? []).filter((item) => item.id !== 'global').map((item) => canonicalFrame(item))];
244
+ const sections = canonicalSections({ clips: initial.clips ?? [], workArea: initial.workArea ?? null });
245
+ state.clips = sections.clips; state.workArea = sections.workArea;
246
+ if (!state.frames.some((item) => item.id === state.activeFrameId)) state.activeFrameId = 'global';
247
+ }
248
+ return Object.freeze(api);
249
+ }
@@ -0,0 +1,47 @@
1
+ /*
2
+ * model-tree.js - the cap-window arithmetic a model tree needs, and nothing else.
3
+ *
4
+ * WHAT THIS IS NOT. It is not a virtual tree, and the parent plan's `model-virtual-tree.js` is not what
5
+ * this repo wants. Nothing in this app windows a list: the Explorer's body is a plain `overflow:auto`,
6
+ * and the reference tree deliberately rejected virtualisation in favour of lazy group building plus a
7
+ * cap that is STATED in the UI rather than applied silently. Introducing row recycling here would be a
8
+ * second solution to a solved problem, arriving inside a refactor whose contract is "no behaviour
9
+ * change". So this file carries the arithmetic that already shipped, under a name that describes it.
10
+ *
11
+ * WHY ONLY ONE EXPORT. An earlier draft also exported a filter matcher and ctrl/shift selection, on the
12
+ * strength of "two consumers in Steel today". Only the windowing is actually wired, which would have
13
+ * left the other two as code nobody calls - exactly what this task refuses a virtual tree for. Applying
14
+ * that rule to this module rather than only to someone else's: the unwired exports did not ship. They
15
+ * are one line each to add when something calls them.
16
+ *
17
+ * NO DOM AND NO GLOBALS. Guarded in server/model-editor-facade.test.ts alongside the contract and the
18
+ * adapter - this is pure arithmetic, so it is in the strict group, not the DOM-half one.
19
+ */
20
+
21
+ /**
22
+ * Which slice of `list` to render, given a cap and a row that must stay visible.
23
+ *
24
+ * THE KEEP-THE-SELECTION CLAUSE IS THE WHOLE POINT. A plain `slice(0, cap)` is one character shorter
25
+ * and silently breaks "drilling into an object in 3D shows you its row": on the 9,210-object IFCMEMBER
26
+ * group that motivated the cap, it would be false for 8,910 of them. When the selection sits past the
27
+ * cap the window centres on it instead, which is why the offset is `cap >> 1` rather than 0.
28
+ *
29
+ * `selectedIndex` is a position in the list AS PASSED - callers hand in `list.indexOf(...)` over their
30
+ * filtered array, so a filtered view windows by its own positions. `-1` (indexOf's miss) means nothing
31
+ * is selected, and must not be read as row 0.
32
+ *
33
+ * `hidden` is not an internal: it is the number the UI prints ("Showing 300 of 9,210"). The caller owns
34
+ * the wording and the cap; this owns only the arithmetic.
35
+ *
36
+ * @param {{ list: unknown[], selectedIndex: number, cap: number }} o
37
+ * @returns {{ from: number, shown: unknown[], hidden: number }}
38
+ */
39
+ export function windowRows({ list, selectedIndex, cap }) {
40
+ // `from` needs no Math.max(0, …): the branch runs only when the selection index reaches the cap, and
41
+ // an index into the list is below its length, so length is above the cap whenever this fires. Stated
42
+ // because it reads like a missing guard, and a test pins it.
43
+ let from = 0;
44
+ if (selectedIndex >= cap) from = Math.min(selectedIndex - (cap >> 1), list.length - cap);
45
+ const shown = list.slice(from, from + cap);
46
+ return { from, shown, hidden: Math.max(0, list.length - shown.length) };
47
+ }