@floless/app 0.138.2 → 0.139.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/autostart.mjs +6 -2
- package/desktop-access-production-manifest.mjs +7 -0
- package/dist/floless-server.cjs +157207 -70887
- package/dist/schemas/model.continuation.v1.schema.json +19 -0
- package/dist/schemas/model.continuation.v2.schema.json +19 -0
- package/dist/schemas/model.query-response.v1.schema.json +95 -0
- package/dist/schemas/model.query-response.v2.schema.json +80 -0
- package/dist/schemas/model.query.v1.schema.json +87 -0
- package/dist/schemas/model.query.v2.schema.json +87 -0
- package/dist/schemas/model.snap-candidate.v1.schema.json +48 -0
- package/dist/schemas/model.snap-constraint.v1.schema.json +18 -0
- package/dist/schemas/model.snap-query.v1.schema.json +24 -0
- package/dist/schemas/model.snap-result.v1.schema.json +33 -0
- package/dist/schemas/model.snapshot.v1.schema.json +136 -0
- package/dist/schemas/revit.model.v1.schema.json +24 -0
- package/dist/schemas/steel.model.v2.schema.json +45 -6
- package/dist/skills/floless-app-approval/SKILL.md +19 -5
- package/dist/skills/floless-app-bridge/SKILL.md +19 -6
- package/dist/skills/floless-app-knowledge/SKILL.md +22 -1
- package/dist/skills/floless-app-new-workflow/SKILL.md +31 -27
- package/dist/skills/floless-app-new-workflow/references/build-and-verify.md +13 -12
- package/dist/skills/floless-app-onboarding/SKILL.md +3 -3
- package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +16 -9
- package/dist/skills/floless-app-steel-model/SKILL.md +11 -2
- package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +95 -0
- package/dist/skills/floless-app-steel-takeoff/SKILL.md +142 -21
- package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +19 -0
- package/dist/skills/floless-app-tweak-contract/SKILL.md +42 -8
- package/dist/skills/floless-app-vectorize/SKILL.md +19 -6
- package/dist/skills/floless-app-workflows/SKILL.md +30 -3
- package/dist/skills/floless-app-workflows/references/workspace-data.md +77 -4
- package/dist/templates/floless-workspace-model-report.flo +77 -0
- package/dist/templates/revit-model.flo +111 -0
- package/dist/web/app.css +415 -177
- package/dist/web/app.js +302 -51
- package/dist/web/aware.js +1357 -1032
- package/dist/web/chat.css +692 -0
- package/dist/web/chat.js +2651 -0
- package/dist/web/commands-revit.js +42 -0
- package/dist/web/commands-shell.js +531 -70
- package/dist/web/commands-steel.js +344 -146
- package/dist/web/commands.js +1 -1
- package/dist/web/index.html +283 -77
- package/dist/web/instructor.js +217 -36
- package/dist/web/left-pane.js +636 -0
- package/dist/web/model-artifact-loader.js +75 -0
- package/dist/web/model-authoring-gestures.js +141 -0
- package/dist/web/model-cad-tools.js +20 -0
- package/dist/web/model-clip-gesture.js +148 -0
- package/dist/web/model-clip-list.js +156 -0
- package/dist/web/model-clip-session.js +274 -0
- package/dist/web/model-clip-three-overlay.js +295 -0
- package/dist/web/model-clip-three-preview.js +59 -0
- package/dist/web/model-editor-contract.js +519 -0
- package/dist/web/model-editor-revit-adapter.js +139 -0
- package/dist/web/model-editor-shell.js +271 -0
- package/dist/web/model-editor-state-recovery.js +44 -0
- package/dist/web/model-editor-steel-adapter.js +415 -0
- package/dist/web/model-editor.css +268 -0
- package/dist/web/model-frame.js +192 -0
- package/dist/web/model-inspector.js +128 -0
- package/dist/web/model-measure.js +390 -0
- package/dist/web/model-navigation-controls.js +246 -0
- package/dist/web/model-orientation-overlay.js +217 -0
- package/dist/web/model-panel-bridge.js +230 -0
- package/dist/web/model-pointer-dock.js +164 -0
- package/dist/web/model-revit-module.js +83 -0
- package/dist/web/model-selection-coordinator.js +151 -0
- package/dist/web/model-selection-tools.js +290 -0
- package/dist/web/model-snap-contract.js +267 -0
- package/dist/web/model-snapping.js +497 -0
- package/dist/web/model-spatial-panel.js +294 -0
- package/dist/web/model-spatial-tools.js +249 -0
- package/dist/web/model-tree.js +47 -0
- package/dist/web/model-viewport-lighting.js +166 -0
- package/dist/web/model-viewport-revit-adapter.js +1224 -0
- package/dist/web/model-viewport-state.js +505 -0
- package/dist/web/model-viewport-steel-adapter.js +150 -0
- package/dist/web/model-viewport-toolbar.js +516 -0
- package/dist/web/model-viewport.js +717 -0
- package/dist/web/panels.js +8 -15
- package/dist/web/renderers.js +3 -0
- package/dist/web/revit-editor.css +35 -0
- package/dist/web/revit-editor.html +74 -0
- package/dist/web/revit-editor.js +845 -0
- package/dist/web/steel-3d-core.js +16 -44
- package/dist/web/steel-3d-view.js +1384 -633
- package/dist/web/steel-canvas-guidance.js +3 -1
- package/dist/web/steel-editor.html +2145 -1255
- package/dist/web/steel-filter.html +5 -1
- package/dist/web/steel-model-v2-commands.js +80 -3
- package/dist/web/steel-split-view.js +5 -39
- package/dist/web/steel-view-generation.js +107 -17
- package/dist/web/vector-3d.html +12 -0
- package/dist/web/workspaces.js +2154 -283
- package/distribution-profile-active.mjs +2 -0
- package/distribution-profile-production.mjs +47 -0
- package/distribution-profile-shared.mjs +8 -0
- package/distribution-profile.mjs +18 -0
- package/distribution-resource-inventory.mjs +81 -0
- package/launch.mjs +18 -10
- package/log.mjs +2 -1
- package/managed-runtime-policy.mjs +104 -0
- package/model-reader-policy-active.mjs +7 -0
- package/network-policy-active.mjs +6 -0
- package/package.json +17 -2
- package/post-update-marker.mjs +3 -1
- package/rvt-production-uat-authority.mjs +60 -0
- package/teardown.mjs +4 -3
|
@@ -0,0 +1,845 @@
|
|
|
1
|
+
import { mountInspectorShell } from './model-inspector.js';
|
|
2
|
+
import { mountModelEditorShell, mountSidePanel } from './model-editor-shell.js';
|
|
3
|
+
import { mountToolbarChrome, renderToolbarMarkup } from './model-viewport-toolbar.js';
|
|
4
|
+
import { mountModelLightingPanel } from './model-viewport-lighting.js';
|
|
5
|
+
import { createRevitEditorAdapter, revitRenderPlan } from './model-editor-revit-adapter.js';
|
|
6
|
+
import {
|
|
7
|
+
buildRevitClassificationTree, filterRevitPropertyGroups, groupRevitProperties,
|
|
8
|
+
revitExplorerTabs, revitPropertyEncodingLabel,
|
|
9
|
+
} from './model-revit-module.js';
|
|
10
|
+
import { createRevitViewport } from './model-viewport-revit-adapter.js';
|
|
11
|
+
import { mountModelOrientationOverlay } from './model-orientation-overlay.js';
|
|
12
|
+
import { mountModelMeasureTool } from './model-measure.js';
|
|
13
|
+
import { createModelCadToolController } from './model-cad-tools.js';
|
|
14
|
+
import { createModelSelectionTools } from './model-selection-tools.js';
|
|
15
|
+
import { mountModelPointerDock, REVIT_POINTER_DOCK_PLAN } from './model-pointer-dock.js';
|
|
16
|
+
import { createModelSpatialTools } from './model-spatial-tools.js';
|
|
17
|
+
import { mountModelSpatialPanel } from './model-spatial-panel.js';
|
|
18
|
+
import { createModelClipSession } from './model-clip-session.js';
|
|
19
|
+
import { mountModelClipList } from './model-clip-list.js';
|
|
20
|
+
import { createModelEditorStateRecoveryStore } from './model-editor-state-recovery.js';
|
|
21
|
+
import {
|
|
22
|
+
MODEL_EXPLORER_ENTITY_CAP, MODEL_EXPLORER_GROUP_CAP, assertModelViewerRowBudget,
|
|
23
|
+
preflightModelJsonReceipt, readModelBinaryArtifact, readModelJsonArtifact,
|
|
24
|
+
} from './model-artifact-loader.js';
|
|
25
|
+
import { createModelPanelBridge, createModelSelectionOriginGuard, createPanelHost, expandModelPanelGroup, serializeModelPanelNodes } from './model-panel-bridge.js';
|
|
26
|
+
|
|
27
|
+
const $ = (id) => document.getElementById(id);
|
|
28
|
+
const projectId = new URLSearchParams(location.search).get('project') || '';
|
|
29
|
+
let entities = [], properties = [], relationships = [], entityById = new Map(), propertyByEntity = new Map(), selectedId = null, selectedIds = [], selectionOrigin = 'tree', classificationFollowedId = null, facade = null, viewport = null, inspector = null;
|
|
30
|
+
let measureTool = null;
|
|
31
|
+
let cadTools = null;
|
|
32
|
+
let selectionTools = null;
|
|
33
|
+
let selectionFilterChrome = null;
|
|
34
|
+
let spatialTools = null;
|
|
35
|
+
let releaseSpatialViewport = null;
|
|
36
|
+
let spatialPanel = null;
|
|
37
|
+
let clipSession = null;
|
|
38
|
+
let clipList = null;
|
|
39
|
+
let releaseClipViewport = null;
|
|
40
|
+
let releaseClipEditor = null;
|
|
41
|
+
let modelShellMount = null;
|
|
42
|
+
let spatialDialog = null;
|
|
43
|
+
let editorStateEtag = null;
|
|
44
|
+
let editorStateBinding = null;
|
|
45
|
+
let editorStateSaveTimer = null;
|
|
46
|
+
let editorStateLoaded = null;
|
|
47
|
+
let editorStateBindingToken = 0;
|
|
48
|
+
let editorStateDirtyGeneration = 0;
|
|
49
|
+
let editorStateSavedGeneration = 0;
|
|
50
|
+
let editorStateSaveQueue = Promise.resolve();
|
|
51
|
+
let editorStateDirtyPayload = null;
|
|
52
|
+
let projectContract = null;
|
|
53
|
+
let sharedTools = null;
|
|
54
|
+
let terminalDisposed = false;
|
|
55
|
+
let bfcacheSuspended = false;
|
|
56
|
+
let revisionLoadToken = 0;
|
|
57
|
+
let revisionLoadController = null;
|
|
58
|
+
const MODEL_VIEWER_MAX_TILE_BYTES = 256 * 1024 * 1024;
|
|
59
|
+
const MODEL_VIEWER_MAX_AGGREGATE_BYTES = MODEL_VIEWER_MAX_TILE_BYTES + (128 * 1024 * 1024 * 5);
|
|
60
|
+
const editorStateRecovery = createModelEditorStateRecoveryStore({
|
|
61
|
+
storage: localStorage,
|
|
62
|
+
key: 'floless:revit-editor-dirty:v1',
|
|
63
|
+
schema: 'floless.revit-editor-dirty/v1',
|
|
64
|
+
maxBytes: 512 * 1024,
|
|
65
|
+
});
|
|
66
|
+
let modelPanelBridge = null;
|
|
67
|
+
const selectionOriginGuard = createModelSelectionOriginGuard();
|
|
68
|
+
|
|
69
|
+
function modelPanelSnapshot() {
|
|
70
|
+
const bodies = {};
|
|
71
|
+
for (const tab of revitExplorerTabs) bodies[tab.key] = serializeModelPanelNodes($(tab.bodyId), tab.key);
|
|
72
|
+
return { context: $('modelName')?.textContent || 'Project model', selectedId, selectedIds: [...selectedIds], selectionOrigin,
|
|
73
|
+
tabs: revitExplorerTabs.map((tab) => ({ key: tab.key, label: tab.key[0].toUpperCase() + tab.key.slice(1) })), bodies,
|
|
74
|
+
panelTabs: REVIT_PANEL_TABS };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let realisticFallbackAnnounced = false;
|
|
78
|
+
function toast(message) { const el = $('toast'); el.textContent = message; el.classList.add('show'); clearTimeout(toast.timer); toast.timer = setTimeout(() => el.classList.remove('show'), 2400); }
|
|
79
|
+
function fail(message) { const state = $('loadingState'); state.replaceChildren(); const strong = document.createElement('strong'); strong.textContent = 'Model unavailable'; const copy = document.createElement('span'); copy.textContent = message; state.append(strong, copy); }
|
|
80
|
+
async function json(url, options) { const response = await fetch(url, { credentials: 'same-origin', ...options }); const value = await response.json().catch(() => ({})); if (!response.ok || value.ok === false) throw new Error(value.message || value.error || `Request failed (${response.status})`); return value; }
|
|
81
|
+
|
|
82
|
+
function propertySection(heading, rows) {
|
|
83
|
+
return { id: heading.toLowerCase().replace(/\W+/g, '-'), heading, editable: false, render(host) {
|
|
84
|
+
for (const [key, value] of rows) { const row = document.createElement('div'); row.className = 'property-row'; const a = document.createElement('span'); a.className = 'property-key'; a.textContent = key; const b = document.createElement('bdi'); b.className = 'property-value'; b.textContent = value == null || value === '' ? '—' : String(value); row.append(a, b); host.append(row); }
|
|
85
|
+
} };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function importedPropertySection(groups) {
|
|
89
|
+
return { id: 'imported-parameters', heading: 'Imported parameters', editable: false, render(host) {
|
|
90
|
+
const search = document.createElement('input'); search.type = 'search'; search.className = 'revit-property-search';
|
|
91
|
+
search.placeholder = 'Search selected object'; search.setAttribute('aria-label', 'Search selected object properties');
|
|
92
|
+
const results = document.createElement('div'); results.className = 'revit-property-groups';
|
|
93
|
+
const paint = (query = '') => {
|
|
94
|
+
results.replaceChildren();
|
|
95
|
+
const visible = filterRevitPropertyGroups(groups, query);
|
|
96
|
+
if (!visible.length) { const empty = document.createElement('div'); empty.className = 'insp-note'; empty.textContent = query ? 'No matching imported parameters.' : 'No imported parameters were supplied for this object.'; results.append(empty); return; }
|
|
97
|
+
for (const [groupIndex, group] of visible.entries()) {
|
|
98
|
+
const section = document.createElement('section'); section.className = 'revit-property-group';
|
|
99
|
+
const trigger = document.createElement('button'); trigger.type = 'button'; trigger.className = 'revit-property-group-trigger';
|
|
100
|
+
const label = document.createElement('span'); label.textContent = group.name;
|
|
101
|
+
const count = document.createElement('span'); count.className = 'explorer-count'; count.textContent = String(group.rows.length);
|
|
102
|
+
trigger.append(label, count); trigger.setAttribute('aria-expanded', String(visible.length === 1 || groupIndex === 0));
|
|
103
|
+
const body = document.createElement('div'); body.className = 'revit-property-group-body'; body.hidden = trigger.getAttribute('aria-expanded') !== 'true';
|
|
104
|
+
for (const item of group.rows) {
|
|
105
|
+
const row = document.createElement('div'); row.className = 'revit-imported-property';
|
|
106
|
+
const key = document.createElement('span'); key.className = 'property-key'; key.textContent = item.name || item.parameterId || 'Unnamed parameter';
|
|
107
|
+
const value = document.createElement('bdi'); value.className = 'property-value';
|
|
108
|
+
const rendered = item.value == null ? '—' : String(item.value); value.textContent = item.unit ? `${rendered} ${item.unit}` : rendered;
|
|
109
|
+
const provenance = document.createElement('span'); provenance.className = 'revit-property-provenance'; provenance.textContent = revitPropertyEncodingLabel(item);
|
|
110
|
+
const copy = document.createElement('button'); copy.type = 'button'; copy.className = 'revit-property-copy'; copy.textContent = 'Copy';
|
|
111
|
+
copy.dataset.tip = 'Copy this imported display value'; copy.setAttribute('aria-label', `Copy ${key.textContent}`);
|
|
112
|
+
copy.addEventListener('click', async () => { try { await navigator.clipboard.writeText(rendered); toast('Property value copied.'); } catch { toast('Could not copy this property value.'); } });
|
|
113
|
+
row.append(key, value, provenance, copy); body.append(row);
|
|
114
|
+
}
|
|
115
|
+
trigger.addEventListener('click', () => { const open = trigger.getAttribute('aria-expanded') !== 'true'; trigger.setAttribute('aria-expanded', String(open)); body.hidden = !open; });
|
|
116
|
+
section.append(trigger, body); results.append(section);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
let timer = null; search.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(() => paint(search.value), 120); });
|
|
120
|
+
host.append(search, results); paint();
|
|
121
|
+
} };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function inspect(id, syncViewport = true, publish = true, origin = 'tree') {
|
|
125
|
+
selectedId = id;
|
|
126
|
+
selectionOrigin = origin;
|
|
127
|
+
if (syncViewport) selectedIds = id ? [id] : [];
|
|
128
|
+
window.__revitInstructorState = { ...(window.__revitInstructorState || {}), selected: id };
|
|
129
|
+
if (syncViewport) {
|
|
130
|
+
if (id) clipSession?.clearSelection?.();
|
|
131
|
+
selectionOriginGuard.run(() => viewport.setSelection({ ids: id ? [id] : [] }));
|
|
132
|
+
}
|
|
133
|
+
updateSelectionActions();
|
|
134
|
+
const modelHostId = revitExplorerTabs.find((tab) => tab.key === 'model')?.bodyId;
|
|
135
|
+
const nextFollowedId = selectedIds.length === 1 && entities.slice(MODEL_EXPLORER_ENTITY_CAP).some((item) => item.id === selectedIds[0]) ? selectedIds[0] : null;
|
|
136
|
+
const classificationChanged = nextFollowedId !== classificationFollowedId;
|
|
137
|
+
if (classificationChanged && modelHostId) {
|
|
138
|
+
renderClassification($(modelHostId), entities, relationships, nextFollowedId);
|
|
139
|
+
classificationFollowedId = nextFollowedId;
|
|
140
|
+
if (publish) modelPanelBridge?.publishSnapshot();
|
|
141
|
+
}
|
|
142
|
+
if (!id) { inspector.render({ state: 'empty' }); if (publish) modelPanelBridge?.publishSelection(selectionOrigin); return true; }
|
|
143
|
+
const entity = entityById.get(id);
|
|
144
|
+
if (!entity) { inspector.render({ state: 'unavailable', message: 'This object is not in the loaded revision.' }); if (publish) modelPanelBridge?.publishSelection(selectionOrigin); return false; }
|
|
145
|
+
const own = propertyByEntity.get(id) || [];
|
|
146
|
+
const groups = groupRevitProperties(own);
|
|
147
|
+
const sections = [propertySection('Identity', [['Element', entity.id], ['Name', entity.name], ['Category', entity.categoryName ?? entity.category], ['Family', entity.familyName ?? entity.family], ['Type', entity.typeName], ['Level', entity.levelName]])];
|
|
148
|
+
sections.push(importedPropertySection(groups));
|
|
149
|
+
inspector.render({ state: 'ready', heading: entity.name || entity.typeName || entity.id, sections });
|
|
150
|
+
if (publish) modelPanelBridge?.publishSelection(selectionOrigin);
|
|
151
|
+
window.__instructor?.notifyChanged();
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function row(label, count, entityId) {
|
|
156
|
+
const button = document.createElement('button'); button.type = 'button'; button.className = 'explorer-row';
|
|
157
|
+
if (entityId) button.dataset.entityId = entityId;
|
|
158
|
+
const text = document.createElement('span'); text.className = 'row-label'; text.textContent = label;
|
|
159
|
+
button.append(text);
|
|
160
|
+
if (count != null) { const number = document.createElement('span'); number.className = 'explorer-count'; number.textContent = String(count); button.append(number); }
|
|
161
|
+
if (entityId) button.addEventListener('click', () => inspect(entityId));
|
|
162
|
+
return button;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function renderTreeNodes(host, nodes, depth = 0) {
|
|
166
|
+
for (const node of nodes) {
|
|
167
|
+
if (node.kind === 'element') { const item = row(node.label, null, node.entityId); item.style.setProperty('--tree-depth', String(depth)); item.setAttribute('role', 'treeitem'); host.append(item); continue; }
|
|
168
|
+
const branch = document.createElement('div'); branch.className = 'revit-tree-branch'; branch.setAttribute('role', 'treeitem');
|
|
169
|
+
const trigger = row(node.label, node.children.length); trigger.classList.add('revit-tree-trigger'); trigger.style.setProperty('--tree-depth', String(depth));
|
|
170
|
+
trigger.setAttribute('aria-expanded', 'false');
|
|
171
|
+
if (node.groupedByName) { trigger.dataset.tip = 'Grouped by provider-supplied name; this is not a source relationship.'; }
|
|
172
|
+
const children = document.createElement('div'); children.className = 'revit-tree-children'; children.setAttribute('role', 'group'); children.hidden = true;
|
|
173
|
+
trigger.addEventListener('click', () => { const open = trigger.getAttribute('aria-expanded') !== 'true'; trigger.setAttribute('aria-expanded', String(open)); children.hidden = !open; });
|
|
174
|
+
renderTreeNodes(children, node.children, depth + 1); branch.append(trigger, children); host.append(branch);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function renderClassification(host, values = entities, relationValues = [], followedId = undefined) {
|
|
179
|
+
host.replaceChildren(); host.setAttribute('role', 'tree'); host.setAttribute('aria-label', 'Browse by classification');
|
|
180
|
+
const label = document.createElement('div'); label.className = 'revit-explorer-label'; label.textContent = 'Browse by classification'; host.append(label);
|
|
181
|
+
const visibleValues = values.slice(0, MODEL_EXPLORER_ENTITY_CAP);
|
|
182
|
+
const requestedFollowedId = followedId === undefined ? (selectedIds.length === 1 ? selectedIds[0] : null) : followedId;
|
|
183
|
+
const followed = requestedFollowedId ? values.find((entity) => entity.id === requestedFollowedId) : null;
|
|
184
|
+
if (followed && !visibleValues.some((entity) => entity.id === followed.id)) visibleValues.push(followed);
|
|
185
|
+
const nodes = buildRevitClassificationTree(visibleValues);
|
|
186
|
+
if (nodes.length) renderTreeNodes(host, nodes); else { const empty = document.createElement('div'); empty.className = 'explorer-empty'; empty.textContent = 'No objects in this classification index.'; host.append(empty); }
|
|
187
|
+
if (values.length > MODEL_EXPLORER_ENTITY_CAP) { const note = document.createElement('div'); note.className = 'explorer-empty explorer-limit'; note.textContent = `Showing the first ${MODEL_EXPLORER_ENTITY_CAP.toLocaleString()} of ${values.length.toLocaleString()} classified objects${followed && visibleValues.length > MODEL_EXPLORER_ENTITY_CAP ? ', plus the selected object' : ''}. Use the Level, Category, or Type index to narrow the model.`; host.append(note); }
|
|
188
|
+
if (!relationValues.length) return;
|
|
189
|
+
const relationLabel = document.createElement('div'); relationLabel.className = 'revit-explorer-label'; relationLabel.textContent = 'Source relationships'; host.append(relationLabel);
|
|
190
|
+
for (const relation of relationValues.slice(0, 500)) {
|
|
191
|
+
const target = values.find((entity) => entity.id === relation.to);
|
|
192
|
+
const item = row(`${relation.kind}: ${target?.name || relation.to}`, null, target?.id || null);
|
|
193
|
+
item.dataset.tip = `Supplied relationship from ${relation.from}`; host.append(item);
|
|
194
|
+
}
|
|
195
|
+
if (relationValues.length > 500) { const note = document.createElement('div'); note.className = 'explorer-empty'; note.textContent = `Showing 500 of ${relationValues.length.toLocaleString()} supplied relationships.`; host.append(note); }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function renderEntityList(host, values) {
|
|
199
|
+
host.replaceChildren();
|
|
200
|
+
if (!values.length) { const empty = document.createElement('div'); empty.className = 'explorer-empty'; empty.textContent = 'No objects in this index.'; host.append(empty); return; }
|
|
201
|
+
const fragment = document.createDocumentFragment();
|
|
202
|
+
for (const entity of values.slice(0, 500)) fragment.append(row(entity.name || entity.typeName || entity.id, null, entity.id));
|
|
203
|
+
host.append(fragment);
|
|
204
|
+
if (values.length > 500) { const note = document.createElement('div'); note.className = 'explorer-empty'; note.textContent = `Showing 500 of ${values.length.toLocaleString()} objects.`; host.append(note); }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function renderGroupList(host, key, fallback, values = entities) {
|
|
208
|
+
host.replaceChildren(); const groups = new Map();
|
|
209
|
+
for (const entity of values) { const label = (typeof key === 'function' ? key(entity) : entity[key]) || fallback; const grouped = groups.get(label) || []; grouped.push(entity); groups.set(label, grouped); }
|
|
210
|
+
host.setAttribute('role', 'tree');
|
|
211
|
+
const ordered = [...groups.entries()].sort((a, b) => a[0].localeCompare(b[0]));
|
|
212
|
+
for (const [label, grouped] of ordered.slice(0, MODEL_EXPLORER_GROUP_CAP)) {
|
|
213
|
+
const branch = document.createElement('div'); branch.className = 'revit-tree-branch'; branch.setAttribute('role', 'treeitem');
|
|
214
|
+
const item = row(label, grouped.length); item.classList.add('revit-tree-trigger'); item.setAttribute('aria-expanded', 'false');
|
|
215
|
+
const children = document.createElement('div'); children.className = 'revit-tree-children'; children.setAttribute('role', 'group'); children.hidden = true;
|
|
216
|
+
let populated = false;
|
|
217
|
+
item.addEventListener('click', () => { const open = item.getAttribute('aria-expanded') !== 'true'; if (open && !populated) { renderEntityList(children, grouped); populated = true; } item.setAttribute('aria-expanded', String(open)); children.hidden = !open; });
|
|
218
|
+
branch.append(item, children); host.append(branch);
|
|
219
|
+
}
|
|
220
|
+
if (ordered.length > MODEL_EXPLORER_GROUP_CAP) { const note = document.createElement('div'); note.className = 'explorer-empty explorer-limit'; note.textContent = `Showing ${MODEL_EXPLORER_GROUP_CAP} of ${ordered.length.toLocaleString()} groups. Refine the model before browsing the remaining groups.`; host.append(note); }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function receipt(manifest, logicalName, legacySchema) {
|
|
224
|
+
return manifest.receipts.find((item) => item.logicalName === logicalName || item.schema === legacySchema || item.kind === logicalName);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function updateSelectionActions() {
|
|
228
|
+
const blocked = !selectedId;
|
|
229
|
+
for (const command of ['revit.fit-selection']) {
|
|
230
|
+
const control = [...document.querySelectorAll('[data-command-id]')].find((item) => item.dataset.commandId === command);
|
|
231
|
+
if (!control) continue;
|
|
232
|
+
if (command === 'revit.fit-selection') {
|
|
233
|
+
control.disabled = blocked;
|
|
234
|
+
if (blocked) control.dataset.blockedReason = 'Select a model object first.'; else delete control.dataset.blockedReason;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const SELECTION_FACETS = Object.freeze([
|
|
240
|
+
Object.freeze({ id: 'category', label: 'Categories', value: (entity) => entity.categoryName ?? entity.category ?? 'No category' }),
|
|
241
|
+
Object.freeze({ id: 'type', label: 'Types', value: (entity) => entity.typeName ?? 'No type' }),
|
|
242
|
+
Object.freeze({ id: 'family', label: 'Families or classes', value: (entity) => entity.familyName ?? entity.family ?? 'No family or class' }),
|
|
243
|
+
]);
|
|
244
|
+
|
|
245
|
+
function selectionFacetValues(facet) {
|
|
246
|
+
const spec = SELECTION_FACETS.find((item) => item.id === facet);
|
|
247
|
+
return spec ? [...new Set(entities.map(spec.value).filter(Boolean))].sort((a, b) => a.localeCompare(b)) : [];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function mountRevitSelectionFilters(tools) {
|
|
251
|
+
const host = $('modelSelectBar'); const subscribers = new Set(); let menu = null; let destroyed = false;
|
|
252
|
+
const own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
|
253
|
+
const state = () => {
|
|
254
|
+
const filters = tools.filters(); const out = {};
|
|
255
|
+
for (const facet of SELECTION_FACETS) {
|
|
256
|
+
const values = selectionFacetValues(facet.id); const accepted = filters[facet.id];
|
|
257
|
+
out[facet.id] = !own(filters, facet.id) || accepted.length >= values.length ? true : accepted.length ? 'partial' : false;
|
|
258
|
+
}
|
|
259
|
+
return out;
|
|
260
|
+
};
|
|
261
|
+
const publish = () => { const value = state(); for (const subscriber of subscribers) subscriber(value); };
|
|
262
|
+
const close = () => { menu?.remove(); menu = null; };
|
|
263
|
+
const apply = (facet, values, selected) => {
|
|
264
|
+
const next = { ...tools.filters() };
|
|
265
|
+
if (selected.size === values.length) delete next[facet]; else next[facet] = [...selected];
|
|
266
|
+
tools.setFilters(next);
|
|
267
|
+
};
|
|
268
|
+
const open = (facet) => {
|
|
269
|
+
const button = host.querySelector(`[data-cls="${facet}"]`); const spec = SELECTION_FACETS.find((item) => item.id === facet);
|
|
270
|
+
if (!button || !spec) return;
|
|
271
|
+
if (menu?.dataset.facet === facet) { close(); return; }
|
|
272
|
+
close();
|
|
273
|
+
const values = selectionFacetValues(facet); const filters = tools.filters(); const selected = new Set(own(filters, facet) ? filters[facet] : values);
|
|
274
|
+
const panel = document.createElement('section'); panel.className = 'model-selection-filter-flyout'; panel.dataset.facet = facet; panel.setAttribute('aria-label', `${spec.label} selection filter`);
|
|
275
|
+
const heading = document.createElement('div'); heading.className = 'model-filter-heading';
|
|
276
|
+
const headingLabel = document.createElement('strong'); headingLabel.textContent = spec.label;
|
|
277
|
+
const actions = document.createElement('div'); actions.className = 'model-filter-actions';
|
|
278
|
+
const all = document.createElement('button'); all.type = 'button'; all.textContent = 'All'; all.dataset.tip = `Allow every ${spec.label.toLowerCase()}`;
|
|
279
|
+
const none = document.createElement('button'); none.type = 'button'; none.textContent = 'None'; none.dataset.tip = `Block every ${spec.label.toLowerCase()}`;
|
|
280
|
+
actions.append(all, none); heading.append(headingLabel, actions);
|
|
281
|
+
const search = document.createElement('input'); search.type = 'search'; search.placeholder = `Search ${spec.label.toLowerCase()}`; search.setAttribute('aria-label', `Search ${spec.label.toLowerCase()}`);
|
|
282
|
+
const list = document.createElement('div'); list.className = 'model-filter-list';
|
|
283
|
+
const render = () => {
|
|
284
|
+
const query = search.value.trim().toLocaleLowerCase(); list.replaceChildren();
|
|
285
|
+
const visible = values.filter((value) => value.toLocaleLowerCase().includes(query));
|
|
286
|
+
for (const value of visible) {
|
|
287
|
+
const label = document.createElement('label'); label.className = 'model-filter-option';
|
|
288
|
+
const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.checked = selected.has(value);
|
|
289
|
+
const text = document.createElement('span'); text.textContent = value; label.append(checkbox, text);
|
|
290
|
+
checkbox.addEventListener('change', () => { if (checkbox.checked) selected.add(value); else selected.delete(value); apply(facet, values, selected); });
|
|
291
|
+
list.append(label);
|
|
292
|
+
}
|
|
293
|
+
if (!visible.length) { const empty = document.createElement('div'); empty.className = 'explorer-empty'; empty.textContent = values.length ? 'No matching values.' : 'No values were supplied.'; list.append(empty); }
|
|
294
|
+
};
|
|
295
|
+
all.addEventListener('click', () => { values.forEach((value) => selected.add(value)); apply(facet, values, selected); render(); });
|
|
296
|
+
none.addEventListener('click', () => { selected.clear(); apply(facet, values, selected); render(); });
|
|
297
|
+
search.addEventListener('input', render); panel.addEventListener('click', (event) => event.stopPropagation());
|
|
298
|
+
panel.append(heading, search, list); document.body.append(panel); menu = panel;
|
|
299
|
+
const rect = button.getBoundingClientRect(); panel.style.left = `${Math.max(8, Math.min(rect.left, innerWidth - panel.offsetWidth - 8))}px`; panel.style.bottom = `${Math.max(8, innerHeight - rect.top + 7)}px`;
|
|
300
|
+
render(); search.focus();
|
|
301
|
+
};
|
|
302
|
+
const outside = () => close(); document.addEventListener('click', outside);
|
|
303
|
+
const filterUnsubscribe = tools.subscribeFilters(publish);
|
|
304
|
+
return Object.freeze({
|
|
305
|
+
port: Object.freeze({ getState: state, subscribe(listener) { subscribers.add(listener); listener(state()); return () => subscribers.delete(listener); }, toggle: open }),
|
|
306
|
+
refresh() { publish(); close(); },
|
|
307
|
+
destroy() { if (destroyed) return; destroyed = true; close(); filterUnsubscribe(); subscribers.clear(); document.removeEventListener('click', outside); },
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function reflectSelectionHover(hit) {
|
|
312
|
+
const id = hit?.entity?.sourceId ?? null; viewport?.setHover?.(id);
|
|
313
|
+
const summary = $('modelHoverSummary');
|
|
314
|
+
if (!id) { summary.hidden = true; summary.textContent = ''; return; }
|
|
315
|
+
const entity = entityById.get(id); summary.textContent = entity?.name || entity?.typeName || id; summary.hidden = false;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function reflectSelectionMarquee(rect) {
|
|
319
|
+
const box = $('modelSelectionMarquee');
|
|
320
|
+
if (!rect) { box.hidden = true; box.removeAttribute('data-mode'); return; }
|
|
321
|
+
const surface = $('modelCanvas').getBoundingClientRect();
|
|
322
|
+
box.hidden = false; box.dataset.mode = rect.mode;
|
|
323
|
+
box.style.left = `${rect.left - surface.left}px`; box.style.top = `${rect.top - surface.top}px`; box.style.width = `${rect.right - rect.left}px`; box.style.height = `${rect.bottom - rect.top}px`;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function closeSpatialDialog() { spatialDialog?.remove(); spatialDialog = null; }
|
|
327
|
+
|
|
328
|
+
function spatialFrameFromStored(frame) {
|
|
329
|
+
return { id: frame.frameId, kind: frame.frameId === 'object' ? 'object' : frame.frameId === 'work-plane' ? 'work-plane' : 'local',
|
|
330
|
+
label: frame.frameId === 'work-plane' ? 'Working plane' : frame.frameId === 'object' ? 'Object' : 'Local',
|
|
331
|
+
origin: frame.originMm, xAxis: frame.xAxis, yAxis: frame.yAxis, zAxis: frame.zAxis };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function spatialInitialFromStored(state) {
|
|
335
|
+
if (!state) return null;
|
|
336
|
+
return { schema: 'floless.model-spatial-state/v1', activeFrameId: 'global',
|
|
337
|
+
frames: (state.coordinateFrames || []).map(spatialFrameFromStored), workPlane: null,
|
|
338
|
+
savedViews: (state.namedViews || []).map((view) => ({ id: view.id, name: view.name, frameId: view.frameId || 'global', state: view.state })),
|
|
339
|
+
clips: state.sections?.clips ?? [], workArea: state.sections?.workArea ?? null, visibility: { hidden: [], isolated: [] } };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function editorStatePayload() {
|
|
343
|
+
const value = spatialTools.serialize();
|
|
344
|
+
return { ...(editorStateLoaded || {}), schemaVersion: 'floless.model-editor-state/v1', frameSchemaVersion: 'floless.model-frame/v1',
|
|
345
|
+
modelId: editorStateBinding.modelId, baseRevisionId: editorStateBinding.baseRevisionId, sourceDigest: editorStateBinding.sourceDigest,
|
|
346
|
+
annotations: editorStateLoaded?.annotations ?? [],
|
|
347
|
+
namedViews: value.savedViews.map((view) => ({ id: view.id, name: view.name, frameId: view.frameId === 'global' ? null : view.frameId,
|
|
348
|
+
state: view.state ?? { camera: view.camera ?? null, displayMode: view.displayMode ?? 'solid' } })),
|
|
349
|
+
coordinateFrames: value.frames.filter((frame) => frame.id !== 'global').map((frame) => ({ schemaVersion: 'floless.model-frame/v1', frameId: frame.id,
|
|
350
|
+
originMm: frame.origin, xAxis: frame.xAxis, yAxis: frame.yAxis, zAxis: frame.zAxis })),
|
|
351
|
+
sections: { clips: value.clips, workArea: value.workArea } };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function editorStateUrl(binding) {
|
|
355
|
+
return `/api/editor/model/${encodeURIComponent(binding.projectUuid)}/${encodeURIComponent(binding.baseRevisionId)}/editor-state`;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function readEditorStateRecovery(binding, etag) {
|
|
359
|
+
return editorStateRecovery.read(binding, etag);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function retainEditorStateRecovery() {
|
|
363
|
+
if (!editorStateBinding || !editorStateDirtyPayload || editorStateSavedGeneration >= editorStateDirtyGeneration) return;
|
|
364
|
+
const owned = { namedViews: editorStateDirtyPayload.namedViews, coordinateFrames: editorStateDirtyPayload.coordinateFrames, sections: editorStateDirtyPayload.sections };
|
|
365
|
+
editorStateRecovery.retain(editorStateBinding, editorStateEtag, owned);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function clearEditorStateRecovery(binding) {
|
|
369
|
+
editorStateRecovery.clear(binding);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function payloadOnly(state) {
|
|
373
|
+
if (!state) return null;
|
|
374
|
+
const { projectUuid, stateRevision, etag, createdAt, updatedAt, ...payload } = state;
|
|
375
|
+
return payload;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async function putEditorState({ binding, token, payload, etag }) {
|
|
379
|
+
const request = async (body, currentEtag) => fetch(editorStateUrl(binding), { method: 'PUT', credentials: 'same-origin',
|
|
380
|
+
headers: { 'content-type': 'application/json', ...(currentEtag ? { 'if-match': currentEtag } : { 'if-none-match': '*' }) }, body: JSON.stringify(body) });
|
|
381
|
+
let sentPayload = payload; let response = await request(sentPayload, etag);
|
|
382
|
+
if (response.status === 412) {
|
|
383
|
+
const fresh = await fetch(editorStateUrl(binding), { credentials: 'same-origin' });
|
|
384
|
+
if (!fresh.ok) throw new Error(`Editor state conflict reload failed (${fresh.status})`);
|
|
385
|
+
const freshValue = await fresh.json(); const freshPayload = payloadOnly(freshValue.state) || {};
|
|
386
|
+
sentPayload = { ...freshPayload, namedViews: payload.namedViews, coordinateFrames: payload.coordinateFrames, sections: payload.sections };
|
|
387
|
+
response = await request(sentPayload, fresh.headers.get('etag') || freshValue.state?.etag || null);
|
|
388
|
+
}
|
|
389
|
+
const value = await response.json().catch(() => ({}));
|
|
390
|
+
if (!response.ok || value.ok === false) throw new Error(value.message || value.error || `Editor state save failed (${response.status})`);
|
|
391
|
+
if (token !== editorStateBindingToken) return;
|
|
392
|
+
editorStateEtag = response.headers.get('etag') || value.state?.etag || editorStateEtag;
|
|
393
|
+
editorStateLoaded = payloadOnly(value.state) || sentPayload;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function drainEditorStateSaves() {
|
|
397
|
+
const token = editorStateBindingToken;
|
|
398
|
+
editorStateSaveQueue = editorStateSaveQueue.catch(() => {}).then(async () => {
|
|
399
|
+
while (token === editorStateBindingToken && editorStateSavedGeneration < editorStateDirtyGeneration && editorStateBinding && editorStateDirtyPayload) {
|
|
400
|
+
const generation = editorStateDirtyGeneration; const payload = editorStateDirtyPayload;
|
|
401
|
+
await putEditorState({ binding: { ...editorStateBinding }, token, payload, etag: editorStateEtag });
|
|
402
|
+
if (token === editorStateBindingToken) {
|
|
403
|
+
editorStateSavedGeneration = generation;
|
|
404
|
+
if (editorStateSavedGeneration >= editorStateDirtyGeneration) clearEditorStateRecovery(editorStateBinding);
|
|
405
|
+
else retainEditorStateRecovery();
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
return editorStateSaveQueue;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async function flushEditorStateSave() {
|
|
413
|
+
clearTimeout(editorStateSaveTimer); editorStateSaveTimer = null;
|
|
414
|
+
if (editorStateDirtyGeneration > editorStateSavedGeneration) await Promise.race([
|
|
415
|
+
drainEditorStateSaves(),
|
|
416
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('Saving this model view timed out. Try again before switching models.')), 8_000)),
|
|
417
|
+
]);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function scheduleEditorStateSave(reason) {
|
|
421
|
+
if (reason === 'replay' || !editorStateBinding) return;
|
|
422
|
+
editorStateDirtyPayload = editorStatePayload(); editorStateDirtyGeneration += 1;
|
|
423
|
+
retainEditorStateRecovery();
|
|
424
|
+
clearTimeout(editorStateSaveTimer);
|
|
425
|
+
editorStateSaveTimer = setTimeout(() => { editorStateSaveTimer = null; drainEditorStateSaves().catch((error) => toast(error.message || 'Could not save model view state.')); }, 350);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async function activateSpatialForRevision(state, handle) {
|
|
429
|
+
await flushEditorStateSave();
|
|
430
|
+
editorStateBindingToken += 1; clearTimeout(editorStateSaveTimer); editorStateSaveTimer = null; editorStateEtag = null;
|
|
431
|
+
editorStateLoaded = null; editorStateDirtyPayload = null; editorStateDirtyGeneration = 0; editorStateSavedGeneration = 0;
|
|
432
|
+
clipList?.destroy(); clipList = null; releaseClipEditor?.(); releaseClipEditor = null; releaseClipViewport?.(); releaseClipViewport = null; clipSession?.dispose(); clipSession = null;
|
|
433
|
+
spatialPanel?.destroy(); spatialPanel = null; releaseSpatialViewport?.(); releaseSpatialViewport = null; spatialTools?.dispose(); spatialTools = null;
|
|
434
|
+
const primary = projectContract?.models?.find((model) => model.modelId === projectContract.primaryModelId);
|
|
435
|
+
if (!primary || typeof projectContract.primaryModelId !== 'string') throw new Error('The model contract does not identify its primary model.');
|
|
436
|
+
editorStateBinding = { projectUuid: state.projectUuid, modelId: projectContract.primaryModelId, baseRevisionId: handle.revisionId, sourceDigest: handle.sourceSha256 };
|
|
437
|
+
const url = editorStateUrl(editorStateBinding);
|
|
438
|
+
const response = await fetch(url, { credentials: 'same-origin' }); let stored = null;
|
|
439
|
+
if (response.ok) { const value = await response.json(); stored = value.state; editorStateLoaded = payloadOnly(stored); editorStateEtag = response.headers.get('etag') || stored?.etag || null; }
|
|
440
|
+
else if (response.status !== 404) { const value = await response.json().catch(() => ({})); throw new Error(value.message || value.error || `Editor state read failed (${response.status})`); }
|
|
441
|
+
const recovered = readEditorStateRecovery(editorStateBinding, editorStateEtag);
|
|
442
|
+
if (recovered) { stored = { ...(stored || {}), ...recovered, annotations: stored?.annotations ?? recovered.annotations ?? [] }; editorStateLoaded = payloadOnly(stored); }
|
|
443
|
+
spatialTools = createModelSpatialTools({ initial: spatialInitialFromStored(stored), onChange: (_value, reason) => scheduleEditorStateSave(reason) });
|
|
444
|
+
releaseSpatialViewport = viewport.bindSpatialTools(spatialTools);
|
|
445
|
+
clipSession = createModelClipSession({
|
|
446
|
+
tools: spatialTools,
|
|
447
|
+
placementOwnsKeyboard: () => !!facade?.clipMode?.(),
|
|
448
|
+
dragOwnsKeyboard: () => !!viewport?.clipDragActive?.(),
|
|
449
|
+
onArmPlane: () => { facade?.dispatch('model.clip.arm', 'plane'); },
|
|
450
|
+
onArmBox: () => { facade?.dispatch('model.clip.arm', 'box'); },
|
|
451
|
+
});
|
|
452
|
+
releaseClipViewport = viewport.bindClipSession(clipSession);
|
|
453
|
+
clipList = mountModelClipList({ session: clipSession, host: revitClipListHost, onError: toast });
|
|
454
|
+
releaseClipEditor = clipSession.subscribe((value) => {
|
|
455
|
+
if (!value.selectedIds.length || !selectedId) return;
|
|
456
|
+
inspect(null);
|
|
457
|
+
});
|
|
458
|
+
spatialTools.subscribe((value) => { $('modelFrameStatus').textContent = spatialTools.activeFrame().label; window.__revitInstructorState = { ...(window.__revitInstructorState || {}), activeFrame: value.activeFrameId }; reflectToolbarState(); });
|
|
459
|
+
spatialPanel = mountModelSpatialPanel({ tools: spatialTools, trigger: $('modelFrameStatus'), onBeforeOpen: closeSpatialDialog,
|
|
460
|
+
onError: (error) => toast(error.message || 'That spatial action is unavailable.') });
|
|
461
|
+
if (recovered) { editorStateDirtyPayload = editorStatePayload(); editorStateDirtyGeneration = 1; retainEditorStateRecovery(); editorStateSaveTimer = setTimeout(() => drainEditorStateSaves().catch((error) => toast(error.message || 'Could not restore model view state.')), 0); }
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function positionDialog(panel, anchor) {
|
|
465
|
+
document.body.append(panel); spatialDialog = panel; const rect = anchor.getBoundingClientRect();
|
|
466
|
+
panel.style.left = `${Math.max(8, Math.min(rect.left, innerWidth - panel.offsetWidth - 8))}px`; panel.style.top = `${Math.min(innerHeight - panel.offsetHeight - 8, rect.bottom + 7)}px`;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function openSavedViews() {
|
|
470
|
+
const anchor = $('revitSavedViews'); if (!anchor || !spatialTools) return;
|
|
471
|
+
spatialPanel?.close({ restoreFocus: false }); closeSpatialDialog(); const panel = document.createElement('section'); panel.className = 'model-spatial-dialog'; panel.setAttribute('aria-label', 'Saved camera views');
|
|
472
|
+
const header = document.createElement('div'); header.className = 'model-spatial-dialog-header'; const headingLabel = document.createElement('strong'); headingLabel.textContent = 'Saved views';
|
|
473
|
+
const close = document.createElement('button'); close.type = 'button'; close.textContent = '×'; close.dataset.tip = 'Close saved views'; close.setAttribute('aria-label', 'Close saved views'); close.addEventListener('click', closeSpatialDialog); header.append(headingLabel, close);
|
|
474
|
+
const input = document.createElement('input'); input.type = 'text'; input.maxLength = 120; input.placeholder = 'View name'; input.setAttribute('aria-label', 'Saved view name');
|
|
475
|
+
const save = document.createElement('button'); save.type = 'button'; save.textContent = 'Save current view';
|
|
476
|
+
const list = document.createElement('div'); list.className = 'model-saved-view-list';
|
|
477
|
+
const paint = () => {
|
|
478
|
+
list.replaceChildren(); const views = spatialTools.state().savedViews;
|
|
479
|
+
for (const view of views) {
|
|
480
|
+
const row = document.createElement('div'); row.className = 'model-saved-view-row';
|
|
481
|
+
const restore = document.createElement('button'); restore.type = 'button'; restore.textContent = view.name; restore.dataset.tip = `Restore ${view.name}`;
|
|
482
|
+
restore.addEventListener('click', () => {
|
|
483
|
+
const saved = view.state || {}; if (saved.camera) viewport.applyCamera(saved.camera); if (saved.displayMode) facade.dispatch('model.display-mode.set', saved.displayMode);
|
|
484
|
+
if (typeof saved.ghostUnselected === 'boolean' && facade.ghostUnselected() !== saved.ghostUnselected) facade.dispatch('model.ghost-unselected');
|
|
485
|
+
spatialTools.replaceSections({ clips: Array.isArray(saved.clips) ? saved.clips : [], workArea: saved.workArea ?? null });
|
|
486
|
+
spatialTools.clearWorkPlane();
|
|
487
|
+
if (saved.workPlane?.source === 'principal') { spatialTools.setPrincipalWorkPlane({ plane: saved.workPlane.principal, offsetMm: saved.workPlane.offsetMm }); if (saved.workPlane.visible === false) spatialTools.setWorkPlaneVisible(false); }
|
|
488
|
+
if (view.frameId && spatialTools.state().frames.some((frame) => frame.id === view.frameId)) spatialTools.activateFrame(view.frameId);
|
|
489
|
+
closeSpatialDialog();
|
|
490
|
+
});
|
|
491
|
+
const remove = document.createElement('button'); remove.type = 'button'; remove.textContent = 'Delete'; remove.dataset.tip = `Delete ${view.name}`; remove.addEventListener('click', () => { spatialTools.deleteView(view.id); paint(); });
|
|
492
|
+
row.append(restore, remove); list.append(row);
|
|
493
|
+
}
|
|
494
|
+
if (!views.length) { const empty = document.createElement('div'); empty.className = 'model-dialog-note'; empty.textContent = 'No saved views for this model revision yet.'; list.append(empty); }
|
|
495
|
+
};
|
|
496
|
+
save.addEventListener('click', () => { const name = input.value.trim(); if (!name) { input.focus(); return; } const spatial = spatialTools.state(); spatialTools.saveView({ id: `view-${Date.now().toString(36)}`, name, frameId: spatialTools.activeFrame().id,
|
|
497
|
+
state: { camera: viewport.cameraState(), displayMode: viewport.displayMode(), ghostUnselected: facade.ghostUnselected(), clips: spatial.clips, workArea: spatial.workArea, workPlane: spatial.workPlane } }); input.value = ''; paint(); });
|
|
498
|
+
panel.append(header, input, save, list); positionDialog(panel, anchor); paint(); input.focus();
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function openPlaneOffset(plane, anchor) {
|
|
502
|
+
spatialPanel?.close({ restoreFocus: false }); closeSpatialDialog(); const panel = document.createElement('section'); panel.className = 'model-spatial-dialog'; panel.setAttribute('aria-label', `${plane.toUpperCase()} working plane offset`);
|
|
503
|
+
const headingLabel = document.createElement('strong'); headingLabel.textContent = `${plane.toUpperCase()} working plane`;
|
|
504
|
+
const note = document.createElement('div'); note.className = 'model-dialog-note'; note.textContent = 'Offset in millimetres along the plane normal.';
|
|
505
|
+
const input = document.createElement('input'); input.type = 'number'; input.step = '1'; input.value = '0'; input.setAttribute('aria-label', 'Working plane offset in millimetres');
|
|
506
|
+
const actions = document.createElement('div'); actions.className = 'model-spatial-dialog-actions'; const cancel = document.createElement('button'); cancel.type = 'button'; cancel.textContent = 'Cancel'; cancel.addEventListener('click', closeSpatialDialog);
|
|
507
|
+
const apply = document.createElement('button'); apply.type = 'button'; apply.textContent = 'Set plane'; apply.addEventListener('click', () => { const offsetMm = Number(input.value); if (!Number.isFinite(offsetMm)) return; facade.dispatch('model.work-plane.principal', { plane, offsetMm }); closeSpatialDialog(); });
|
|
508
|
+
actions.append(cancel, apply); panel.append(headingLabel, note, input, actions); positionDialog(panel, anchor); input.focus(); input.select();
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function handleSpatialAction(action, control) {
|
|
512
|
+
if (action === 'clip-plane') { facade.dispatch('model.clip.arm', 'plane'); toast('Click a model face to place the clip plane.'); }
|
|
513
|
+
else if (action === 'clip-box') { facade.dispatch('model.clip.arm', 'box'); toast('Pick two footprint corners, then set the clip height.'); }
|
|
514
|
+
else if (action === 'clip-clear') { facade.dispatch('model.clip.clear'); toast('All clips removed.'); }
|
|
515
|
+
else if (action.startsWith('plane-') && ['xy', 'xz', 'yz'].includes(action.slice(6))) openPlaneOffset(action.slice(6), control);
|
|
516
|
+
else if (action === 'plane-toggle') { const plane = spatialTools.state().workPlane; if (!plane) facade.dispatch('model.work-plane.principal', { plane: 'xy', offsetMm: 0 }); else facade.dispatch('model.work-plane.show', !plane.visible); }
|
|
517
|
+
else if (action === 'frame-global') facade.dispatch('model.work-plane.reset');
|
|
518
|
+
else if (action === 'area-model') facade.dispatch('model.work-area.set', 'all');
|
|
519
|
+
else if (action === 'area-selection') facade.dispatch('model.work-area.set', 'selection');
|
|
520
|
+
else if (action === 'area-whole') facade.dispatch('model.work-area.whole');
|
|
521
|
+
else if (action === 'area-toggle') facade.dispatch('model.work-area.toggle');
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function reflectToolbarState() {
|
|
525
|
+
if (!facade) return;
|
|
526
|
+
const projection = facade.projection() === 'ortho' ? 'ortho' : 'persp';
|
|
527
|
+
const projectionButton = $('revitProjection');
|
|
528
|
+
if (projectionButton) {
|
|
529
|
+
projectionButton.dataset.proj = projection;
|
|
530
|
+
projectionButton.dataset.tip = projection === 'ortho' ? 'Orthographic true scale — click for perspective' : 'Perspective — click for orthographic true scale';
|
|
531
|
+
const label = projectionButton.querySelector('.rlbl'); if (label) label.textContent = projection === 'ortho' ? 'Orthographic' : 'Perspective';
|
|
532
|
+
}
|
|
533
|
+
const mode = facade.displayMode() || 'solid'; const displayButton = $('revitDisplay');
|
|
534
|
+
if (displayButton) {
|
|
535
|
+
displayButton.dataset.mode = mode;
|
|
536
|
+
const label = displayButton.querySelector('.rlbl'); if (label) label.textContent = mode === 'wire' ? 'Wireframe' : mode === 'xray' ? 'See-through (X-ray)' : mode === 'realistic' ? 'Realistic' : 'Solid';
|
|
537
|
+
for (const item of $('revitDisplayMenu')?.querySelectorAll('[data-mode]') || []) item.setAttribute('aria-checked', String(item.dataset.mode === mode));
|
|
538
|
+
// Realistic can ask for shading the browser could not generate. The radio keeps showing what the
|
|
539
|
+
// user CHOSE; the tip says what they are actually looking at, so the difference is never silent.
|
|
540
|
+
const realistic = viewport.realisticState?.();
|
|
541
|
+
if (realistic?.requested && !realistic.live) {
|
|
542
|
+
displayButton.dataset.tip = 'Realistic is unavailable on this computer, so the model is shown with Solid shading.';
|
|
543
|
+
if (!realisticFallbackAnnounced) { realisticFallbackAnnounced = true; toast('Realistic shading is unavailable on this computer. Showing Solid shading instead.'); }
|
|
544
|
+
} else {
|
|
545
|
+
displayButton.dataset.tip = 'Display mode — solid, wireframe, see-through, or realistic';
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
const clipButton = $('revitClip'); const clips = spatialTools?.state?.().clips ?? [];
|
|
549
|
+
if (clipButton) {
|
|
550
|
+
const enabledCount = clips.filter((clip) => clip.enabled !== false).length;
|
|
551
|
+
if (enabledCount) clipButton.dataset.stateCount = String(enabledCount); else delete clipButton.dataset.stateCount;
|
|
552
|
+
const armed = !!facade.clipMode?.();
|
|
553
|
+
clipButton.classList.toggle('on', armed);
|
|
554
|
+
clipButton.setAttribute('aria-pressed', String(armed));
|
|
555
|
+
clipButton.dataset.tip = armed ? 'Clipping is armed — click to cancel' : 'Clip planes and boxes — section your model to see inside';
|
|
556
|
+
const label = clipButton.querySelector('.rlbl'); if (label) label.textContent = armed ? 'Cancel clip' : 'Clip';
|
|
557
|
+
}
|
|
558
|
+
const clearClips = $('revitClipMenu')?.querySelector('[data-spatial="clip-clear"]');
|
|
559
|
+
if (clearClips) clearClips.disabled = clips.length === 0;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function wireToolbar() {
|
|
563
|
+
const bar = $('m3dBar'); bar.innerHTML = renderToolbarMarkup(revitRenderPlan()); const chrome = mountToolbarChrome({ toolbar: bar, port: facade });
|
|
564
|
+
const lightingChrome = mountModelLightingPanel({ trigger: $('revitLighting'), anchor: $('revitDisplay'), target: facade, profile: 'revit' });
|
|
565
|
+
const clipButton = $('revitClip');
|
|
566
|
+
const cancelArmedClip = (event) => {
|
|
567
|
+
if (!facade.clipMode?.()) return;
|
|
568
|
+
event.preventDefault(); event.stopImmediatePropagation(); facade.dispatch('model.clip.cancel'); reflectToolbarState();
|
|
569
|
+
};
|
|
570
|
+
clipButton?.addEventListener('click', cancelArmedClip, true);
|
|
571
|
+
bar.addEventListener('click', (event) => {
|
|
572
|
+
const control = event.target.closest('[data-command-id]'); if (!control || control.disabled) return;
|
|
573
|
+
const projection = control.dataset.proj, mode = control.dataset.mode;
|
|
574
|
+
try {
|
|
575
|
+
if (projection && control.dataset.modelControl === 'model.projection') facade.dispatch('model.projection.set', facade.projection() === 'ortho' ? 'persp' : 'ortho');
|
|
576
|
+
else if (mode && control.closest('.m3dmenu')) facade.dispatch('model.display-mode.set', mode);
|
|
577
|
+
else if (control.id === 'revitFit') facade.dispatch('model.fit');
|
|
578
|
+
else if (control.id === 'revitFitSelection') facade.dispatch('model.fit-selection');
|
|
579
|
+
else if (control.id === 'revitSavedViews') facade.dispatch('model.saved-views');
|
|
580
|
+
else if (control.dataset.spatial) handleSpatialAction(control.dataset.spatial, control);
|
|
581
|
+
for (const radio of control.parentElement?.querySelectorAll('[role="menuitemradio"]') || []) radio.setAttribute('aria-checked', String(radio === control));
|
|
582
|
+
reflectToolbarState();
|
|
583
|
+
window.__instructor?.notifyChanged();
|
|
584
|
+
} catch (error) { toast(error.message || 'That view action is unavailable.'); }
|
|
585
|
+
});
|
|
586
|
+
updateSelectionActions();
|
|
587
|
+
reflectToolbarState();
|
|
588
|
+
const release = facade.subscribe(() => { try { reflectToolbarState(); } catch (_) {} });
|
|
589
|
+
return { destroy() { clipButton?.removeEventListener('click', cancelArmedClip, true); release?.(); lightingChrome.destroy(); chrome.destroy(); } };
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
async function loadRevision(state, authority) {
|
|
593
|
+
revisionLoadController?.abort();
|
|
594
|
+
const controller = new AbortController(); revisionLoadController = controller;
|
|
595
|
+
const token = ++revisionLoadToken;
|
|
596
|
+
const handle = state[authority]; if (!handle) throw new Error(`No ${authority} model revision is available.`);
|
|
597
|
+
$('loadingState').style.display = 'flex';
|
|
598
|
+
try {
|
|
599
|
+
const base = `/api/editor/model/${encodeURIComponent(state.projectUuid)}/${encodeURIComponent(handle.revisionId)}`;
|
|
600
|
+
const manifest = (await json(`${base}/manifest`)).manifest;
|
|
601
|
+
if (token !== revisionLoadToken) return false;
|
|
602
|
+
const entityReceipt = receipt(manifest, 'entities-000000', 'aware-package:entities-000000');
|
|
603
|
+
const propertyReceipt = receipt(manifest, 'properties-000000', 'aware-package:properties-000000');
|
|
604
|
+
const relationshipReceipt = receipt(manifest, 'relationships-000000', 'aware-package:relationships-000000');
|
|
605
|
+
const tileId = manifest.tiles.ids[0];
|
|
606
|
+
const tileReceipt = manifest.receipts.find((item) => item.kind === 'tile' && item.digest === tileId);
|
|
607
|
+
if (!entityReceipt || !propertyReceipt || !relationshipReceipt || !tileId || !tileReceipt) throw new Error('The verified snapshot package is incomplete.');
|
|
608
|
+
preflightModelJsonReceipt(entityReceipt); preflightModelJsonReceipt(propertyReceipt); preflightModelJsonReceipt(relationshipReceipt);
|
|
609
|
+
const aggregateBytes = entityReceipt.bytes + propertyReceipt.bytes + relationshipReceipt.bytes + tileReceipt.bytes;
|
|
610
|
+
if (!Number.isSafeInteger(aggregateBytes) || aggregateBytes > MODEL_VIEWER_MAX_AGGREGATE_BYTES) throw new Error('This model exceeds the bounded viewer package limit.');
|
|
611
|
+
// Read large artifacts sequentially so their authenticated byte buffers are released before the
|
|
612
|
+
// next download starts. The parsed rows remain, but four simultaneous 100+ MiB buffers do not.
|
|
613
|
+
const entityArtifact = await readModelJsonArtifact({ url: `${base}/entities/${entityReceipt.digest}`, receipt: entityReceipt, rowKey: 'entities', expectedItems: manifest.entities.count, signal: controller.signal });
|
|
614
|
+
const propertyArtifact = await readModelJsonArtifact({ url: `${base}/entities/${propertyReceipt.digest}`, receipt: propertyReceipt, rowKey: 'properties', signal: controller.signal });
|
|
615
|
+
const relationshipArtifact = await readModelJsonArtifact({ url: `${base}/entities/${relationshipReceipt.digest}`, receipt: relationshipReceipt, rowKey: 'relationships', signal: controller.signal });
|
|
616
|
+
const tile = await readModelBinaryArtifact({ url: `${base}/tiles/${tileId}`, receipt: tileReceipt, maxBytes: MODEL_VIEWER_MAX_TILE_BYTES, signal: controller.signal });
|
|
617
|
+
if (token !== revisionLoadToken) return false;
|
|
618
|
+
const nextEntities = entityArtifact.rows; const nextProperties = propertyArtifact.rows; const nextRelationships = relationshipArtifact.rows;
|
|
619
|
+
assertModelViewerRowBudget(nextEntities, nextProperties, nextRelationships);
|
|
620
|
+
const nextEntityById = new Map(nextEntities.map((entity) => [entity.id, entity]));
|
|
621
|
+
const nextPropertyByEntity = new Map();
|
|
622
|
+
for (const item of nextProperties) { const values = nextPropertyByEntity.get(item.entityId) || []; values.push(item); nextPropertyByEntity.set(item.entityId, values); }
|
|
623
|
+
const owners = new Map(); for (const entity of nextEntities) for (const geometry of entity.geometry || []) if (geometry.nodeName) owners.set(geometry.nodeName, entity.id);
|
|
624
|
+
const staged = {
|
|
625
|
+
model: document.createElement('div'), levels: document.createElement('div'),
|
|
626
|
+
categories: document.createElement('div'), types: document.createElement('div'),
|
|
627
|
+
};
|
|
628
|
+
renderClassification(staged.model, nextEntities, nextRelationships, null);
|
|
629
|
+
renderGroupList(staged.levels, 'levelName', 'No level', nextEntities);
|
|
630
|
+
renderGroupList(staged.categories, (entity) => entity.categoryName ?? entity.category, 'No category', nextEntities);
|
|
631
|
+
renderGroupList(staged.types, 'typeName', 'No type', nextEntities);
|
|
632
|
+
if (token !== revisionLoadToken) return false;
|
|
633
|
+
await viewport.load(tile, owners, { schema: manifest.schema, geometryToRenderMatrix: manifest.geometryToRenderMatrix });
|
|
634
|
+
if (token !== revisionLoadToken) return false;
|
|
635
|
+
entities = nextEntities; properties = nextProperties; relationships = nextRelationships; entityById = nextEntityById; propertyByEntity = nextPropertyByEntity;
|
|
636
|
+
selectionTools?.generationChanged();
|
|
637
|
+
selectionFilterChrome?.refresh();
|
|
638
|
+
$('revitExplorerClassification').replaceChildren(...staged.model.childNodes);
|
|
639
|
+
classificationFollowedId = null;
|
|
640
|
+
$('revitExplorerLevels').replaceChildren(...staged.levels.childNodes);
|
|
641
|
+
$('revitExplorerCategories').replaceChildren(...staged.categories.childNodes);
|
|
642
|
+
$('revitExplorerTypes').replaceChildren(...staged.types.childNodes);
|
|
643
|
+
inspect(null, true, false, 'tree');
|
|
644
|
+
modelPanelBridge?.ready(handle.revisionId);
|
|
645
|
+
$('loadingState').style.display = 'none';
|
|
646
|
+
return true;
|
|
647
|
+
} catch (error) {
|
|
648
|
+
if (token !== revisionLoadToken) return false;
|
|
649
|
+
if (viewport?.isReady?.()) $('loadingState').style.display = 'none';
|
|
650
|
+
throw error;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// The main window's left Model section shows the clip list as a PANEL tab (web/model-panel-bridge.js).
|
|
655
|
+
const REVIT_PANEL_TABS = Object.freeze([Object.freeze({ key: 'clips', label: 'Clips', tip: 'Clips — the planes and boxes cutting the model: select, rename, switch on or off, remove' })]);
|
|
656
|
+
// Held, not looked up: once shown, the Clips tab lives in the main window's frame, where $() cannot find it.
|
|
657
|
+
const revitClipListHost = $('revitClipListHost');
|
|
658
|
+
const revitPanelHost = createPanelHost({ win: window, root: $('revitPanelTabs'), bodies: { clips: revitClipListHost }, install: installTooltips });
|
|
659
|
+
|
|
660
|
+
function mountPanels() {
|
|
661
|
+
inspector = mountInspectorShell({ panel: $('inspectorBody'), doc: document, win: window, placement: 'docked', readOnly: true, emptyMessage: 'Select an object to inspect its imported Revit properties.' });
|
|
662
|
+
mountSidePanel({ panel: $('inspectorPanel'), resizer: $('inspectorResizer'), toggle: $('inspectorToggle'), root: $('editorRoot'), doc: document, win: window, widthKey: 'floless:revit:inspector-width', collapsedKey: 'floless:revit:inspector-collapsed' });
|
|
663
|
+
modelPanelBridge = createModelPanelBridge({
|
|
664
|
+
win: window, origin: location.origin, snapshot: modelPanelSnapshot, selectedId: () => selectedId, selectedIds: () => [...selectedIds],
|
|
665
|
+
// ids: what a list click selects (Ctrl/Shift can make it several, or none). The Inspector shows the row clicked
|
|
666
|
+
// when it stays selected, else the last one; the viewport shows them all.
|
|
667
|
+
select: (id, ids = [id]) => {
|
|
668
|
+
if (!ids.every((each) => entityById.has(each))) return false;
|
|
669
|
+
selectedIds = [...ids]; if (ids.length) clipSession?.clearSelection?.();
|
|
670
|
+
selectionOriginGuard.run(() => viewport.setSelection({ ids }));
|
|
671
|
+
return inspect(ids.includes(id) ? id : (ids.at(-1) ?? null), false, false, 'tree');
|
|
672
|
+
},
|
|
673
|
+
expand: (groupId) => expandModelPanelGroup(revitExplorerTabs, $, groupId),
|
|
674
|
+
panel: (tab) => tab === null || revitPanelHost.show(tab),
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
function mountSharedModelTools() {
|
|
679
|
+
const measureListeners = new Set(); const snapListeners = new Set();
|
|
680
|
+
const cleanup = []; let destroyed = false;
|
|
681
|
+
const own = (action) => { let live = true; const once = () => { if (live) { live = false; action(); } }; cleanup.push(once); return once; };
|
|
682
|
+
const rollback = () => { while (cleanup.length) { try { cleanup.pop()(); } catch (_) {} } };
|
|
683
|
+
try {
|
|
684
|
+
own(() => { measureListeners.clear(); snapListeners.clear(); });
|
|
685
|
+
const orientation = mountModelOrientationOverlay({
|
|
686
|
+
cubeHost: $('modelViewCube'), triadHost: $('modelWorldAxes'), orientation: viewport.orientation,
|
|
687
|
+
escapeTarget: $('modelCanvas'),
|
|
688
|
+
});
|
|
689
|
+
own(() => orientation.destroy());
|
|
690
|
+
const nextMeasureTool = mountModelMeasureTool({
|
|
691
|
+
surface: $('modelCanvas'), host: $('modelDimensionOverlay'), viewport,
|
|
692
|
+
snapIndex: () => viewport.snapIndex(),
|
|
693
|
+
onState(state) { for (const listener of measureListeners) listener(state); for (const listener of snapListeners) listener(state.snapModes); },
|
|
694
|
+
});
|
|
695
|
+
const destroyMeasure = own(() => nextMeasureTool.destroy());
|
|
696
|
+
const nextCadTools = createModelCadToolController({ provider: {
|
|
697
|
+
measureState: () => nextMeasureTool.state(), setMeasureArmed: (on) => nextMeasureTool.setArmed(on), clearMeasures: () => nextMeasureTool.clear(),
|
|
698
|
+
setMeasureAxisLock: (kind) => nextMeasureTool.setAxisLock(kind),
|
|
699
|
+
setSnapMode: (kind, on) => nextMeasureTool.setSnapMode(kind, on), snapState: () => nextMeasureTool.state().snapModes,
|
|
700
|
+
dispose: destroyMeasure,
|
|
701
|
+
} });
|
|
702
|
+
own(() => nextCadTools.dispose());
|
|
703
|
+
const selectionPort = viewport.selectionTools;
|
|
704
|
+
let nextSelectionTools = null;
|
|
705
|
+
if (selectionPort && ['coordinator', 'hitsAt', 'allHits', 'marqueeHits', 'generationToken', 'registerInterceptor']
|
|
706
|
+
.every((name) => name === 'coordinator' ? selectionPort.coordinator : typeof selectionPort[name] === 'function')) {
|
|
707
|
+
const decorate = (hits) => (Array.isArray(hits) ? hits : []).map((hit) => {
|
|
708
|
+
const sourceId = hit?.entity?.sourceId ?? hit?.sourceId ?? hit?.providerToken;
|
|
709
|
+
const entity = entityById.get(sourceId);
|
|
710
|
+
return { ...hit, entity: { kind: hit?.entity?.kind ?? 'native', sourceId: String(sourceId) }, facets: {
|
|
711
|
+
...(hit?.facets ?? {}), level: entity?.levelName ?? '', category: entity?.categoryName ?? entity?.category ?? '',
|
|
712
|
+
family: entity?.familyName ?? entity?.family ?? '', type: entity?.typeName ?? '',
|
|
713
|
+
} };
|
|
714
|
+
}).filter((hit) => hit.entity.sourceId && hit.entity.sourceId !== 'undefined');
|
|
715
|
+
nextSelectionTools = createModelSelectionTools({
|
|
716
|
+
coordinator: selectionPort.coordinator,
|
|
717
|
+
hitsAt: (pointer, event) => decorate(selectionPort.hitsAt(pointer, event)),
|
|
718
|
+
allHits: () => decorate(selectionPort.allHits()),
|
|
719
|
+
marqueeHits: (rect) => decorate(selectionPort.marqueeHits(rect)),
|
|
720
|
+
generationToken: () => selectionPort.generationToken(),
|
|
721
|
+
fitSelection: () => facade.dispatch('model.fit-selection'),
|
|
722
|
+
onHover: reflectSelectionHover,
|
|
723
|
+
onMarquee: reflectSelectionMarquee,
|
|
724
|
+
});
|
|
725
|
+
own(() => nextSelectionTools.destroy());
|
|
726
|
+
const releaseInput = selectionPort.registerInterceptor(nextSelectionTools.interceptor); if (releaseInput) own(releaseInput);
|
|
727
|
+
const releaseCamera = viewport.onCameraChange?.(() => nextSelectionTools.cameraChanged()); if (releaseCamera) own(releaseCamera);
|
|
728
|
+
}
|
|
729
|
+
const nextSelectionFilterChrome = nextSelectionTools ? mountRevitSelectionFilters(nextSelectionTools) : null;
|
|
730
|
+
if (nextSelectionFilterChrome) own(() => nextSelectionFilterChrome.destroy());
|
|
731
|
+
const subscribe = (set) => (listener) => { set.add(listener); let live = true; return () => { if (live) { live = false; set.delete(listener); } }; };
|
|
732
|
+
const dock = mountModelPointerDock({
|
|
733
|
+
selectionHost: $('modelSelectBar'), snapHost: $('modelSnapBar'), actionsHost: $('modelModuleActions'),
|
|
734
|
+
plan: REVIT_POINTER_DOCK_PLAN,
|
|
735
|
+
ports: {
|
|
736
|
+
selection: nextSelectionFilterChrome?.port,
|
|
737
|
+
snap: {
|
|
738
|
+
getState: () => nextCadTools.snapState(), subscribe: subscribe(snapListeners),
|
|
739
|
+
toggle: (kind) => { const state = nextCadTools.snapState(); nextCadTools.setSnapMode(kind, state[kind] === false); },
|
|
740
|
+
},
|
|
741
|
+
measure: {
|
|
742
|
+
getState: () => nextCadTools.measureState(), subscribe: subscribe(measureListeners),
|
|
743
|
+
toggle: () => nextCadTools.toggleMeasure(), setAxisLock: (kind) => nextCadTools.setMeasureAxisLock(kind), clear: () => nextCadTools.clearMeasures(),
|
|
744
|
+
},
|
|
745
|
+
},
|
|
746
|
+
});
|
|
747
|
+
own(() => dock.destroy());
|
|
748
|
+
measureTool = nextMeasureTool; cadTools = nextCadTools; selectionTools = nextSelectionTools; selectionFilterChrome = nextSelectionFilterChrome;
|
|
749
|
+
sharedTools = { destroy() { if (destroyed) return; destroyed = true; rollback(); measureTool = null; cadTools = null; selectionTools = null; selectionFilterChrome = null; } };
|
|
750
|
+
} catch (error) {
|
|
751
|
+
destroyed = true; rollback(); measureTool = null; cadTools = null; selectionTools = null; selectionFilterChrome = null; sharedTools = null; throw error;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function authorityButtons(state) {
|
|
756
|
+
const host = $('authorityChoices'); host.replaceChildren(); const available = ['draft', 'approved'].filter((key) => state[key]); const initial = state.draft ? 'draft' : 'approved';
|
|
757
|
+
window.__revitInstructorState = { ...(window.__revitInstructorState || {}), authority: initial };
|
|
758
|
+
for (const key of available) { const button = document.createElement('button'); button.type = 'button'; button.dataset.commandId = 'revit.authority'; button.dataset.commandInstanceLabel = key; button.textContent = key === 'draft' ? 'Working model' : 'Approved model'; button.setAttribute('aria-pressed', String(key === initial)); button.addEventListener('click', async () => { if (button.getAttribute('aria-pressed') === 'true') return; try { if (!await loadRevision(state, key)) return; await activateSpatialForRevision(state, state[key]); host.querySelectorAll('button').forEach((item) => item.setAttribute('aria-pressed', String(item === button))); window.__revitInstructorState = { ...(window.__revitInstructorState || {}), authority: key }; window.__instructor?.notifyChanged(); } catch (error) { toast(error.message); } }); host.append(button); }
|
|
759
|
+
return initial;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
async function boot() {
|
|
763
|
+
// Refuse an invalid direct-open before creating any of the three WebGL contexts (provider + chrome).
|
|
764
|
+
if (!projectId) throw new Error('Open this viewer from a Revit project workspace.');
|
|
765
|
+
modelShellMount = mountModelEditorShell({
|
|
766
|
+
root: $('editorRoot'), viewport: $('modelStage'), surface: $('modelCanvas'), toolbar: $('m3dBar'),
|
|
767
|
+
orientation: $('modelViewCube'), axes: $('modelWorldAxes'), explorer: $('modelExplorer'),
|
|
768
|
+
pointerDock: $('modelBottomDock'), inspector: $('inspectorPanel'), statusHud: $('modelSpatialHud'),
|
|
769
|
+
});
|
|
770
|
+
mountPanels();
|
|
771
|
+
viewport = createRevitViewport({ canvas: $('modelCanvas'),
|
|
772
|
+
// A big model takes a few seconds to convert, and the first moment shows nothing happening
|
|
773
|
+
// yet. After that the parts converting one by one are their own progress indicator.
|
|
774
|
+
onOutlineBuild: () => toast('Building the wireframe… large models take a few seconds.'),
|
|
775
|
+
onSelect: (ids) => {
|
|
776
|
+
if (selectionOriginGuard.isProgrammatic()) return;
|
|
777
|
+
selectedIds = [...ids]; if (ids.length) clipSession?.clearSelection?.();
|
|
778
|
+
inspect(ids.at(-1) || null, false, true, 'viewport');
|
|
779
|
+
} });
|
|
780
|
+
facade = createRevitEditorAdapter({ viewport, host: { openSavedViews } }); wireToolbar();
|
|
781
|
+
window.__revitEditorTest = { dispatchLog: () => facade.dispatchLog(), selected: () => selectedId, entityCount: () => entities.length,
|
|
782
|
+
selectionCapabilities: () => selectionTools?.capabilities() ?? null, spatialState: () => spatialTools?.state() ?? null,
|
|
783
|
+
editorState: () => facade.getState(), presentation: () => viewport.presentationProbe(),
|
|
784
|
+
lighting: () => facade.lightingState(),
|
|
785
|
+
// Wireframe must be probed on the DRAWN outline, never the hidden fill: the fill carries state in
|
|
786
|
+
// every mode, so reading it reports a picture the user is not looking at.
|
|
787
|
+
outline: () => viewport.outlineState?.() ?? null,
|
|
788
|
+
realistic: () => viewport.realisticState?.() ?? null };
|
|
789
|
+
window.__revitInstructorState = { selected: selectedId, authority: null };
|
|
790
|
+
await json('/api/editor/session', { method: 'POST' });
|
|
791
|
+
const state = (await json(`/api/editor/revit-projects/${encodeURIComponent(projectId)}`)).state;
|
|
792
|
+
projectContract = await json(`/api/contract/revit-model?project=${encodeURIComponent(projectId)}&quietMissing=1`);
|
|
793
|
+
$('modelName').textContent = state.projectName || projectId;
|
|
794
|
+
$('sourceName').textContent = state.source?.filename || 'No RVT source';
|
|
795
|
+
const authority = authorityButtons(state); await loadRevision(state, authority); await activateSpatialForRevision(state, state[authority]); mountSharedModelTools();
|
|
796
|
+
const releasePointerCoordinates = viewport.onPointerWorld((renderPoint) => {
|
|
797
|
+
if (!renderPoint || !spatialTools) { $('modelCursorCoordinates').textContent = 'X — · Y — · Z — mm'; return; }
|
|
798
|
+
const coords = spatialTools.coordinates(viewport.renderToCanonicalPoint(renderPoint));
|
|
799
|
+
$('modelCursorCoordinates').textContent = `X ${coords[0].toFixed(1)} · Y ${coords[1].toFixed(1)} · Z ${coords[2].toFixed(1)} mm`;
|
|
800
|
+
});
|
|
801
|
+
window.addEventListener('pagehide', releasePointerCoordinates, { once: true });
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function disposeEditor() {
|
|
805
|
+
if (terminalDisposed) return;
|
|
806
|
+
terminalDisposed = true; bfcacheSuspended = false;
|
|
807
|
+
revisionLoadController?.abort(); revisionLoadController = null; revisionLoadToken += 1;
|
|
808
|
+
sharedTools?.destroy(); sharedTools = null;
|
|
809
|
+
modelPanelBridge?.dispose(); modelPanelBridge = null;
|
|
810
|
+
closeSpatialDialog(); clipList?.destroy(); clipList = null; releaseClipEditor?.(); releaseClipEditor = null; releaseClipViewport?.(); releaseClipViewport = null; clipSession?.dispose(); clipSession = null;
|
|
811
|
+
retainEditorStateRecovery(); spatialPanel?.destroy(); spatialPanel = null; clearTimeout(editorStateSaveTimer); editorStateSaveTimer = null; releaseSpatialViewport?.(); releaseSpatialViewport = null; spatialTools?.dispose(); spatialTools = null;
|
|
812
|
+
modelShellMount?.destroy(); modelShellMount = null;
|
|
813
|
+
const facadeOwnsViewport = !!facade;
|
|
814
|
+
facade?.dispose();
|
|
815
|
+
if (!facadeOwnsViewport) viewport?.dispose();
|
|
816
|
+
facade = null; viewport = null; measureTool = null; cadTools = null; selectionTools = null;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
window.addEventListener('pagehide', (event) => {
|
|
820
|
+
if (terminalDisposed) return;
|
|
821
|
+
if (event.persisted) { bfcacheSuspended = true; facade?.suspend(); return; }
|
|
822
|
+
disposeEditor();
|
|
823
|
+
});
|
|
824
|
+
window.addEventListener('pageshow', (event) => {
|
|
825
|
+
if (!event.persisted || terminalDisposed || !bfcacheSuspended) return;
|
|
826
|
+
bfcacheSuspended = false; facade?.resume();
|
|
827
|
+
});
|
|
828
|
+
window.addEventListener('beforeunload', disposeEditor, { once: true });
|
|
829
|
+
|
|
830
|
+
// A function of its document: the Clips tab lives in a second one, the left Model section's frame.
|
|
831
|
+
function installTooltips(doc) { const win=doc.defaultView||window; const tip=doc.createElement('div'); tip.id='tooltip'; doc.body.appendChild(tip); let timer=null;
|
|
832
|
+
function show(el){ const text=el.getAttribute('data-tip'); if(!text)return; tip.textContent=text; tip.classList.add('show'); const rect=el.getBoundingClientRect(), width=tip.offsetWidth, height=tip.offsetHeight; tip.style.left=Math.max(6,Math.min(rect.left+rect.width/2-width/2,win.innerWidth-width-6))+'px'; tip.style.top=(rect.bottom+height+6>win.innerHeight?rect.top-height-6:rect.bottom+6)+'px'; }
|
|
833
|
+
function hide(){clearTimeout(timer);tip.classList.remove('show')} doc.addEventListener('pointerover',(event)=>{const el=event.target.closest('[data-tip]');if(!el)return;clearTimeout(timer);timer=setTimeout(()=>show(el),400)});doc.addEventListener('pointerout',(event)=>{if(event.target.closest('[data-tip]'))hide()});doc.addEventListener('pointerdown',hide,true);
|
|
834
|
+
}
|
|
835
|
+
installTooltips(document);
|
|
836
|
+
|
|
837
|
+
boot().catch((error) => {
|
|
838
|
+
if (terminalDisposed) return;
|
|
839
|
+
console.error(error);
|
|
840
|
+
modelPanelBridge?.failed(error.message || 'The verified model could not be opened.');
|
|
841
|
+
// A failed session fetch, project read, or first revision load is terminal for this editor instance.
|
|
842
|
+
// Release the provider renderer and both shared mini-renderers instead of waiting for page navigation.
|
|
843
|
+
disposeEditor();
|
|
844
|
+
fail(error.message || 'The verified model could not be opened.');
|
|
845
|
+
});
|