@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.
- package/autostart.mjs +6 -2
- package/desktop-access-production-manifest.mjs +7 -0
- package/dist/floless-server.cjs +157202 -70901
- 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 +410 -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 +2121 -1253
- package/dist/web/steel-filter.html +5 -1
- package/dist/web/steel-model-v2-commands.js +72 -1
- 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,717 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Instance-based viewport controller.
|
|
3
|
+
*
|
|
4
|
+
* The controller owns lifecycle, scheduling, input leases and serializable state. An injected adapter
|
|
5
|
+
* owns scene meaning and all host-specific rendering resources.
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
applySelectionProposal,
|
|
9
|
+
createModelEditorState,
|
|
10
|
+
createEntityKeyRegistry,
|
|
11
|
+
createViewportState,
|
|
12
|
+
transitionViewportState,
|
|
13
|
+
validateSelectionCommit,
|
|
14
|
+
} from './model-viewport-state.js';
|
|
15
|
+
|
|
16
|
+
export const MODEL_VIEWPORT_ADAPTER_REQUIRED = Object.freeze([
|
|
17
|
+
'mount', 'unmount', 'rebuild', 'bounds', 'fit', 'pick', 'applyCamera', 'applyOrientation', 'applyDisplayMode',
|
|
18
|
+
'applyClipState', 'applyPresentation', 'beforeRender', 'render', 'afterRender', 'setPaintAllowed',
|
|
19
|
+
'snapshotVisibility', 'applyVisibilitySnapshot', 'hideSelection', 'isolateSelection',
|
|
20
|
+
'clearVisibility', 'hasVisibilityFilter', 'cameraState', 'displayMode', 'sectionState', 'resize',
|
|
21
|
+
'show', 'hide', 'dispose',
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
export class ModelViewportError extends Error {
|
|
25
|
+
constructor(code, message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = 'ModelViewportError';
|
|
28
|
+
this.code = code;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const fail = (code, message) => { throw new ModelViewportError(code, message); };
|
|
33
|
+
|
|
34
|
+
export function assertModelViewportAdapter(adapter) {
|
|
35
|
+
if (!adapter || typeof adapter !== 'object') fail('E_VIEWPORT_ADAPTER_INCOMPLETE', 'viewport adapter is missing');
|
|
36
|
+
for (const name of MODEL_VIEWPORT_ADAPTER_REQUIRED) {
|
|
37
|
+
if (typeof adapter[name] !== 'function') fail('E_VIEWPORT_ADAPTER_INCOMPLETE', `viewport adapter does not implement ${name}`);
|
|
38
|
+
}
|
|
39
|
+
for (const name of ['snapData', 'workingPlaneData']) {
|
|
40
|
+
if (name in adapter && adapter[name] !== undefined && typeof adapter[name] !== 'function') {
|
|
41
|
+
fail('E_VIEWPORT_ADAPTER_INCOMPLETE', `optional adapter capability ${name} must be a function`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const immutable = (value) => {
|
|
48
|
+
if (!value || typeof value !== 'object') return value;
|
|
49
|
+
if (Array.isArray(value)) return Object.freeze(value.map(immutable));
|
|
50
|
+
const out = {};
|
|
51
|
+
for (const [key, item] of Object.entries(value)) out[key] = immutable(item);
|
|
52
|
+
return Object.freeze(out);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
function normalizedEvent(event) {
|
|
56
|
+
return immutable({
|
|
57
|
+
type: event?.type ?? '', pointerId: Number.isInteger(event?.pointerId) ? event.pointerId : null,
|
|
58
|
+
button: Number.isInteger(event?.button) ? event.button : null,
|
|
59
|
+
buttons: Number.isInteger(event?.buttons) ? event.buttons : 0,
|
|
60
|
+
clientX: Number.isFinite(event?.clientX) ? event.clientX : null,
|
|
61
|
+
clientY: Number.isFinite(event?.clientY) ? event.clientY : null,
|
|
62
|
+
key: typeof event?.key === 'string' ? event.key : '', code: typeof event?.code === 'string' ? event.code : '',
|
|
63
|
+
altKey: event?.altKey === true, ctrlKey: event?.ctrlKey === true,
|
|
64
|
+
metaKey: event?.metaKey === true, shiftKey: event?.shiftKey === true,
|
|
65
|
+
deltaX: Number.isFinite(event?.deltaX) ? event.deltaX : 0,
|
|
66
|
+
deltaY: Number.isFinite(event?.deltaY) ? event.deltaY : 0,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const EVENT_BINDINGS = Object.freeze([
|
|
71
|
+
['surface', 'pointerenter', 'pointerEnter'], ['surface', 'pointerleave', 'pointerLeave'],
|
|
72
|
+
['surface', 'pointerdown', 'pointerDown'], ['surface', 'pointercancel', 'pointerCancel'],
|
|
73
|
+
['surface', 'wheel', 'wheel'], ['surface', 'dblclick', 'doubleClick'],
|
|
74
|
+
['surface', 'contextmenu', 'contextMenu'], ['win', 'pointermove', 'pointerMove'],
|
|
75
|
+
['win', 'pointerup', 'pointerUp'], ['win', 'keydown', 'keyDown'],
|
|
76
|
+
['win', 'keyup', 'keyUp'], ['win', 'blur', 'windowBlur'],
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Own the input listener set and lend one pointer at a time to an adapter interceptor.
|
|
81
|
+
*/
|
|
82
|
+
/** @param {any} options */
|
|
83
|
+
export function createGestureBroker(options) {
|
|
84
|
+
const { surface, win = globalThis, orbit, raycast, requestFrame = () => {} } = options;
|
|
85
|
+
if (!surface?.addEventListener || !surface?.removeEventListener) fail('E_GESTURE_SURFACE', 'gesture surface must support events');
|
|
86
|
+
if (!win?.addEventListener || !win?.removeEventListener) fail('E_GESTURE_SURFACE', 'gesture window must support events');
|
|
87
|
+
let interceptor = null;
|
|
88
|
+
let lease = null;
|
|
89
|
+
let disposed = false;
|
|
90
|
+
const removers = [];
|
|
91
|
+
|
|
92
|
+
const releaseLease = (mode, event) => {
|
|
93
|
+
if (!lease) return false;
|
|
94
|
+
const current = lease; lease = null;
|
|
95
|
+
try {
|
|
96
|
+
if (current.pointerId !== null) surface.releasePointerCapture?.(current.pointerId);
|
|
97
|
+
} catch (_) {}
|
|
98
|
+
try {
|
|
99
|
+
if (mode === 'finish') current.onFinish?.(normalizedEvent(event));
|
|
100
|
+
else current.onCancel?.(mode, normalizedEvent(event));
|
|
101
|
+
} finally {
|
|
102
|
+
current.releaseOrbit?.();
|
|
103
|
+
}
|
|
104
|
+
return true;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const context = (event) => Object.freeze({
|
|
108
|
+
leased: !!lease,
|
|
109
|
+
raycastRecords: (filters) => immutable((raycast?.(normalizedEvent(event), filters) ?? []).map((hit) => ({
|
|
110
|
+
providerToken: hit.providerToken,
|
|
111
|
+
key: hit.key,
|
|
112
|
+
instanceIndex: Number.isInteger(hit.instanceIndex) ? hit.instanceIndex : null,
|
|
113
|
+
point: Array.isArray(hit.point) ? [...hit.point] : null,
|
|
114
|
+
normal: Array.isArray(hit.normal) ? [...hit.normal] : null,
|
|
115
|
+
distance: Number.isFinite(hit.distance) ? hit.distance : null,
|
|
116
|
+
}))),
|
|
117
|
+
requestFrame,
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
const consume = (event) => {
|
|
121
|
+
event?.preventDefault?.();
|
|
122
|
+
event?.stopImmediatePropagation?.();
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const handle = (callbackName, event) => {
|
|
126
|
+
if (disposed || !interceptor) return;
|
|
127
|
+
if (callbackName === 'pointerMove' && lease && event?.pointerId !== lease.pointerId) return;
|
|
128
|
+
if (callbackName === 'pointerUp' && lease && event?.pointerId === lease.pointerId) {
|
|
129
|
+
interceptor.pointerUp?.(normalizedEvent(event), context(event));
|
|
130
|
+
releaseLease('finish', event); return;
|
|
131
|
+
}
|
|
132
|
+
if (callbackName === 'pointerCancel' && lease && (event?.pointerId === lease.pointerId || event?.pointerId == null)) {
|
|
133
|
+
interceptor.pointerCancel?.(normalizedEvent(event), context(event));
|
|
134
|
+
releaseLease('pointer-cancel', event); return;
|
|
135
|
+
}
|
|
136
|
+
const disposition = interceptor[callbackName]?.(normalizedEvent(event), context(event));
|
|
137
|
+
if (callbackName === 'keyDown' && event?.key === 'Escape' && lease) {
|
|
138
|
+
consume(event); releaseLease('escape', event); return;
|
|
139
|
+
}
|
|
140
|
+
if (callbackName === 'windowBlur' && lease) { releaseLease('window-blur', event); return; }
|
|
141
|
+
if (callbackName !== 'pointerDown' || !disposition || disposition.kind === 'pass') return;
|
|
142
|
+
if (!['consume', 'begin'].includes(disposition.kind)) fail('E_GESTURE_DISPOSITION', `unknown gesture disposition ${disposition.kind}`);
|
|
143
|
+
consume(event);
|
|
144
|
+
if (disposition.kind === 'consume') return;
|
|
145
|
+
if (lease) fail('E_GESTURE_BUSY', 'a pointer lease is already active');
|
|
146
|
+
const pointerId = Number.isInteger(event?.pointerId) ? event.pointerId : null;
|
|
147
|
+
const releaseOrbit = orbit?.block?.(disposition.reason ?? 'adapter-gesture') ?? (() => {});
|
|
148
|
+
lease = { pointerId, onFinish: disposition.onFinish, onCancel: disposition.onCancel, releaseOrbit };
|
|
149
|
+
if (pointerId !== null) surface.setPointerCapture?.(pointerId);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
for (const [owner, type, callback] of EVENT_BINDINGS) {
|
|
153
|
+
const target = owner === 'surface' ? surface : win;
|
|
154
|
+
const fn = (event) => handle(callback, event);
|
|
155
|
+
const options = type === 'pointerdown' || type === 'wheel' ? { capture: true, passive: false } : undefined;
|
|
156
|
+
target.addEventListener(type, fn, options);
|
|
157
|
+
removers.push(() => target.removeEventListener(type, fn, options?.capture ?? false));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return Object.freeze({
|
|
161
|
+
register(value) {
|
|
162
|
+
if (disposed) fail('E_GESTURE_DISPOSED', 'gesture broker is disposed');
|
|
163
|
+
if (interceptor) fail('E_GESTURE_INTERCEPTOR', 'only one adapter interceptor may be registered');
|
|
164
|
+
interceptor = value ?? {};
|
|
165
|
+
return () => { if (interceptor === value) interceptor = null; };
|
|
166
|
+
},
|
|
167
|
+
cancel(reason = 'cancel') { return releaseLease(reason, null); },
|
|
168
|
+
hasLease() { return !!lease; },
|
|
169
|
+
dispose() {
|
|
170
|
+
if (disposed) return;
|
|
171
|
+
disposed = true; releaseLease('dispose', null);
|
|
172
|
+
for (const remove of removers.splice(0)) remove();
|
|
173
|
+
interceptor = null;
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/*
|
|
179
|
+
* How long a scheduled frame waits for an animation frame before a timer drives it instead. 100ms is
|
|
180
|
+
* the same fallback an adapter in this repo already races against its own build loop, for exactly this
|
|
181
|
+
* starvation: a starved viewer then redraws at ~10Hz rather than never, and a composited one never
|
|
182
|
+
* reaches the timer at all.
|
|
183
|
+
*/
|
|
184
|
+
const FRAME_FALLBACK_MS = 100;
|
|
185
|
+
|
|
186
|
+
function defaultPlatform() {
|
|
187
|
+
return {
|
|
188
|
+
requestFrame: (callback) => globalThis.requestAnimationFrame(callback),
|
|
189
|
+
cancelFrame: (id) => globalThis.cancelAnimationFrame(id),
|
|
190
|
+
observeResize: (surface, callback) => {
|
|
191
|
+
const observer = new globalThis.ResizeObserver(callback); observer.observe(surface); return () => observer.disconnect();
|
|
192
|
+
},
|
|
193
|
+
measureSurface: (surface) => {
|
|
194
|
+
const rect = surface.getBoundingClientRect();
|
|
195
|
+
return { width: rect.width, height: rect.height, pixelRatio: Math.min(globalThis.devicePixelRatio || 1, 2) };
|
|
196
|
+
},
|
|
197
|
+
win: globalThis,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let fallbackToken = 0;
|
|
202
|
+
const newToken = () => globalThis.crypto?.randomUUID?.() ?? `viewport-${++fallbackToken}`;
|
|
203
|
+
|
|
204
|
+
/** @param {any} options */
|
|
205
|
+
export function createModelViewportController(options) {
|
|
206
|
+
const { adapter, platform = defaultPlatform(), identityRegistry = createEntityKeyRegistry(), initialSelectionCommit = null,
|
|
207
|
+
selectionCoordinator = null } = options;
|
|
208
|
+
assertModelViewportAdapter(adapter);
|
|
209
|
+
/*
|
|
210
|
+
* requestAnimationFrame is the right pacing for a page that is being composited. A page that is NOT
|
|
211
|
+
* composited gets no animation frames at all — an occluded but foreground window, a headless or
|
|
212
|
+
* virtual display — and the page-visibility flag reads "visible" in exactly those cases, so there is
|
|
213
|
+
* nothing to branch on. Left rAF-only the loop simply stops, with no error and no visible
|
|
214
|
+
* explanation (#1419).
|
|
215
|
+
*
|
|
216
|
+
* So each frame races a timer against the animation frame: whichever arrives first runs the frame and
|
|
217
|
+
* withdraws the other. On a composited page the animation frame wins and the timer is cancelled
|
|
218
|
+
* before it fires, so the fallback costs a healthy viewport nothing beyond arming it.
|
|
219
|
+
*
|
|
220
|
+
* Resolved here rather than in defaultPlatform() because every shipping adapter injects a platform of
|
|
221
|
+
* its own, so a fix confined to the default platform would reach none of them.
|
|
222
|
+
*/
|
|
223
|
+
const requestTimer = platform.requestTimer ?? ((callback, ms) => globalThis.setTimeout(callback, ms));
|
|
224
|
+
const cancelTimer = platform.cancelTimer ?? ((id) => globalThis.clearTimeout(id));
|
|
225
|
+
// Required as a PAIR rather than defaulted apart. A platform bringing its own scheduler but no
|
|
226
|
+
// canceller would have its ids handed to globalThis.clearTimeout, which silently no-ops on an id it
|
|
227
|
+
// did not issue — so every fallback frame would leak a live timer with nothing to say so.
|
|
228
|
+
if ((platform.requestTimer === undefined) !== (platform.cancelTimer === undefined)) {
|
|
229
|
+
fail('E_VIEWPORT_PLATFORM', 'a platform that supplies requestTimer must also supply cancelTimer');
|
|
230
|
+
}
|
|
231
|
+
// A timer-driven frame carries performance.now(), which IS the animation frame's own time origin, so
|
|
232
|
+
// a fallback frame is indistinguishable from a real one should an adapter ever difference `time`.
|
|
233
|
+
// None in this repo reads it today.
|
|
234
|
+
const clock = platform.now ?? (() => globalThis.performance?.now?.() ?? Date.now());
|
|
235
|
+
/*
|
|
236
|
+
* A page the browser reports as hidden — a background tab, a minimized window — is NOT starved:
|
|
237
|
+
* suspending its frames is the browser working correctly, and waking a WebGL scene ten times a second
|
|
238
|
+
* to draw what nobody can see is cost with no benefit. Only the cases the flag cannot see need the
|
|
239
|
+
* fallback, and those are precisely the ones that still read "visible".
|
|
240
|
+
*
|
|
241
|
+
* The platform owns the read because it means touching the document, which belongs to the provider
|
|
242
|
+
* layer and not to this provider-neutral module. A platform that does not supply it always gets the
|
|
243
|
+
* fallback, which is the safe direction.
|
|
244
|
+
*/
|
|
245
|
+
const pageHidden = () => platform.pageHidden?.() === true;
|
|
246
|
+
const scheduleFrame = (callback) => {
|
|
247
|
+
let settled = false;
|
|
248
|
+
let timer = null;
|
|
249
|
+
let frameId = null;
|
|
250
|
+
let frameArmed = false; // explicit, because a platform may legitimately issue 0 or null as an id
|
|
251
|
+
const run = (time) => {
|
|
252
|
+
if (settled) return;
|
|
253
|
+
settled = true;
|
|
254
|
+
const pendingTimer = timer; timer = null;
|
|
255
|
+
const pendingFrame = frameId; frameId = null;
|
|
256
|
+
const hadFrame = frameArmed; frameArmed = false;
|
|
257
|
+
// Withdraw BOTH registrations — the winner's own, which has already fired and is inert to cancel,
|
|
258
|
+
// and the loser's, which is still live. Cancelling in only one direction leaks: on a page that is
|
|
259
|
+
// never composited the timer wins every single frame, so each losing animation frame stayed
|
|
260
|
+
// registered, ten a second, retaining this closure and the adapter behind it for as long as the
|
|
261
|
+
// page stayed dark, and outliving dispose(). Both cancels are best-effort here: the frame has
|
|
262
|
+
// already been delivered, and a platform that refuses to tidy up after an id it has itself fired
|
|
263
|
+
// must not cost us that frame.
|
|
264
|
+
if (pendingTimer !== null) { try { cancelTimer(pendingTimer); } catch (_) { /* already fired */ } }
|
|
265
|
+
if (hadFrame) { try { platform.cancelFrame(pendingFrame); } catch (_) { /* already fired */ } }
|
|
266
|
+
callback(time);
|
|
267
|
+
};
|
|
268
|
+
const handle = platform.requestFrame(run);
|
|
269
|
+
// Guarded: a platform whose requestFrame calls back synchronously has already run the frame, so
|
|
270
|
+
// there is nothing left to arm and nothing left to withdraw.
|
|
271
|
+
if (!settled) {
|
|
272
|
+
frameId = handle; frameArmed = true;
|
|
273
|
+
if (!pageHidden()) {
|
|
274
|
+
try {
|
|
275
|
+
timer = requestTimer(() => run(clock()), FRAME_FALLBACK_MS);
|
|
276
|
+
} catch (error) {
|
|
277
|
+
// The frame is registered and this handle is about to be lost with the throw, so withdraw it
|
|
278
|
+
// here or it becomes an uncancellable second loop beside the one the caller schedules next.
|
|
279
|
+
frameArmed = false; frameId = null;
|
|
280
|
+
try { platform.cancelFrame(handle); } catch (_) {}
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return {
|
|
286
|
+
cancel() {
|
|
287
|
+
if (settled) return;
|
|
288
|
+
const pendingTimer = timer; timer = null;
|
|
289
|
+
const pendingFrame = frameId; frameId = null;
|
|
290
|
+
const hadFrame = frameArmed; frameArmed = false;
|
|
291
|
+
try {
|
|
292
|
+
if (pendingTimer !== null) cancelTimer(pendingTimer);
|
|
293
|
+
} finally {
|
|
294
|
+
// `settled` latches only once the frame itself is retired. Latching first would strand a frame
|
|
295
|
+
// that a failing cancelFrame left live: run() would no-op it, while hide()'s `loopFrame = null`
|
|
296
|
+
// never runs after a throw, so scheduleLoop() stays wedged and the viewport freezes for good —
|
|
297
|
+
// the very failure this file exists to fix. Left unlatched, that live frame still fires and
|
|
298
|
+
// revives the loop, exactly as it did before this race was added.
|
|
299
|
+
if (hadFrame) platform.cancelFrame(pendingFrame);
|
|
300
|
+
settled = true;
|
|
301
|
+
}
|
|
302
|
+
},
|
|
303
|
+
};
|
|
304
|
+
};
|
|
305
|
+
let state = createViewportState();
|
|
306
|
+
let surface = null;
|
|
307
|
+
let observerRelease = null;
|
|
308
|
+
let loopFrame = null;
|
|
309
|
+
let resizeFrame = null;
|
|
310
|
+
let mounted = false;
|
|
311
|
+
let disposed = false;
|
|
312
|
+
let rebuildEpoch = 0;
|
|
313
|
+
let rebuildAbort = null;
|
|
314
|
+
let renderEpoch = -1;
|
|
315
|
+
let records = new Map();
|
|
316
|
+
let generationSequence = 0;
|
|
317
|
+
let activeGeneration = null;
|
|
318
|
+
const preparedGenerations = new Map();
|
|
319
|
+
let selectionCommit = initialSelectionCommit
|
|
320
|
+
? validateSelectionCommit(initialSelectionCommit, { registry: identityRegistry })
|
|
321
|
+
: immutable({ revision: 0, origin: 'programmatic', operation: 'clear', keys: [], primaryKey: null });
|
|
322
|
+
if (selectionCommit.keys.length) {
|
|
323
|
+
state = transitionViewportState(state, { type: 'selection', keys: selectionCommit.keys, primaryKey: selectionCommit.primaryKey });
|
|
324
|
+
}
|
|
325
|
+
let broker = null;
|
|
326
|
+
const stateSubscribers = new Set();
|
|
327
|
+
const instanceToken = newToken();
|
|
328
|
+
|
|
329
|
+
const ensureLive = () => { if (disposed) fail('E_VIEWPORT_DISPOSED', 'viewport controller is disposed'); };
|
|
330
|
+
const paint = (on) => { adapter.setPaintAllowed(on === true); };
|
|
331
|
+
const resize = () => {
|
|
332
|
+
if (!surface || disposed) return;
|
|
333
|
+
const size = platform.measureSurface(surface);
|
|
334
|
+
adapter.resize?.(immutable(size));
|
|
335
|
+
};
|
|
336
|
+
const scheduleLoop = () => {
|
|
337
|
+
if (loopFrame !== null || disposed || !state.shown) return;
|
|
338
|
+
loopFrame = scheduleFrame(frame);
|
|
339
|
+
};
|
|
340
|
+
const frame = (time) => {
|
|
341
|
+
loopFrame = null;
|
|
342
|
+
if (disposed || !state.shown) return;
|
|
343
|
+
scheduleLoop();
|
|
344
|
+
if (!state.frameAllowed) return;
|
|
345
|
+
adapter.beforeRender(time); adapter.render(time); adapter.afterRender(time);
|
|
346
|
+
};
|
|
347
|
+
const applyPresentation = () => adapter.applyPresentation(immutable({ selectedKeys: state.selectedKeys, primaryKey: state.primaryKey, hoverKey: state.hoverKey, ghostUnselected: state.ghostUnselected }));
|
|
348
|
+
const editorState = () => createModelEditorState({
|
|
349
|
+
selectionCount: state.selectedKeys.length,
|
|
350
|
+
actionableVisibilitySelectionCount: state.selectedKeys.reduce((count, key) => (
|
|
351
|
+
count + Number(adapter.isVisibilityActionable?.(key) === true)
|
|
352
|
+
), 0),
|
|
353
|
+
ghostUnselected: state.ghostUnselected,
|
|
354
|
+
hasVisibilityFilter: state.hasVisibilityFilter,
|
|
355
|
+
});
|
|
356
|
+
const publishState = () => {
|
|
357
|
+
const snapshot = editorState();
|
|
358
|
+
for (const listener of [...stateSubscribers]) {
|
|
359
|
+
try { listener(snapshot); } catch (_) {}
|
|
360
|
+
}
|
|
361
|
+
return snapshot;
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
const closePreparedGeneration = (entry, reason = 'discard') => {
|
|
365
|
+
if (!entry || entry.status !== 'prepared') return [];
|
|
366
|
+
entry.status = reason;
|
|
367
|
+
preparedGenerations.delete(entry.handle.token);
|
|
368
|
+
const errors = [];
|
|
369
|
+
try { identityRegistry.discardGeneration?.(entry.identity); } catch (error) { errors.push(error); }
|
|
370
|
+
try { entry.payload?.dispose?.(reason); } catch (error) { errors.push(error); }
|
|
371
|
+
return errors;
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
const normalizedGenerationRecords = (entry) => {
|
|
375
|
+
const list = entry.payload?.records ?? [];
|
|
376
|
+
if (!Array.isArray(list)) fail('E_GENERATION_RECORDS', 'prepared generation records must be an array');
|
|
377
|
+
const next = new Map();
|
|
378
|
+
for (const source of list) {
|
|
379
|
+
const receipt = source?.identity ?? source;
|
|
380
|
+
if (!receipt?.key || !entry.identity.hasReceipt?.(receipt)) fail('E_STALE_ENTITY_GENERATION', 'generation record has a stale identity receipt');
|
|
381
|
+
if (next.has(receipt.key)) fail('E_GENERATION_RECORDS', `generation record ${receipt.key} is duplicated`);
|
|
382
|
+
next.set(receipt.key, immutable({ ...source, key: receipt.key, namespace: receipt.namespace, generation: receipt.generation }));
|
|
383
|
+
}
|
|
384
|
+
return next;
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const api = {
|
|
388
|
+
init(nextSurface) {
|
|
389
|
+
ensureLive();
|
|
390
|
+
if (mounted) return api;
|
|
391
|
+
if (!nextSurface) fail('E_VIEWPORT_SURFACE', 'viewport surface is required');
|
|
392
|
+
surface = nextSurface;
|
|
393
|
+
const rollbacks = [];
|
|
394
|
+
try {
|
|
395
|
+
paint(false);
|
|
396
|
+
if (surface.addEventListener && platform.win?.addEventListener) {
|
|
397
|
+
broker = createGestureBroker({
|
|
398
|
+
surface, win: platform.win,
|
|
399
|
+
orbit: { block: (reason) => adapter.blockOrbit?.(reason) ?? (() => {}) },
|
|
400
|
+
raycast: (event, filters) => adapter.raycastRecords?.(event, filters) ?? [],
|
|
401
|
+
requestFrame: platform.requestFrame,
|
|
402
|
+
});
|
|
403
|
+
rollbacks.push(() => broker.dispose());
|
|
404
|
+
}
|
|
405
|
+
adapter.mount(immutable({
|
|
406
|
+
surface, instanceToken,
|
|
407
|
+
replaceRenderRecords: api.replaceRenderRecords,
|
|
408
|
+
reportCameraState: api.reportCameraState,
|
|
409
|
+
reportDisplayMode: api.reportDisplayMode,
|
|
410
|
+
reportSectionState: api.reportSectionState,
|
|
411
|
+
reportVisibility: api.reportVisibility,
|
|
412
|
+
gestureBroker: broker,
|
|
413
|
+
}));
|
|
414
|
+
state = transitionViewportState(state, { type: 'camera', camera: adapter.cameraState() });
|
|
415
|
+
state = transitionViewportState(state, { type: 'display', mode: adapter.displayMode() });
|
|
416
|
+
const section = adapter.sectionState();
|
|
417
|
+
state = transitionViewportState(state, { type: 'section', clipping: section.clipping, workPlane: section.workPlane, workArea: section.workArea, activeClipGesture: section.activeClipGesture ?? null });
|
|
418
|
+
state = transitionViewportState(state, { type: 'visibility', filtered: adapter.hasVisibilityFilter() });
|
|
419
|
+
applyPresentation();
|
|
420
|
+
mounted = true; rollbacks.push(() => adapter.unmount());
|
|
421
|
+
observerRelease = platform.observeResize(surface, resize); rollbacks.push(() => observerRelease?.());
|
|
422
|
+
resize();
|
|
423
|
+
resizeFrame = scheduleFrame(() => { resizeFrame = null; resize(); });
|
|
424
|
+
rollbacks.push(() => { resizeFrame?.cancel(); resizeFrame = null; });
|
|
425
|
+
state = transitionViewportState(state, { type: 'init' });
|
|
426
|
+
return api;
|
|
427
|
+
} catch (error) {
|
|
428
|
+
for (const rollback of rollbacks.reverse()) { try { rollback(); } catch (_) {} }
|
|
429
|
+
mounted = false; broker = null; observerRelease = null; surface = null;
|
|
430
|
+
state = transitionViewportState(state, { type: 'fail' });
|
|
431
|
+
throw error;
|
|
432
|
+
}
|
|
433
|
+
},
|
|
434
|
+
show() {
|
|
435
|
+
ensureLive(); if (!mounted) fail('E_VIEWPORT_NOT_READY', 'viewport is not initialized');
|
|
436
|
+
state = transitionViewportState(state, { type: 'show' });
|
|
437
|
+
paint(state.frameAllowed); adapter.show(); resize(); scheduleLoop(); return api;
|
|
438
|
+
},
|
|
439
|
+
hide() {
|
|
440
|
+
ensureLive(); if (!mounted) return api;
|
|
441
|
+
broker?.cancel('hide');
|
|
442
|
+
loopFrame?.cancel(); loopFrame = null;
|
|
443
|
+
state = transitionViewportState(state, { type: 'hide' }); paint(false); adapter.hide(); return api;
|
|
444
|
+
},
|
|
445
|
+
async rebuild(options = {}) {
|
|
446
|
+
ensureLive(); if (!mounted) fail('E_VIEWPORT_NOT_READY', 'viewport is not initialized');
|
|
447
|
+
const epoch = ++rebuildEpoch;
|
|
448
|
+
rebuildAbort?.abort(); rebuildAbort = new AbortController();
|
|
449
|
+
const prepared = api.prepareGeneration({ epoch });
|
|
450
|
+
const context = immutable({ fit: options.fit === true, instanceToken, epoch, signal: rebuildAbort.signal,
|
|
451
|
+
generation: prepared.identity, generationToken: prepared.token, generationNamespace: prepared.namespace });
|
|
452
|
+
try {
|
|
453
|
+
const result = await adapter.rebuild(context);
|
|
454
|
+
if (result?.generation) prepared.stage(result.generation);
|
|
455
|
+
if (disposed || epoch !== rebuildEpoch) { closePreparedGeneration(preparedGenerations.get(prepared.token), 'stale'); return { stale: true, result }; }
|
|
456
|
+
if (result?.generation) {
|
|
457
|
+
const preparedClear = selectionCoordinator?.prepareClearForGeneration?.({ namespace: prepared.namespace }) ?? null;
|
|
458
|
+
api.commitGeneration(prepared, { preparedClear });
|
|
459
|
+
} else closePreparedGeneration(preparedGenerations.get(prepared.token), 'unused');
|
|
460
|
+
if (result?.cameraFitted === true) {
|
|
461
|
+
state = transitionViewportState(state, { type: 'camera', camera: adapter.cameraState() });
|
|
462
|
+
state = transitionViewportState(state, { type: 'fit-complete' });
|
|
463
|
+
} else if (options.fit === true && !result?.empty) {
|
|
464
|
+
const bounds = adapter.bounds('camera-all');
|
|
465
|
+
if (bounds) { adapter.fit(immutable({ purpose: 'camera-all', bounds })); state = transitionViewportState(state, { type: 'camera', camera: adapter.cameraState() }); state = transitionViewportState(state, { type: 'fit-complete' }); }
|
|
466
|
+
else state = transitionViewportState(state, { type: 'build-settled', outcome: 'empty' });
|
|
467
|
+
} else state = transitionViewportState(state, { type: 'build-settled', outcome: result?.empty ? 'empty' : 'success' });
|
|
468
|
+
applyPresentation(); paint(state.frameAllowed); return { stale: false, result };
|
|
469
|
+
} catch (error) {
|
|
470
|
+
closePreparedGeneration(preparedGenerations.get(prepared.token), 'failure');
|
|
471
|
+
if (disposed || epoch !== rebuildEpoch) return { stale: true, error };
|
|
472
|
+
state = transitionViewportState(state, { type: 'build-settled', outcome: 'failure' }); paint(true); throw error;
|
|
473
|
+
}
|
|
474
|
+
},
|
|
475
|
+
replaceRenderRecords(publication) {
|
|
476
|
+
if (disposed || publication?.instanceToken !== instanceToken || !Number.isSafeInteger(publication?.renderEpoch) || publication.renderEpoch <= renderEpoch || !Array.isArray(publication.records)) return false;
|
|
477
|
+
const next = new Map();
|
|
478
|
+
if (activeGeneration && publication.namespace !== activeGeneration.namespace) return false;
|
|
479
|
+
for (const record of publication.records) {
|
|
480
|
+
if (!record?.key) continue;
|
|
481
|
+
if (activeGeneration) {
|
|
482
|
+
if (record.namespace !== activeGeneration.namespace || !identityRegistry.has(record.key, record)) return false;
|
|
483
|
+
}
|
|
484
|
+
next.set(record.key, record);
|
|
485
|
+
}
|
|
486
|
+
renderEpoch = publication.renderEpoch; records = next;
|
|
487
|
+
if (state.hoverKey && !records.has(state.hoverKey)) { state = transitionViewportState(state, { type: 'hover', key: null }); applyPresentation(); }
|
|
488
|
+
return true;
|
|
489
|
+
},
|
|
490
|
+
pick(pointer) {
|
|
491
|
+
ensureLive();
|
|
492
|
+
const hit = adapter.pick(immutable(pointer ?? {}));
|
|
493
|
+
if (!hit?.key || !identityRegistry.has(hit.key) || !records.has(hit.key)) return null;
|
|
494
|
+
const record = records.get(hit.key);
|
|
495
|
+
if (activeGeneration && (hit.namespace !== activeGeneration.namespace || hit.generation !== record.generation
|
|
496
|
+
|| !identityRegistry.has(hit.key, hit))) return null;
|
|
497
|
+
return immutable({
|
|
498
|
+
key: hit.key,
|
|
499
|
+
...(activeGeneration ? { namespace: hit.namespace, generation: hit.generation } : {}),
|
|
500
|
+
providerToken: hit.providerToken ?? null,
|
|
501
|
+
instanceIndex: Number.isInteger(hit.instanceIndex) ? hit.instanceIndex : null,
|
|
502
|
+
point: Array.isArray(hit.point) ? hit.point : null,
|
|
503
|
+
normal: Array.isArray(hit.normal) ? hit.normal : null,
|
|
504
|
+
distance: Number.isFinite(hit.distance) ? hit.distance : null,
|
|
505
|
+
});
|
|
506
|
+
},
|
|
507
|
+
reportCameraState(value) {
|
|
508
|
+
if (disposed) return false;
|
|
509
|
+
state = transitionViewportState(state, { type: 'camera', camera: value ?? adapter.cameraState() }); return true;
|
|
510
|
+
},
|
|
511
|
+
reportDisplayMode(mode) {
|
|
512
|
+
if (disposed) return false;
|
|
513
|
+
state = transitionViewportState(state, { type: 'display', mode: mode ?? adapter.displayMode() }); return true;
|
|
514
|
+
},
|
|
515
|
+
reportSectionState(value) {
|
|
516
|
+
if (disposed) return false;
|
|
517
|
+
const next = value ?? adapter.sectionState();
|
|
518
|
+
state = transitionViewportState(state, { type: 'section', clipping: next.clipping, workPlane: next.workPlane, workArea: next.workArea, activeClipGesture: next.activeClipGesture ?? null }); publishState(); return true;
|
|
519
|
+
},
|
|
520
|
+
reportVisibility(filtered) {
|
|
521
|
+
if (disposed) return false;
|
|
522
|
+
state = transitionViewportState(state, { type: 'visibility', filtered: filtered ?? adapter.hasVisibilityFilter() }); publishState(); return true;
|
|
523
|
+
},
|
|
524
|
+
commitSelection(commit) {
|
|
525
|
+
ensureLive();
|
|
526
|
+
if (commit?.revision <= selectionCommit.revision) return selectionCommit;
|
|
527
|
+
const next = validateSelectionCommit(commit, { previousRevision: selectionCommit.revision, registry: identityRegistry });
|
|
528
|
+
selectionCommit = next;
|
|
529
|
+
state = transitionViewportState(state, { type: 'selection', keys: next.keys, primaryKey: next.primaryKey });
|
|
530
|
+
applyPresentation(); publishState(); return next;
|
|
531
|
+
},
|
|
532
|
+
proposeSelection(proposal) {
|
|
533
|
+
ensureLive();
|
|
534
|
+
const next = selectionCoordinator?.applyProposal
|
|
535
|
+
? selectionCoordinator.applyProposal(proposal)
|
|
536
|
+
: applySelectionProposal(selectionCommit, proposal, identityRegistry);
|
|
537
|
+
selectionCommit = next;
|
|
538
|
+
state = transitionViewportState(state, { type: 'selection', keys: next.keys, primaryKey: next.primaryKey });
|
|
539
|
+
applyPresentation(); publishState(); return next;
|
|
540
|
+
},
|
|
541
|
+
selectionCommit() { return selectionCommit; },
|
|
542
|
+
setHover(key) {
|
|
543
|
+
ensureLive();
|
|
544
|
+
const next = key && identityRegistry.has(key) && records.has(key) ? key : null;
|
|
545
|
+
state = transitionViewportState(state, { type: 'hover', key: next }); applyPresentation(); return next;
|
|
546
|
+
},
|
|
547
|
+
hideSelection() {
|
|
548
|
+
ensureLive(); const outcome = adapter.hideSelection(state.selectedKeys);
|
|
549
|
+
const hiddenKeys = Array.isArray(outcome?.hiddenKeys) ? outcome.hiddenKeys.filter((key) => state.selectedKeys.includes(key)) : [];
|
|
550
|
+
state = transitionViewportState(state, { type: 'visibility', filtered: adapter.hasVisibilityFilter() });
|
|
551
|
+
const hoverHidden = hiddenKeys.includes(state.hoverKey);
|
|
552
|
+
if (hoverHidden) state = transitionViewportState(state, { type: 'hover', key: null });
|
|
553
|
+
if (selectionCoordinator && hiddenKeys.length) {
|
|
554
|
+
const hidden = new Set(hiddenKeys);
|
|
555
|
+
selectionCoordinator.remove(selectionCoordinator.entries().filter((entry) => hidden.has(entry.key)));
|
|
556
|
+
} else if (hoverHidden) applyPresentation();
|
|
557
|
+
publishState(); return Number.isFinite(outcome?.count) ? outcome.count : outcome;
|
|
558
|
+
},
|
|
559
|
+
isolateSelection() {
|
|
560
|
+
ensureLive(); const result = adapter.isolateSelection(state.selectedKeys);
|
|
561
|
+
state = transitionViewportState(state, { type: 'visibility', filtered: adapter.hasVisibilityFilter() });
|
|
562
|
+
if (state.ghostUnselected) { state = transitionViewportState(state, { type: 'ghost', enabled: false }); applyPresentation(); }
|
|
563
|
+
publishState(); return result;
|
|
564
|
+
},
|
|
565
|
+
showAll() {
|
|
566
|
+
ensureLive(); adapter.clearVisibility();
|
|
567
|
+
state = transitionViewportState(state, { type: 'visibility', filtered: adapter.hasVisibilityFilter() });
|
|
568
|
+
state = transitionViewportState(state, { type: 'ghost', enabled: false });
|
|
569
|
+
applyPresentation(); publishState();
|
|
570
|
+
},
|
|
571
|
+
setGhostUnselected(enabled) {
|
|
572
|
+
ensureLive();
|
|
573
|
+
// Isolate and Ghost unselected are alternatives: Ghost lifts an isolation, and the adapter brings back only what
|
|
574
|
+
// the isolation hid. An isolation already cleared some other way leaves nothing to lift.
|
|
575
|
+
if (enabled && adapter.isIsolated?.()) {
|
|
576
|
+
adapter.clearIsolation();
|
|
577
|
+
state = transitionViewportState(state, { type: 'visibility', filtered: adapter.hasVisibilityFilter() });
|
|
578
|
+
}
|
|
579
|
+
state = transitionViewportState(state, { type: 'ghost', enabled });
|
|
580
|
+
applyPresentation(); publishState(); return state.ghostUnselected;
|
|
581
|
+
},
|
|
582
|
+
toggleGhostUnselected() { return api.setGhostUnselected(!state.ghostUnselected); },
|
|
583
|
+
ghostUnselected() { ensureLive(); return state.ghostUnselected; },
|
|
584
|
+
visibilitySnapshot() { ensureLive(); return immutable(adapter.snapshotVisibility()); },
|
|
585
|
+
applyVisibilitySnapshot(value) {
|
|
586
|
+
ensureLive(); adapter.applyVisibilitySnapshot(value);
|
|
587
|
+
state = transitionViewportState(state, { type: 'visibility', filtered: adapter.hasVisibilityFilter() });
|
|
588
|
+
if (value && Object.prototype.hasOwnProperty.call(value, 'ghostUnselected')) {
|
|
589
|
+
state = transitionViewportState(state, { type: 'ghost', enabled: value.ghostUnselected });
|
|
590
|
+
}
|
|
591
|
+
applyPresentation(); publishState();
|
|
592
|
+
},
|
|
593
|
+
applyCamera(value) { ensureLive(); adapter.applyCamera(value); state = transitionViewportState(state, { type: 'camera', camera: adapter.cameraState() }); },
|
|
594
|
+
setProjection(mode) {
|
|
595
|
+
ensureLive();
|
|
596
|
+
const camera = immutable({ ...state.camera, projection: mode });
|
|
597
|
+
adapter.applyCamera(camera); state = transitionViewportState(state, { type: 'camera', camera: adapter.cameraState() });
|
|
598
|
+
},
|
|
599
|
+
applyOrientation(value) {
|
|
600
|
+
ensureLive(); adapter.applyOrientation(value);
|
|
601
|
+
state = transitionViewportState(state, { type: 'camera', camera: adapter.cameraState() });
|
|
602
|
+
},
|
|
603
|
+
setDisplayMode(mode) { ensureLive(); adapter.applyDisplayMode(mode); state = transitionViewportState(state, { type: 'display', mode }); applyPresentation(); },
|
|
604
|
+
setSectionState(value) {
|
|
605
|
+
ensureLive(); const normalized = { clipping: value?.clipping ?? value?.clips ?? [], selectedClipIds: value?.selectedClipIds ?? value?.selected ?? [], workPlane: value?.workPlane ?? null, workArea: value?.workArea ?? null };
|
|
606
|
+
adapter.applyClipState(immutable(normalized)); state = transitionViewportState(state, { type: 'section', ...normalized, activeClipGesture: null });
|
|
607
|
+
},
|
|
608
|
+
fitAll() { ensureLive(); const bounds = adapter.bounds('camera-all'); if (bounds) { adapter.fit(immutable({ purpose: 'camera-all', bounds })); state = transitionViewportState(state, { type: 'camera', camera: adapter.cameraState() }); state = transitionViewportState(state, { type: 'fit-complete' }); paint(true); return true; } return false; },
|
|
609
|
+
fitSelection() { ensureLive(); const bounds = adapter.bounds('camera-selection', state.selectedKeys); if (bounds) { adapter.fit(immutable({ purpose: 'camera-selection', bounds })); state = transitionViewportState(state, { type: 'camera', camera: adapter.cameraState() }); state = transitionViewportState(state, { type: 'fit-complete' }); paint(true); return true; } return false; },
|
|
610
|
+
refreshRenderRecords() { ensureLive(); adapter.publishRenderRecords?.(); },
|
|
611
|
+
prepareGeneration({ epoch = rebuildEpoch, namespace } = {}) {
|
|
612
|
+
ensureLive();
|
|
613
|
+
if (typeof identityRegistry.prepareGeneration !== 'function') fail('E_GENERATION_UNSUPPORTED', 'identity registry does not support generation batches');
|
|
614
|
+
const identity = identityRegistry.prepareGeneration({ namespace: namespace ?? `${instanceToken}.generation.${++generationSequence}` });
|
|
615
|
+
let staged = false;
|
|
616
|
+
const handle = Object.freeze({
|
|
617
|
+
token: identity.token, namespace: identity.namespace, identity, epoch,
|
|
618
|
+
stage(payload = {}) {
|
|
619
|
+
const entry = preparedGenerations.get(identity.token);
|
|
620
|
+
if (!entry || entry.status !== 'prepared') fail('E_GENERATION_CLOSED', 'prepared generation is closed');
|
|
621
|
+
if (staged) fail('E_GENERATION_STAGED', 'prepared generation payload is already staged');
|
|
622
|
+
if (payload.dispose !== undefined && typeof payload.dispose !== 'function') fail('E_GENERATION_DISPOSAL', 'prepared generation dispose must be a function');
|
|
623
|
+
if (typeof payload.activate !== 'function') {
|
|
624
|
+
try { payload.dispose?.('invalid'); } catch (_) {}
|
|
625
|
+
fail('E_GENERATION_ACTIVATION', 'prepared generation needs a synchronous activate function');
|
|
626
|
+
}
|
|
627
|
+
staged = true; entry.payload = payload; return handle;
|
|
628
|
+
},
|
|
629
|
+
});
|
|
630
|
+
preparedGenerations.set(identity.token, { handle, identity, status: 'prepared', payload: null });
|
|
631
|
+
return handle;
|
|
632
|
+
},
|
|
633
|
+
commitGeneration(handle, { preparedClear = null } = {}) {
|
|
634
|
+
ensureLive();
|
|
635
|
+
const entry = handle?.token && preparedGenerations.get(handle.token);
|
|
636
|
+
if (!entry || entry.handle !== handle || entry.status !== 'prepared') fail('E_GENERATION_CLOSED', 'prepared generation is unknown or closed');
|
|
637
|
+
if (!entry.payload) fail('E_GENERATION_UNSTAGED', 'prepared generation has no staged payload');
|
|
638
|
+
if (Number.isSafeInteger(handle.epoch) && handle.epoch !== rebuildEpoch) { closePreparedGeneration(entry, 'stale'); fail('E_STALE_GENERATION', 'prepared generation epoch is stale'); }
|
|
639
|
+
const nextRecords = normalizedGenerationRecords(entry);
|
|
640
|
+
// All fallible registry work must finish before the adapter changes the live scene.
|
|
641
|
+
// commitGeneration can therefore remain a synchronous, no-await activation boundary.
|
|
642
|
+
identityRegistry.validateGeneration?.(entry.identity);
|
|
643
|
+
if (selectionCoordinator) {
|
|
644
|
+
if (!preparedClear) fail('E_GENERATION_PREPARED_CLEAR', 'generation commit needs a coordinator-owned prepared clear');
|
|
645
|
+
selectionCoordinator.validatePreparedClear(preparedClear);
|
|
646
|
+
if (preparedClear.namespace !== handle.namespace) fail('E_GENERATION_PREPARED_CLEAR', 'prepared clear belongs to another namespace');
|
|
647
|
+
} else if (selectionCommit.keys.length) {
|
|
648
|
+
fail('E_GENERATION_SELECTION_COORDINATOR', 'a selected viewport needs its selection coordinator for generation replacement');
|
|
649
|
+
}
|
|
650
|
+
const wasInputActive = state.inputActive;
|
|
651
|
+
broker?.cancel('generation-commit');
|
|
652
|
+
state = transitionViewportState(state, { type: 'input', active: false });
|
|
653
|
+
try {
|
|
654
|
+
// The adapter promised this activation was prevalidated and synchronous. Registry/records
|
|
655
|
+
// remain untouched if it throws, so the old generation stays authoritative.
|
|
656
|
+
entry.payload.activate();
|
|
657
|
+
} catch (error) {
|
|
658
|
+
if (wasInputActive) state = transitionViewportState(state, { type: 'input', active: true });
|
|
659
|
+
closePreparedGeneration(entry, 'activation-failure');
|
|
660
|
+
throw error;
|
|
661
|
+
}
|
|
662
|
+
identityRegistry.commitGeneration(entry.identity);
|
|
663
|
+
const oldGeneration = activeGeneration;
|
|
664
|
+
records = nextRecords;
|
|
665
|
+
renderEpoch++;
|
|
666
|
+
activeGeneration = { namespace: handle.namespace, token: handle.token, dispose: entry.payload.dispose ?? null };
|
|
667
|
+
entry.status = 'committed'; preparedGenerations.delete(handle.token);
|
|
668
|
+
if (selectionCoordinator) {
|
|
669
|
+
selectionCommit = selectionCoordinator.consumePreparedClear(preparedClear);
|
|
670
|
+
state = transitionViewportState(state, { type: 'selection', keys: selectionCommit.keys, primaryKey: selectionCommit.primaryKey });
|
|
671
|
+
}
|
|
672
|
+
if (state.hoverKey) state = transitionViewportState(state, { type: 'hover', key: null });
|
|
673
|
+
applyPresentation(); publishState();
|
|
674
|
+
if (wasInputActive) state = transitionViewportState(state, { type: 'input', active: true });
|
|
675
|
+
const disposalErrors = [];
|
|
676
|
+
try { oldGeneration?.dispose?.('replaced'); } catch (error) { disposalErrors.push(error); }
|
|
677
|
+
return immutable({ namespace: handle.namespace, recordCount: records.size, selectionRevision: selectionCommit.revision, disposalErrors });
|
|
678
|
+
},
|
|
679
|
+
setInputActive(active) { ensureLive(); state = transitionViewportState(state, { type: 'input', active }); },
|
|
680
|
+
cameraState() { return state.camera; },
|
|
681
|
+
displayMode() { return state.displayMode; },
|
|
682
|
+
sectionState() { return immutable({ clipping: state.clipping, workPlane: state.workPlane, workArea: state.workArea, activeClipGesture: state.activeClipGesture }); },
|
|
683
|
+
getState() { ensureLive(); return editorState(); },
|
|
684
|
+
subscribe(listener) {
|
|
685
|
+
ensureLive();
|
|
686
|
+
if (typeof listener !== 'function') fail('E_VIEWPORT_SUBSCRIBER', 'viewport subscriber must be a function');
|
|
687
|
+
stateSubscribers.add(listener);
|
|
688
|
+
try { listener(editorState()); } catch (_) {}
|
|
689
|
+
let live = true;
|
|
690
|
+
return () => { if (!live) return false; live = false; return stateSubscribers.delete(listener); };
|
|
691
|
+
},
|
|
692
|
+
state() { return state; },
|
|
693
|
+
instanceToken() { return instanceToken; },
|
|
694
|
+
identityRegistry() { return identityRegistry; },
|
|
695
|
+
dispose() {
|
|
696
|
+
if (disposed) return { errors: [] };
|
|
697
|
+
disposed = true; rebuildEpoch++; rebuildAbort?.abort();
|
|
698
|
+
const errors = [];
|
|
699
|
+
const attempt = (fn) => { try { fn(); } catch (error) { errors.push(error); } };
|
|
700
|
+
attempt(() => broker?.cancel('dispose'));
|
|
701
|
+
attempt(() => loopFrame?.cancel()); loopFrame = null;
|
|
702
|
+
attempt(() => resizeFrame?.cancel()); resizeFrame = null;
|
|
703
|
+
attempt(() => observerRelease?.()); observerRelease = null;
|
|
704
|
+
attempt(() => broker?.dispose()); broker = null;
|
|
705
|
+
paint(false);
|
|
706
|
+
if (mounted) attempt(() => adapter.unmount()); mounted = false;
|
|
707
|
+
for (const entry of [...preparedGenerations.values()]) for (const error of closePreparedGeneration(entry, 'dispose')) errors.push(error);
|
|
708
|
+
attempt(() => activeGeneration?.dispose?.('dispose')); activeGeneration = null;
|
|
709
|
+
attempt(() => adapter.dispose());
|
|
710
|
+
records.clear(); identityRegistry.clear(); surface = null;
|
|
711
|
+
state = transitionViewportState(state, { type: 'dispose' });
|
|
712
|
+
publishState(); stateSubscribers.clear();
|
|
713
|
+
return { errors };
|
|
714
|
+
},
|
|
715
|
+
};
|
|
716
|
+
return Object.freeze(api);
|
|
717
|
+
}
|