@floless/app 0.138.1 → 0.139.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/autostart.mjs +6 -2
  2. package/desktop-access-production-manifest.mjs +7 -0
  3. package/dist/floless-server.cjs +157133 -70500
  4. package/dist/schemas/model.continuation.v1.schema.json +19 -0
  5. package/dist/schemas/model.continuation.v2.schema.json +19 -0
  6. package/dist/schemas/model.query-response.v1.schema.json +95 -0
  7. package/dist/schemas/model.query-response.v2.schema.json +80 -0
  8. package/dist/schemas/model.query.v1.schema.json +87 -0
  9. package/dist/schemas/model.query.v2.schema.json +87 -0
  10. package/dist/schemas/model.snap-candidate.v1.schema.json +48 -0
  11. package/dist/schemas/model.snap-constraint.v1.schema.json +18 -0
  12. package/dist/schemas/model.snap-query.v1.schema.json +24 -0
  13. package/dist/schemas/model.snap-result.v1.schema.json +33 -0
  14. package/dist/schemas/model.snapshot.v1.schema.json +136 -0
  15. package/dist/schemas/revit.model.v1.schema.json +24 -0
  16. package/dist/schemas/steel.model.v2.schema.json +45 -6
  17. package/dist/skills/floless-app-approval/SKILL.md +19 -5
  18. package/dist/skills/floless-app-bridge/SKILL.md +19 -6
  19. package/dist/skills/floless-app-knowledge/SKILL.md +22 -1
  20. package/dist/skills/floless-app-new-workflow/SKILL.md +31 -27
  21. package/dist/skills/floless-app-new-workflow/references/build-and-verify.md +13 -12
  22. package/dist/skills/floless-app-onboarding/SKILL.md +3 -3
  23. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +16 -9
  24. package/dist/skills/floless-app-steel-model/SKILL.md +11 -2
  25. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +95 -0
  26. package/dist/skills/floless-app-steel-takeoff/SKILL.md +146 -21
  27. package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +19 -0
  28. package/dist/skills/floless-app-tweak-contract/SKILL.md +42 -8
  29. package/dist/skills/floless-app-vectorize/SKILL.md +19 -6
  30. package/dist/skills/floless-app-workflows/SKILL.md +30 -3
  31. package/dist/skills/floless-app-workflows/references/workspace-data.md +77 -4
  32. package/dist/templates/floless-workspace-model-report.flo +77 -0
  33. package/dist/templates/revit-model.flo +111 -0
  34. package/dist/web/app.css +415 -177
  35. package/dist/web/app.js +302 -51
  36. package/dist/web/aware.js +1430 -1040
  37. package/dist/web/chat.css +692 -0
  38. package/dist/web/chat.js +2651 -0
  39. package/dist/web/commands-revit.js +42 -0
  40. package/dist/web/commands-shell.js +536 -70
  41. package/dist/web/commands-steel.js +344 -146
  42. package/dist/web/commands.js +1 -1
  43. package/dist/web/index.html +283 -77
  44. package/dist/web/instructor.js +217 -36
  45. package/dist/web/left-pane.js +636 -0
  46. package/dist/web/model-artifact-loader.js +75 -0
  47. package/dist/web/model-authoring-gestures.js +141 -0
  48. package/dist/web/model-cad-tools.js +20 -0
  49. package/dist/web/model-clip-gesture.js +148 -0
  50. package/dist/web/model-clip-list.js +156 -0
  51. package/dist/web/model-clip-session.js +274 -0
  52. package/dist/web/model-clip-three-overlay.js +295 -0
  53. package/dist/web/model-clip-three-preview.js +59 -0
  54. package/dist/web/model-editor-contract.js +519 -0
  55. package/dist/web/model-editor-revit-adapter.js +139 -0
  56. package/dist/web/model-editor-shell.js +271 -0
  57. package/dist/web/model-editor-state-recovery.js +44 -0
  58. package/dist/web/model-editor-steel-adapter.js +410 -0
  59. package/dist/web/model-editor.css +268 -0
  60. package/dist/web/model-frame.js +192 -0
  61. package/dist/web/model-inspector.js +128 -0
  62. package/dist/web/model-measure.js +390 -0
  63. package/dist/web/model-navigation-controls.js +246 -0
  64. package/dist/web/model-orientation-overlay.js +217 -0
  65. package/dist/web/model-panel-bridge.js +230 -0
  66. package/dist/web/model-pointer-dock.js +164 -0
  67. package/dist/web/model-revit-module.js +83 -0
  68. package/dist/web/model-selection-coordinator.js +151 -0
  69. package/dist/web/model-selection-tools.js +290 -0
  70. package/dist/web/model-snap-contract.js +267 -0
  71. package/dist/web/model-snapping.js +497 -0
  72. package/dist/web/model-spatial-panel.js +294 -0
  73. package/dist/web/model-spatial-tools.js +249 -0
  74. package/dist/web/model-tree.js +47 -0
  75. package/dist/web/model-viewport-lighting.js +166 -0
  76. package/dist/web/model-viewport-revit-adapter.js +1224 -0
  77. package/dist/web/model-viewport-state.js +505 -0
  78. package/dist/web/model-viewport-steel-adapter.js +150 -0
  79. package/dist/web/model-viewport-toolbar.js +516 -0
  80. package/dist/web/model-viewport.js +717 -0
  81. package/dist/web/panels.js +8 -15
  82. package/dist/web/renderers.js +3 -0
  83. package/dist/web/revit-editor.css +35 -0
  84. package/dist/web/revit-editor.html +74 -0
  85. package/dist/web/revit-editor.js +845 -0
  86. package/dist/web/steel-3d-core.js +16 -44
  87. package/dist/web/steel-3d-view.js +1384 -633
  88. package/dist/web/steel-canvas-guidance.js +3 -1
  89. package/dist/web/steel-editor.html +2121 -1253
  90. package/dist/web/steel-filter.html +5 -1
  91. package/dist/web/steel-model-v2-commands.js +72 -1
  92. package/dist/web/steel-split-view.js +5 -39
  93. package/dist/web/steel-view-generation.js +107 -17
  94. package/dist/web/vector-3d.html +12 -0
  95. package/dist/web/workspaces.js +2190 -277
  96. package/distribution-profile-active.mjs +2 -0
  97. package/distribution-profile-production.mjs +47 -0
  98. package/distribution-profile-shared.mjs +8 -0
  99. package/distribution-profile.mjs +18 -0
  100. package/distribution-resource-inventory.mjs +81 -0
  101. package/launch.mjs +18 -10
  102. package/log.mjs +2 -1
  103. package/managed-runtime-policy.mjs +104 -0
  104. package/model-reader-policy-active.mjs +7 -0
  105. package/network-policy-active.mjs +6 -0
  106. package/package.json +17 -2
  107. package/post-update-marker.mjs +3 -1
  108. package/rvt-production-uat-authority.mjs +60 -0
  109. package/teardown.mjs +4 -3
@@ -0,0 +1,390 @@
1
+ import { closestModelSnap } from './model-snapping.js';
2
+ import { FT_TO_MM, IN_TO_MM, projectPointOnSegment2d, SEG_DEGENERACY } from './steel-3d-core.js';
3
+
4
+ const SVG_NS = 'http://www.w3.org/2000/svg';
5
+ const GLOBAL_FRAME = Object.freeze({ id: 'global', label: 'Global', origin: Object.freeze([0, 0, 0]),
6
+ xAxis: Object.freeze([1, 0, 0]), yAxis: Object.freeze([0, 1, 0]), zAxis: Object.freeze([0, 0, 1]) });
7
+ const SNAP_GLYPH = Object.freeze({
8
+ 'mesh-vertex': '□', 'mesh-edge-midpoint': '△', 'mesh-edge-nearest': '⧗', surface: '●',
9
+ 'semantic-endpoint': '□', 'semantic-midpoint': '△', 'semantic-intersection': '×', origin: '◎',
10
+ });
11
+ const SNAP_LABEL = Object.freeze({ 'mesh-vertex': 'Mesh vertex', 'mesh-edge-midpoint': 'Mesh edge midpoint',
12
+ 'mesh-edge-nearest': 'Nearest on mesh edge', surface: 'Mesh surface' });
13
+
14
+ const point3 = (value) => Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);
15
+ const unit = (value) => { const length = Math.hypot(...value); return length > 1e-9 ? value.map((item) => item / length) : null; };
16
+ const dot = (a, b) => a.reduce((sum, item, axis) => sum + item * b[axis], 0);
17
+ const add = (a, b) => a.map((item, axis) => item + b[axis]);
18
+ const scale = (value, scalar) => value.map((item) => item * scalar);
19
+ const clone = (value) => globalThis.structuredClone ? globalThis.structuredClone(value) : JSON.parse(JSON.stringify(value));
20
+
21
+ function normalizePresentation(value = {}) {
22
+ const units = ['mm', 'cm', 'm', 'in', 'ft'].includes(value?.units) ? value.units : 'mm';
23
+ const precision = Number.isInteger(value?.precision) && value.precision >= 0 && value.precision <= 6 ? value.precision : 1;
24
+ const labelPlacement = ['above', 'center', 'below'].includes(value?.labelPlacement) ? value.labelPlacement : 'above';
25
+ return Object.freeze({ units, precision, labelPlacement });
26
+ }
27
+
28
+ function normalizeDimension(value) {
29
+ if (!point3(value?.a) || !point3(value?.b)) throw new TypeError('A dimension needs two finite 3D points.');
30
+ return Object.freeze({
31
+ id: String(value.id || `dimension-${value.a.join(':')}-${value.b.join(':')}`),
32
+ a: Object.freeze([...value.a]), b: Object.freeze([...value.b]), offsetPx: Number.isFinite(value.offsetPx) ? value.offsetPx : 24,
33
+ firstRef: value.firstRef ?? null, secondRef: value.secondRef ?? null,
34
+ firstProviderRef: value.firstProviderRef ?? null, secondProviderRef: value.secondProviderRef ?? null,
35
+ frameId: String(value.frameId || 'global'), locks: Object.freeze([...(value.locks ?? [])].filter((key) => ['x', 'y', 'z'].includes(key))),
36
+ presentation: normalizePresentation(value.presentation),
37
+ });
38
+ }
39
+
40
+ function distanceInUnits(distanceMm, units) {
41
+ if (units === 'cm') return distanceMm / 10;
42
+ if (units === 'm') return distanceMm / 1000;
43
+ if (units === 'in') return distanceMm / IN_TO_MM;
44
+ if (units === 'ft') return distanceMm / FT_TO_MM;
45
+ return distanceMm;
46
+ }
47
+
48
+ function pointSegmentDistance(point, a, b) {
49
+ return projectPointOnSegment2d(point, a, b, SEG_DEGENERACY.atMost(1e-12)).distance;
50
+ }
51
+
52
+ function guidePoints(guide) {
53
+ if (guide?.type === 'point') return [guide.pointMm];
54
+ if (guide?.type === 'segment') return [guide.startMm, guide.endMm];
55
+ if (guide?.type === 'line') return [add(guide.originMm, scale(guide.direction, -1e6)), add(guide.originMm, scale(guide.direction, 1e6))];
56
+ return [];
57
+ }
58
+
59
+ function normalizeAcquisition(value) {
60
+ const point = value?.pointMm ?? value?.point;
61
+ if (!point3(point)) throw Object.assign(new TypeError('Dimension points require a real acquired snap result.'), { code: 'E_MODEL_MEASURE_SNAP_REQUIRED' });
62
+ if (value?.status && value.status !== 'acquired') throw Object.assign(new TypeError('A refused snap cannot become a dimension point.'), { code: 'E_MODEL_MEASURE_SNAP_REQUIRED' });
63
+ return Object.freeze({
64
+ id: String(value.candidateId ?? value.id ?? ''), point: Object.freeze([...point]), kind: value.kind ?? 'free-point',
65
+ providerRef: value.providerRef ?? null, generation: value.generation ?? value.providerRef?.generation ?? null,
66
+ });
67
+ }
68
+
69
+ /**
70
+ * DOM-free dimension lifecycle shared by every renderer. Providers acquire/project points and paint
71
+ * them in SVG or Three; this session is the sole owner of stages, locks, dimensions and presentation.
72
+ * @param {{initialDimensions?:any[],initialPresentation?:any,
73
+ * onChange?:(value:any,reason:string)=>void,onState?:(state:any,reason:string)=>void}} options
74
+ */
75
+ export function createModelMeasureSession({ initialDimensions = [], initialPresentation = null, onChange = () => {}, onState = () => {} } = {}) {
76
+ let armed = false, first = null, second = null, placementOffset = 24, selectedIndex = null, onePickKind = null, visible = true;
77
+ let presentation = normalizePresentation(initialPresentation); const locks = new Set();
78
+ const dimensions = (Array.isArray(initialDimensions) ? initialDimensions : []).map(normalizeDimension);
79
+ let disposed = false, sequence = dimensions.length;
80
+ const live = () => { if (disposed) throw Object.assign(new Error('Model measure session is disposed.'), { code: 'E_MODEL_MEASURE_DISPOSED' }); };
81
+ const state = () => ({ schema: 'floless.model-measure-session/v1', armed, step: !armed ? 0 : !first ? 1 : !second ? 2 : 3,
82
+ hasDraft: !!first, first: first ? clone(first) : null, second: second ? clone(second) : null, placementOffset,
83
+ count: dimensions.length, selectedIndex, onePickKind, visible, presentation: { ...presentation }, locks: [...locks] });
84
+ const publish = (reason, changed = false) => {
85
+ const value = state(); try { onState(clone(value), reason); } catch (_) {}
86
+ if (changed) { try { onChange(api.serialize(), reason); } catch (_) {} }
87
+ return value;
88
+ };
89
+ const clearDraft = () => { first = null; second = null; placementOffset = 24; onePickKind = null; };
90
+ const api = {
91
+ state() { live(); return clone(state()); },
92
+ setArmed(value) { live(); armed = value === true; if (!armed) clearDraft(); return publish('armed'); },
93
+ toggle() { return api.setArmed(!armed); },
94
+ pickPoint(acquisition) {
95
+ live(); if (!armed) throw Object.assign(new Error('Dimension tool is not armed.'), { code: 'E_MODEL_MEASURE_INACTIVE' });
96
+ const point = normalizeAcquisition(acquisition);
97
+ if (!first) first = point;
98
+ else if (!second) {
99
+ if (first.generation && point.generation && JSON.stringify(first.generation) !== JSON.stringify(point.generation)) {
100
+ throw Object.assign(new Error('Dimension points belong to different model generations.'), { code: 'E_MODEL_MEASURE_STALE' });
101
+ }
102
+ second = point;
103
+ } else throw Object.assign(new Error('Place the current dimension before picking another point.'), { code: 'E_MODEL_MEASURE_STAGE' });
104
+ onePickKind = null; return publish('point');
105
+ },
106
+ setPlacementOffset(value) { live(); if (!second || !Number.isFinite(value)) return false; placementOffset = value; publish('placement'); return true; },
107
+ commitPlacement({ frameId = 'global' } = {}) {
108
+ live(); if (!first || !second) throw Object.assign(new Error('A dimension needs two acquired points before placement.'), { code: 'E_MODEL_MEASURE_STAGE' });
109
+ dimensions.push(normalizeDimension({ id: `dimension-${Date.now().toString(36)}-${++sequence}`, a: first.point, b: second.point,
110
+ offsetPx: placementOffset, firstRef: first.id, secondRef: second.id, firstProviderRef: first.providerRef,
111
+ secondProviderRef: second.providerRef, frameId, locks: [...locks], presentation }));
112
+ selectedIndex = dimensions.length - 1; clearDraft(); publish('dimension-add', true); return api.dimension(selectedIndex);
113
+ },
114
+ cancelStep() {
115
+ live(); let rung = 'pass';
116
+ if (onePickKind) { onePickKind = null; rung = 'restriction'; }
117
+ else if (second) { second = null; placementOffset = 24; rung = 'point-2'; }
118
+ else if (first) { first = null; rung = 'point-1'; }
119
+ else if (armed) { armed = false; rung = 'tool'; }
120
+ else if (selectedIndex !== null) { selectedIndex = null; rung = 'selection'; }
121
+ publish('escape'); return rung;
122
+ },
123
+ restrictNextPick(kind) { live(); onePickKind = kind ? String(kind) : null; return publish('restriction'); },
124
+ setAxisLock(kind) { live(); if (kind === 'f') locks.clear(); else if (['x', 'y', 'z'].includes(kind)) { if (locks.has(kind)) locks.delete(kind); else locks.add(kind); } return publish('axis-lock'); },
125
+ clear() { live(); dimensions.splice(0); clearDraft(); selectedIndex = null; return publish('dimensions-clear', true); },
126
+ setVisible(value) { live(); visible = value === true; publish('dimensions-visible', true); return visible; },
127
+ setPresentation(value) { live(); presentation = normalizePresentation({ ...presentation, ...(value ?? {}) }); publish('dimension-presentation', true); return { ...presentation }; },
128
+ update(index, patch) { live(); if (!Number.isInteger(index) || index < 0 || index >= dimensions.length) return false; dimensions[index] = normalizeDimension({ ...dimensions[index], ...(patch ?? {}), presentation: { ...dimensions[index].presentation, ...(patch?.presentation ?? {}) } }); publish('dimension-update', true); return true; },
129
+ remove(index) { live(); if (!Number.isInteger(index) || index < 0 || index >= dimensions.length) return false; dimensions.splice(index, 1); selectedIndex = null; publish('dimension-delete', true); return true; },
130
+ select(index) { live(); selectedIndex = Number.isInteger(index) && index >= 0 && index < dimensions.length ? index : null; publish('dimension-select'); return selectedIndex; },
131
+ dimension(index) { live(); return dimensions[index] ? clone(dimensions[index]) : null; },
132
+ dimensions() { live(); return dimensions.map(clone); },
133
+ serialize() { live(); return { schema: 'floless.model-dimensions/v1', visible, presentation: { ...presentation }, dimensions: dimensions.map(clone) }; },
134
+ dispose() { if (disposed) return; disposed = true; clearDraft(); },
135
+ };
136
+ publish('replay'); return Object.freeze(api);
137
+ }
138
+
139
+ function resolveFrame(viewport) {
140
+ const frame = viewport.activeFrame?.() ?? GLOBAL_FRAME;
141
+ if (!frame || !point3(frame.origin) || ![frame.xAxis, frame.yAxis, frame.zAxis].every(point3)) return GLOBAL_FRAME;
142
+ const axes = [unit(frame.xAxis), unit(frame.yAxis), unit(frame.zAxis)];
143
+ return axes.every(Boolean) ? Object.freeze({ id: frame.id ?? 'provider', label: frame.label ?? 'Provider frame', origin: [...frame.origin],
144
+ xAxis: axes[0], yAxis: axes[1], zAxis: axes[2] }) : GLOBAL_FRAME;
145
+ }
146
+
147
+ function constrainedPoint(anchor, target, lockSet, frame, verticalOnly) {
148
+ const locks = verticalOnly ? ['z'] : [...lockSet];
149
+ if (!locks.length) return [...target];
150
+ const delta = target.map((value, axis) => value - anchor[axis]);
151
+ const axes = { x: frame.xAxis, y: frame.yAxis, z: frame.zAxis };
152
+ return locks.reduce((point, key) => add(point, scale(axes[key], dot(delta, axes[key]))), [...anchor]);
153
+ }
154
+
155
+ /**
156
+ * Session-only, provider-neutral point → point → placement dimension tool.
157
+ * @param {{surface:any,host:any,viewport:any,snapIndex?:()=>any,onState?:(state:any)=>void,
158
+ * onChange?:(value:any,reason:string)=>void,onEditRequest?:((dimension:any,index:number)=>void)|null,
159
+ * initialDimensions?:any[],initialPresentation?:any}} options
160
+ */
161
+ export function mountModelMeasureTool({
162
+ surface, host, viewport, snapIndex = () => null, onState = () => {}, onChange = () => {},
163
+ onEditRequest = null, initialDimensions = [], initialPresentation = null,
164
+ }) {
165
+ if (!surface || !host || !viewport) throw new Error('Model measurement needs a surface, overlay host, and viewport.');
166
+ const svg = document.createElementNS(SVG_NS, 'svg'); svg.classList.add('model-dim-overlay'); svg.setAttribute('aria-hidden', 'true'); host.append(svg);
167
+ const session = createModelMeasureSession({ initialDimensions, initialPresentation, onChange });
168
+ let armed, first, second, placementOffset, selectedIndex, onePickKind, visible, presentation, dimensions, lockSet;
169
+ let hover = null, onePickMenu = null;
170
+ const syncSession = () => {
171
+ const value = session.state(); ({ armed, first, second, placementOffset, selectedIndex, onePickKind, visible, presentation } = value);
172
+ dimensions = session.dimensions(); lockSet = new Set(value.locks); return value;
173
+ };
174
+ syncSession();
175
+ let snapModes = { 'mesh-vertex': true, 'mesh-edge-midpoint': true, 'mesh-edge-nearest': true, surface: true };
176
+ let editor = null;
177
+
178
+ const svgNode = (name, attributes = {}) => {
179
+ const node = document.createElementNS(SVG_NS, name);
180
+ for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, String(value));
181
+ return node;
182
+ };
183
+ const projected = (point) => { const value = viewport.projectPoint(point); return value?.visible ? value : null; };
184
+ const dimensionGeometry = (a, b, offsetPx) => {
185
+ const pa = projected(a), pb = projected(b); if (!pa || !pb) return null;
186
+ const dx = pb.x - pa.x, dy = pb.y - pa.y, length = Math.hypot(dx, dy); if (length < 1e-6) return null;
187
+ const normal = [-dy / length, dx / length];
188
+ const qa = { x: pa.x + normal[0] * offsetPx, y: pa.y + normal[1] * offsetPx };
189
+ const qb = { x: pb.x + normal[0] * offsetPx, y: pb.y + normal[1] * offsetPx };
190
+ return { pa, pb, qa, qb, normal };
191
+ };
192
+ const drawDimension = (dimension, preview = false, selected = false) => {
193
+ const geometry = dimensionGeometry(dimension.a, dimension.b, dimension.offsetPx ?? 0); if (!geometry) return;
194
+ const rect = svg.getBoundingClientRect(); const local = (point) => [point.x - rect.left, point.y - rect.top];
195
+ const group = svgNode('g', { class: `${preview ? 'dimension-preview' : 'dimension-mark'}${selected ? ' selected' : ''}` });
196
+ const [ax, ay] = local(geometry.pa), [bx, by] = local(geometry.pb), [qx, qy] = local(geometry.qa), [rx, ry] = local(geometry.qb);
197
+ if (Math.abs(dimension.offsetPx ?? 0) > 0.5) {
198
+ group.append(svgNode('line', { x1: ax, y1: ay, x2: qx, y2: qy, class: 'dimension-witness' }),
199
+ svgNode('line', { x1: bx, y1: by, x2: rx, y2: ry, class: 'dimension-witness' }));
200
+ }
201
+ group.append(svgNode('line', { x1: qx, y1: qy, x2: rx, y2: ry, class: 'dimension-line' }));
202
+ for (const point of [[qx, qy], [rx, ry]]) group.append(svgNode('line', {
203
+ x1: point[0] - 4, y1: point[1] + 4, x2: point[0] + 4, y2: point[1] - 4, class: 'dimension-tick',
204
+ }));
205
+ const labelDistance = dimension.presentation?.labelPlacement === 'above' ? -8
206
+ : dimension.presentation?.labelPlacement === 'below' ? 16 : 4;
207
+ const label = svgNode('text', { x: (qx + rx) / 2, y: (qy + ry) / 2 + labelDistance });
208
+ const distance = viewport.distanceMm?.(dimension.a, dimension.b) ?? Math.hypot(...dimension.b.map((value, axis) => value - dimension.a[axis]));
209
+ const style = { ...presentation, ...(dimension.presentation ?? {}) };
210
+ const converted = distanceInUnits(distance, style.units);
211
+ label.textContent = `${converted.toLocaleString(undefined, { minimumFractionDigits: style.precision, maximumFractionDigits: style.precision })} ${style.units}`;
212
+ group.append(label); svg.append(group);
213
+ };
214
+ const drawGuide = (guide) => {
215
+ const points = guidePoints(guide).map(projected).filter(Boolean); if (!points.length) return;
216
+ const rect = svg.getBoundingClientRect(); const local = (point) => [point.x - rect.left, point.y - rect.top];
217
+ if (points.length === 1) {
218
+ const [x, y] = local(points[0]); svg.append(svgNode('circle', { cx: x, cy: y, r: 4, class: 'model-snap-guide' })); return;
219
+ }
220
+ const [a, b] = points.map(local); svg.append(svgNode('line', { x1: a[0], y1: a[1], x2: b[0], y2: b[1], class: 'model-snap-guide' }));
221
+ };
222
+ const drawReticle = (acquisition) => {
223
+ if (!acquisition?.screen) return;
224
+ const rect = svg.getBoundingClientRect(); const x = acquisition.screen.x - rect.left, y = acquisition.screen.y - rect.top;
225
+ const group = svgNode('g', { class: 'model-snap-reticle' });
226
+ group.append(svgNode('circle', { cx: x, cy: y, r: 9 }), svgNode('line', { x1: x - 13, y1: y, x2: x + 13, y2: y }),
227
+ svgNode('line', { x1: x, y1: y - 13, x2: x, y2: y + 13 }));
228
+ const glyph = svgNode('text', { x, y: y + 4 }); glyph.textContent = SNAP_GLYPH[acquisition.kind] ?? '•'; group.append(glyph);
229
+ const readout = svgNode('text', { x: x + 15, y: y - 12, class: 'model-snap-readout' });
230
+ readout.textContent = `${acquisition.kind} · ${resolveFrame(viewport).label}`; group.append(readout); svg.append(group);
231
+ };
232
+ const render = () => {
233
+ svg.replaceChildren();
234
+ if (visible) dimensions.forEach((dimension, index) => drawDimension(dimension, false, index === selectedIndex));
235
+ for (const guide of hover?.guides ?? []) drawGuide(guide);
236
+ if (first && hover && !second) drawDimension({ a: first.point, b: hover.point, offsetPx: 0 }, true);
237
+ if (first && second) drawDimension({ a: first.point, b: second.point, offsetPx: placementOffset }, true);
238
+ if (armed && hover) drawReticle(hover);
239
+ };
240
+ const surfaceAcquisition = (event, point) => point && snapModes.surface !== false ? Object.freeze({
241
+ id: 'surface-under-pointer', kind: 'surface', point: Object.freeze([...point]),
242
+ screen: viewport.projectPoint(point), distance: 0, entityId: null,
243
+ }) : null;
244
+ const acquire = (event) => {
245
+ const surfacePoint = viewport.pickSurface(event.clientX, event.clientY); if (!surfacePoint) return null;
246
+ if (event.altKey) return surfaceAcquisition(event, surfacePoint);
247
+ const enabled = onePickKind ? Object.fromEntries(Object.keys(snapModes).map((kind) => [kind, kind === onePickKind])) : snapModes;
248
+ return closestModelSnap(snapIndex(), { x: event.clientX, y: event.clientY }, viewport.projectPoint, enabled, 12, surfacePoint, 256)
249
+ ?? (enabled.surface !== false ? surfaceAcquisition(event, surfacePoint) : null);
250
+ };
251
+ const adjusted = (acquisition, event) => {
252
+ if (!first || !acquisition) return acquisition;
253
+ const frame = resolveFrame(viewport); const point = constrainedPoint(first.point, acquisition.point, lockSet, frame, event.altKey);
254
+ return Object.freeze({ ...acquisition, point: Object.freeze(point), screen: viewport.projectPoint(point), constraint: event.altKey ? 'z' : [...lockSet].join('+') || 'free' });
255
+ };
256
+ const notify = () => {
257
+ const index = snapIndex(); const step = !armed ? 0 : first === null ? 1 : second === null ? 2 : 3;
258
+ const status = index?.available === false ? index.refusal?.message : (step === 1 ? 'Pick point 1' : step === 2 ? 'Pick point 2' : step === 3 ? 'Place dimension'
259
+ : selectedIndex !== null ? 'Dimension selected · Enter to edit · Delete to remove' : (dimensions.length ? `${dimensions.length} placed` : 'Ready'));
260
+ onState({ armed, hasDraft: !!first, step, count: dimensions.length, selectedIndex, status, visible,
261
+ presentation: { ...presentation }, snapModes: { ...snapModes }, locks: [...lockSet],
262
+ activeFrame: resolveFrame(viewport).label, acquired: hover?.kind ?? null, onePickKind });
263
+ };
264
+ const hitDimension = (event) => {
265
+ let best = null;
266
+ dimensions.forEach((dimension, index) => {
267
+ const geometry = dimensionGeometry(dimension.a, dimension.b, dimension.offsetPx ?? 0); if (!geometry) return;
268
+ const distance = pointSegmentDistance([event.clientX, event.clientY], [geometry.qa.x, geometry.qa.y], [geometry.qb.x, geometry.qb.y]);
269
+ if (distance <= 8 && (!best || distance < best.distance)) best = { index, distance };
270
+ });
271
+ return best?.index ?? null;
272
+ };
273
+ const updatePlacement = (event) => {
274
+ const geometry = first && second && dimensionGeometry(first.point, second.point, 0); if (!geometry) return;
275
+ session.setPlacementOffset((event.clientX - geometry.pa.x) * geometry.normal[0] + (event.clientY - geometry.pa.y) * geometry.normal[1]); syncSession();
276
+ };
277
+ const onMove = (event) => {
278
+ if (!armed) return;
279
+ if (second) updatePlacement(event); else hover = adjusted(acquire(event), event);
280
+ render(); notify();
281
+ };
282
+ const onClick = (event) => {
283
+ if (event.button !== 0) return;
284
+ if (!armed) {
285
+ const hit = visible ? hitDimension(event) : null;
286
+ if (hit === null && selectedIndex === null) return;
287
+ event.preventDefault(); event.stopImmediatePropagation(); session.select(hit); syncSession(); render(); notify(); return;
288
+ }
289
+ event.preventDefault(); event.stopImmediatePropagation();
290
+ if (second) {
291
+ session.commitPlacement({ frameId: resolveFrame(viewport).id }); syncSession(); hover = null;
292
+ } else {
293
+ const acquisition = adjusted(acquire(event), event); if (!acquisition) { notify(); return; }
294
+ session.pickPoint(acquisition); syncSession(); if (second) hover = acquisition;
295
+ }
296
+ render(); notify();
297
+ };
298
+ const closeOnePickMenu = () => { onePickMenu?.remove(); onePickMenu = null; };
299
+ const closeEditor = () => { editor?.remove(); editor = null; surface.focus?.(); };
300
+ const requestEdit = (index) => {
301
+ const dimension = api.dimension(index); if (!dimension) return;
302
+ if (typeof onEditRequest === 'function') { onEditRequest(dimension, index); return; }
303
+ closeEditor();
304
+ const dialog = document.createElement('div'); dialog.className = 'model-dimension-editor'; dialog.setAttribute('role', 'dialog');
305
+ dialog.setAttribute('aria-label', 'Dimension presentation');
306
+ const heading = document.createElement('strong'); heading.textContent = 'Dimension'; dialog.append(heading);
307
+ const choice = (label, values, selected, onChoose) => {
308
+ const group = document.createElement('div'); group.className = 'model-dimension-choice'; group.setAttribute('role', 'group'); group.setAttribute('aria-label', label);
309
+ const caption = document.createElement('span'); caption.textContent = label; group.append(caption);
310
+ for (const value of values) {
311
+ const button = document.createElement('button'); button.type = 'button'; button.textContent = String(value); button.dataset.tip = `${label}: ${value}`;
312
+ button.classList.toggle('on', value === selected); button.setAttribute('aria-pressed', String(value === selected));
313
+ button.addEventListener('click', () => { onChoose(value); closeEditor(); requestEdit(index); }); group.append(button);
314
+ }
315
+ dialog.append(group);
316
+ };
317
+ choice('Units', ['mm', 'cm', 'm', 'in', 'ft'], dimension.presentation.units, (units) => api.update(index, { presentation: { units } }));
318
+ choice('Precision', [0, 1, 2, 3, 4], dimension.presentation.precision, (precision) => api.update(index, { presentation: { precision } }));
319
+ choice('Label', ['above', 'center', 'below'], dimension.presentation.labelPlacement, (labelPlacement) => api.update(index, { presentation: { labelPlacement } }));
320
+ const actions = document.createElement('div'); actions.className = 'model-dimension-editor-actions';
321
+ const remove = document.createElement('button'); remove.type = 'button'; remove.textContent = 'Delete'; remove.dataset.tip = 'Delete selected dimension';
322
+ remove.addEventListener('click', () => { api.remove(index); closeEditor(); });
323
+ const done = document.createElement('button'); done.type = 'button'; done.textContent = 'Done'; done.dataset.tip = 'Close dimension settings'; done.addEventListener('click', closeEditor);
324
+ actions.append(remove, done); dialog.append(actions); document.body.append(dialog); editor = dialog; done.focus();
325
+ };
326
+ const onContextMenu = (event) => {
327
+ if (!armed) return;
328
+ event.preventDefault(); event.stopImmediatePropagation(); closeOnePickMenu();
329
+ const menu = document.createElement('div'); menu.className = 'model-snap-one-pick-menu'; menu.setAttribute('role', 'menu');
330
+ menu.style.left = `${event.clientX}px`; menu.style.top = `${event.clientY}px`;
331
+ const heading = document.createElement('div'); heading.className = 'model-snap-one-pick-heading'; heading.textContent = 'Restrict next pick'; menu.append(heading);
332
+ for (const [kind, enabled] of Object.entries(snapModes)) {
333
+ if (enabled === false) continue;
334
+ const button = document.createElement('button'); button.type = 'button'; button.setAttribute('role', 'menuitem');
335
+ button.dataset.snapOnePick = kind; button.textContent = `${SNAP_GLYPH[kind] ?? '•'} ${SNAP_LABEL[kind] ?? kind}`;
336
+ button.addEventListener('click', () => { session.restrictNextPick(kind); syncSession(); closeOnePickMenu(); notify(); }); menu.append(button);
337
+ }
338
+ document.body.append(menu); onePickMenu = menu; menu.querySelector('button')?.focus();
339
+ };
340
+ const setLock = (key) => {
341
+ session.setAxisLock(key); syncSession();
342
+ render(); notify();
343
+ };
344
+ const onKey = (event) => {
345
+ const key = String(event.key || '').toLowerCase();
346
+ if (editor && event.key === 'Escape') { event.preventDefault(); closeEditor(); return; }
347
+ if (key === 'd' && !event.ctrlKey && !event.metaKey && !event.altKey) { event.preventDefault(); api.toggle(); return; }
348
+ if (!armed) {
349
+ if (event.key === 'Delete' && selectedIndex !== null) { event.preventDefault(); session.remove(selectedIndex); syncSession(); render(); notify(); }
350
+ else if (event.key === 'Enter' && selectedIndex !== null) { event.preventDefault(); requestEdit(selectedIndex); }
351
+ else if (event.key === 'Escape' && selectedIndex !== null) { event.preventDefault(); session.select(null); syncSession(); render(); notify(); }
352
+ return;
353
+ }
354
+ if (['f', 'x', 'y', 'z'].includes(key) && !event.ctrlKey && !event.metaKey) { event.preventDefault(); setLock(key); return; }
355
+ if (event.key === 'Delete' && selectedIndex !== null) { event.preventDefault(); session.remove(selectedIndex); syncSession(); render(); notify(); return; }
356
+ if (event.key !== 'Escape') return;
357
+ event.preventDefault();
358
+ if (onePickMenu) closeOnePickMenu();
359
+ // The rung that disarms the tool takes the button's way out: the cursor and the canvas input go with it.
360
+ else if (session.cancelStep() === 'tool') { api.setArmed(false); return; }
361
+ else { syncSession(); hover = null; }
362
+ render(); notify();
363
+ };
364
+ let api;
365
+ const releaseInput = viewport.registerInputTool?.({ pointerMove: onMove, click: onClick, contextMenu: onContextMenu, keyDown: onKey,
366
+ cancel() { if (armed) api?.setArmed(false); } }, { id: 'model-measure', priority: 50, exclusiveGroup: 'model-command' });
367
+ if (typeof releaseInput !== 'function') throw new Error('Model measurement requires the shared CAD input arbiter.');
368
+ const unsubscribe = viewport.onCameraChange?.(render) ?? (() => {});
369
+ api = {
370
+ setArmed(value) { if (value) releaseInput.activate?.(); else releaseInput.deactivate?.(); session.setArmed(value); syncSession(); surface.classList.toggle('measure-armed', armed); if (!armed) { hover = null; closeOnePickMenu(); } render(); notify(); },
371
+ toggle() { api.setArmed(!armed); },
372
+ setSnapMode(kind, value) { if (kind in snapModes) { snapModes = { ...snapModes, [kind]: value === true }; render(); notify(); } },
373
+ setAxisLock(kind) { if (['f', 'x', 'y', 'z'].includes(kind)) setLock(kind); },
374
+ clear() { session.clear(); syncSession(); hover = null; render(); notify(); },
375
+ setVisible(value) { const result = session.setVisible(value); syncSession(); render(); notify(); return result; },
376
+ setPresentation(value) { const result = session.setPresentation(value); syncSession(); render(); notify(); return result; },
377
+ update(index, patch) {
378
+ const result = session.update(index, patch); syncSession(); render(); notify(); return result;
379
+ },
380
+ remove(index) { const result = session.remove(index); syncSession(); render(); notify(); return result; },
381
+ select(index) { const result = session.select(index); syncSession(); render(); notify(); return result; },
382
+ dimension(index) { return session.dimension(index); },
383
+ state() { return { armed, hasDraft: !!first, step: !armed ? 0 : !first ? 1 : !second ? 2 : 3, count: dimensions.length,
384
+ selectedIndex, visible, presentation: { ...presentation }, snapModes: { ...snapModes }, locks: [...lockSet], activeFrame: resolveFrame(viewport).label, onePickKind }; },
385
+ dimensions() { return session.dimensions(); },
386
+ serialize() { return session.serialize(); },
387
+ destroy() { closeOnePickMenu(); closeEditor(); unsubscribe(); releaseInput(); session.dispose(); svg.remove(); },
388
+ };
389
+ notify(); return api;
390
+ }
@@ -0,0 +1,246 @@
1
+ import * as THREE from 'three';
2
+
3
+ // One CAD navigation policy for every model provider. Domain adapters supply geometry and camera
4
+ // state; this module owns the input feel so a Revit model never silently behaves unlike Steel.
5
+ export const MODEL_NAMED_VIEWS = {
6
+ top: Object.freeze([0, 0, 1]), bottom: Object.freeze([0, 0, -1]),
7
+ front: Object.freeze([0, -1, 0]), back: Object.freeze([0, 1, 0]),
8
+ right: Object.freeze([1, 0, 0]), left: Object.freeze([-1, 0, 0]),
9
+ iso: Object.freeze([0.55, -0.8, 0.5]),
10
+ };
11
+ Object.freeze(MODEL_NAMED_VIEWS);
12
+
13
+ export const MODEL_VIEW_KEYS = Object.freeze({ t: 'top', f: 'front', r: 'right', b: 'back', l: 'left' });
14
+
15
+ /** Apply FloLess CAD mouse conventions to an OrbitControls-compatible controller. */
16
+ export function applyCadOrbitPolicy(controls, mouse = THREE.MOUSE) {
17
+ if (!controls) throw new Error('CAD navigation needs OrbitControls.');
18
+ controls.enableDamping = false;
19
+ controls.zoomSpeed = 1.3;
20
+ controls.zoomToCursor = true;
21
+ controls.mouseButtons = { LEFT: null, MIDDLE: mouse.PAN, RIGHT: mouse.ROTATE };
22
+ return controls;
23
+ }
24
+
25
+ const FORWARDED_EVENT_FIELDS = Object.freeze([
26
+ 'pointerId', 'pointerType', 'isPrimary', 'button', 'buttons', 'clientX', 'clientY', 'pageX', 'pageY',
27
+ 'screenX', 'screenY', 'movementX', 'movementY', 'pressure', 'tangentialPressure', 'tiltX', 'tiltY',
28
+ 'twist', 'width', 'height', 'deltaX', 'deltaY', 'deltaZ', 'deltaMode', 'key', 'code', 'location',
29
+ 'repeat', 'ctrlKey', 'shiftKey', 'altKey', 'metaKey',
30
+ ]);
31
+
32
+ function cloneInputEvent(event, type = event.type) {
33
+ try { return new event.constructor(type, event); } catch (_) {
34
+ const clone = new Event(type, { bubbles: false, cancelable: event.cancelable, composed: false });
35
+ for (const field of FORWARDED_EVENT_FIELDS) {
36
+ if (event[field] === undefined) continue;
37
+ try { Object.defineProperty(clone, field, { configurable: true, value: event[field] }); } catch (_) { /* best-effort legacy DOM */ }
38
+ }
39
+ return clone;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * OrbitControls-compatible event target which deliberately owns no browser listeners. The input
45
+ * arbiter forwards only gestures which no active model tool consumed, making its listener order a
46
+ * real architectural boundary rather than a convention individual providers can accidentally break.
47
+ */
48
+ export function createCadOrbitEventProxy(surface) {
49
+ if (!surface) throw new Error('CAD orbit proxy needs a surface.');
50
+ const documentTarget = new EventTarget();
51
+ const elementTarget = new EventTarget();
52
+ Object.defineProperties(elementTarget, {
53
+ ownerDocument: { value: documentTarget },
54
+ style: { get: () => surface.style },
55
+ clientWidth: { get: () => surface.clientWidth },
56
+ clientHeight: { get: () => surface.clientHeight },
57
+ });
58
+ elementTarget.getRootNode = () => documentTarget;
59
+ elementTarget.getBoundingClientRect = () => surface.getBoundingClientRect();
60
+ elementTarget.setPointerCapture = (pointerId) => surface.setPointerCapture?.(pointerId);
61
+ elementTarget.releasePointerCapture = (pointerId) => surface.releasePointerCapture?.(pointerId);
62
+ return Object.freeze({
63
+ element: elementTarget,
64
+ surface: (event) => elementTarget.dispatchEvent(cloneInputEvent(event)),
65
+ document: (event) => documentTarget.dispatchEvent(cloneInputEvent(event)),
66
+ cancel: (event) => elementTarget.dispatchEvent(cloneInputEvent(event, 'pointercancel')),
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Re-pivot orbit/zoom to the depth below the cursor without moving that point off the view axis.
72
+ * `pickPoint` returns a world `[x,y,z]` or null and stays provider-specific.
73
+ */
74
+ function cadRepivotAction({ controls, getCamera, pickPoint, cursor }) {
75
+ return () => {
76
+ const camera = getCamera?.(); const point = cursor();
77
+ const hitPoint = point && pickPoint?.(point[0], point[1]);
78
+ if (!camera || !hitPoint) return;
79
+ camera.updateMatrixWorld?.();
80
+ const hit = new THREE.Vector3().fromArray(hitPoint);
81
+ const forward = camera.getWorldDirection(new THREE.Vector3());
82
+ const depth = hit.sub(camera.position).dot(forward);
83
+ if (depth > 1e-6) controls.target.copy(camera.position).addScaledVector(forward, depth);
84
+ };
85
+ }
86
+
87
+ /** Shared keyboard pan/rotate/named-view behavior. Escape remains owned by the active tool plugin. */
88
+ export function handleCadNavigationKey({ getCamera, getControls, applyView, fitSelection, canFitSelection = () => true, canApplyView = () => true }, event) {
89
+ const arrows = Object.freeze({ ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] });
90
+ if (event.defaultPrevented) return false;
91
+ if (((event.key === ' ' && event.shiftKey) || ((event.key === 'z' || event.key === 'Z') && event.altKey)) && canFitSelection(event)) {
92
+ event.preventDefault(); fitSelection?.(); return true;
93
+ }
94
+ const key = String(event.key || '').toLowerCase(); const namedView = MODEL_VIEW_KEYS[key];
95
+ if (namedView && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && canApplyView(namedView, event)) {
96
+ event.preventDefault(); applyView?.(namedView); return true;
97
+ }
98
+ const arrow = arrows[event.key]; if (!arrow) return false;
99
+ const zUp = new THREE.Vector3(0, 0, 1);
100
+ const camera = getCamera?.(); const controls = getControls?.(); if (!camera || !controls) return false;
101
+ event.preventDefault(); const [horizontal, vertical] = arrow;
102
+ if (event.ctrlKey || event.metaKey || event.shiftKey) {
103
+ const step = Math.PI / (event.shiftKey && !event.ctrlKey && !event.metaKey ? 36 : 12);
104
+ camera.updateMatrix();
105
+ const offset = camera.position.clone().sub(controls.target).applyAxisAngle(zUp, -horizontal * step);
106
+ const right = new THREE.Vector3().crossVectors(offset, zUp);
107
+ if (right.lengthSq() < 1e-9) right.setFromMatrixColumn(camera.matrix, 0);
108
+ right.normalize(); const tilted = offset.clone().applyAxisAngle(right, vertical * step);
109
+ if (Math.abs(tilted.clone().normalize().dot(zUp)) < 0.999) offset.copy(tilted);
110
+ camera.position.copy(controls.target).add(offset); camera.lookAt(controls.target); controls.update(); return true;
111
+ }
112
+ camera.updateMatrix();
113
+ const scale = camera.isOrthographicCamera ? ((camera.top - camera.bottom) / (camera.zoom || 1)) * 0.06 : camera.position.distanceTo(controls.target) * 0.06;
114
+ const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0); const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
115
+ const move = right.multiplyScalar(horizontal * scale).add(up.multiplyScalar(vertical * scale));
116
+ camera.position.add(move); controls.target.add(move); controls.update(); return true;
117
+ }
118
+
119
+ /**
120
+ * Sole surface/window input owner. The common layer decides navigation and listener ordering; a
121
+ * provider plugin receives domain gestures (Steel editing, Revit selection) without mounting a
122
+ * parallel listener set or copying camera behavior.
123
+ */
124
+ export function mountCadInputArbiter({
125
+ surface, controls, mouse = THREE.MOUSE, win = window, getCamera, pickPoint, applyView, fitSelection,
126
+ isActive = () => true, canFitSelection, canApplyView, orbitInput = null, orbitThreshold = 5, plugin = {},
127
+ }) {
128
+ if (!surface || !controls || !win) throw new Error('CAD input arbiter needs a surface, controls, and window.');
129
+ applyCadOrbitPolicy(controls, mouse);
130
+ let cursor = null; let orbitGesture = null; let toolSequence = 0; let pairedClickOwner = null; const removers = [];
131
+ const tools = new Map(); const activeExclusive = new Map();
132
+ const listen = (target, type, callback, options) => {
133
+ target.addEventListener(type, callback, options); removers.push(() => target.removeEventListener(type, callback, options?.capture ?? false));
134
+ };
135
+ const remember = (event) => { if (Number.isFinite(event.clientX) && Number.isFinite(event.clientY)) cursor = [event.clientX, event.clientY]; };
136
+ const repivot = cadRepivotAction({ controls, getCamera, pickPoint, cursor: () => cursor });
137
+ const consumed = (result, event, bubbleBefore = false) => result === true || event.defaultPrevented || (!bubbleBefore && event.cancelBubble === true);
138
+ const invoke = (entry, name, event) => {
139
+ const bubbleBefore = event.cancelBubble === true; const result = entry.plugin?.[name]?.(event);
140
+ if (!consumed(result, event, bubbleBefore)) return false;
141
+ if (!event.defaultPrevented && event.cancelable !== false) event.preventDefault?.();
142
+ return true;
143
+ };
144
+ const dispatch = (name, event, { includeProvider = true } = {}) => {
145
+ for (const entry of [...tools.values()].sort((a, b) => (b.priority - a.priority) || (a.sequence - b.sequence))) {
146
+ if (invoke(entry, name, event)) return entry;
147
+ }
148
+ if (!includeProvider) return null;
149
+ const providerEntry = { id: 'provider', plugin };
150
+ return invoke(providerEntry, name, event) ? providerEntry : null;
151
+ };
152
+ const surfaceEvent = (name, rememberCursor = false) => (event) => { if (rememberCursor) remember(event); dispatch(name, event); };
153
+ const beginOrbit = (event) => {
154
+ if (!orbitInput || !isActive() || event.defaultPrevented) return;
155
+ const isTouch = event.pointerType === 'touch';
156
+ if (!isTouch && event.button !== 1 && event.button !== 2) return;
157
+ orbitGesture = { pointerId: event.pointerId, button: event.button, x: event.clientX, y: event.clientY, pending: !isTouch && event.button === 2, down: event };
158
+ if (!orbitGesture.pending) orbitInput.surface(event);
159
+ };
160
+ listen(surface, 'pointerdown', (event) => {
161
+ remember(event); pairedClickOwner = null;
162
+ const owner = dispatch('pointerDown', event);
163
+ if (owner && event.button === 0) pairedClickOwner = { entry: owner, pointerId: event.pointerId };
164
+ beginOrbit(event);
165
+ }, { capture: true });
166
+ listen(surface, 'pointermove', surfaceEvent('pointerMove', true));
167
+ listen(surface, 'pointerenter', surfaceEvent('pointerEnter', true));
168
+ listen(surface, 'pointerleave', surfaceEvent('pointerLeave'));
169
+ listen(surface, 'pointercancel', (event) => {
170
+ dispatch('pointerCancel', event);
171
+ if (pairedClickOwner?.pointerId === event.pointerId) pairedClickOwner = null;
172
+ if (orbitGesture?.pointerId === event.pointerId && !orbitGesture.pending) orbitInput?.surface(event);
173
+ if (orbitGesture?.pointerId === event.pointerId) orbitGesture = null;
174
+ });
175
+ listen(surface, 'click', (event) => {
176
+ remember(event);
177
+ if (pairedClickOwner) {
178
+ const owner = pairedClickOwner; pairedClickOwner = null;
179
+ if (owner.entry.id === 'provider' || tools.get(owner.entry.id) === owner.entry) invoke(owner.entry, 'click', event);
180
+ event.preventDefault();
181
+ return;
182
+ }
183
+ dispatch('click', event);
184
+ });
185
+ listen(surface, 'dblclick', surfaceEvent('doubleClick', true));
186
+ listen(surface, 'wheel', (event) => {
187
+ remember(event); dispatch('wheel', event);
188
+ if (orbitInput && isActive() && !event.defaultPrevented) { event.preventDefault(); orbitInput.surface(event); }
189
+ }, { capture: true, passive: false });
190
+ listen(surface, 'contextmenu', (event) => { dispatch('contextMenu', event); event.preventDefault(); });
191
+ listen(win, 'pointermove', (event) => {
192
+ dispatch('windowPointerMove', event);
193
+ if (!orbitInput || !orbitGesture || orbitGesture.pointerId !== event.pointerId || event.defaultPrevented) return;
194
+ if (orbitGesture.pending) {
195
+ const distance = Math.hypot(event.clientX - orbitGesture.x, event.clientY - orbitGesture.y);
196
+ if (distance <= orbitThreshold) return;
197
+ orbitGesture.pending = false; orbitInput.surface(orbitGesture.down);
198
+ }
199
+ orbitInput.document(event);
200
+ });
201
+ listen(win, 'pointerup', (event) => {
202
+ dispatch('windowPointerUp', event);
203
+ if (!orbitInput || !orbitGesture || orbitGesture.pointerId !== event.pointerId) return;
204
+ if (!orbitGesture.pending) orbitInput.document(event);
205
+ orbitGesture = null;
206
+ });
207
+ listen(win, 'blur', (event) => {
208
+ if (orbitGesture && !orbitGesture.pending) orbitInput?.cancel(orbitGesture.down);
209
+ orbitGesture = null; pairedClickOwner = null; dispatch('windowBlur', event);
210
+ });
211
+ listen(win, 'keydown', (event) => {
212
+ if (!isActive()) return;
213
+ if (event.defaultPrevented || event.cancelBubble === true) return;
214
+ const active = win.document?.activeElement; if (active && /^(INPUT|SELECT|TEXTAREA)$/.test(active.tagName)) return;
215
+ dispatch('keyDown', event);
216
+ if (event.key === 'Escape' && orbitGesture) {
217
+ if (!orbitGesture.pending) orbitInput?.cancel(orbitGesture.down);
218
+ orbitGesture = null;
219
+ }
220
+ if (orbitInput && !event.defaultPrevented) orbitInput.document(event);
221
+ if (!event.defaultPrevented) handleCadNavigationKey({ getCamera, getControls: () => controls, applyView, fitSelection, canFitSelection, canApplyView }, event);
222
+ });
223
+ listen(win, 'keyup', (event) => { dispatch('keyUp', event); if (orbitInput && !event.defaultPrevented) orbitInput.document(event); });
224
+ controls.addEventListener('start', repivot); removers.push(() => controls.removeEventListener('start', repivot));
225
+ const orbitStart = () => plugin.orbitStart?.(); controls.addEventListener('start', orbitStart); removers.push(() => controls.removeEventListener('start', orbitStart));
226
+ const orbitChange = () => plugin.orbitChange?.(); controls.addEventListener('change', orbitChange); removers.push(() => controls.removeEventListener('change', orbitChange));
227
+ return Object.freeze({
228
+ registerTool(value, options = {}) {
229
+ if (!value || typeof value !== 'object') throw new TypeError('CAD input tool must be an object.');
230
+ const id = String(options.id || `cad-tool-${++toolSequence}`);
231
+ if (tools.has(id)) throw new Error(`CAD input tool ${id} is already registered.`);
232
+ const entry = { id, plugin: value, priority: Number(options.priority) || 0, exclusiveGroup: options.exclusiveGroup || null, sequence: toolSequence };
233
+ tools.set(id, entry);
234
+ const release = () => { tools.delete(id); if (entry.exclusiveGroup && activeExclusive.get(entry.exclusiveGroup) === id) activeExclusive.delete(entry.exclusiveGroup); };
235
+ release.activate = () => {
236
+ if (!entry.exclusiveGroup) return true;
237
+ const previous = tools.get(activeExclusive.get(entry.exclusiveGroup));
238
+ if (previous && previous !== entry) previous.plugin?.cancel?.('exclusive-tool');
239
+ activeExclusive.set(entry.exclusiveGroup, id); return true;
240
+ };
241
+ release.deactivate = () => { if (entry.exclusiveGroup && activeExclusive.get(entry.exclusiveGroup) === id) activeExclusive.delete(entry.exclusiveGroup); };
242
+ return release;
243
+ },
244
+ destroy() { for (const entry of tools.values()) entry.plugin?.cancel?.('destroy'); tools.clear(); activeExclusive.clear(); orbitGesture = null; pairedClickOwner = null; for (const remove of removers.splice(0).reverse()) remove(); },
245
+ });
246
+ }