@floless/app 0.138.2 → 0.139.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +157207 -70887
  4. package/dist/schemas/model.continuation.v1.schema.json +19 -0
  5. package/dist/schemas/model.continuation.v2.schema.json +19 -0
  6. package/dist/schemas/model.query-response.v1.schema.json +95 -0
  7. package/dist/schemas/model.query-response.v2.schema.json +80 -0
  8. package/dist/schemas/model.query.v1.schema.json +87 -0
  9. package/dist/schemas/model.query.v2.schema.json +87 -0
  10. package/dist/schemas/model.snap-candidate.v1.schema.json +48 -0
  11. package/dist/schemas/model.snap-constraint.v1.schema.json +18 -0
  12. package/dist/schemas/model.snap-query.v1.schema.json +24 -0
  13. package/dist/schemas/model.snap-result.v1.schema.json +33 -0
  14. package/dist/schemas/model.snapshot.v1.schema.json +136 -0
  15. package/dist/schemas/revit.model.v1.schema.json +24 -0
  16. package/dist/schemas/steel.model.v2.schema.json +45 -6
  17. package/dist/skills/floless-app-approval/SKILL.md +19 -5
  18. package/dist/skills/floless-app-bridge/SKILL.md +19 -6
  19. package/dist/skills/floless-app-knowledge/SKILL.md +22 -1
  20. package/dist/skills/floless-app-new-workflow/SKILL.md +31 -27
  21. package/dist/skills/floless-app-new-workflow/references/build-and-verify.md +13 -12
  22. package/dist/skills/floless-app-onboarding/SKILL.md +3 -3
  23. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +16 -9
  24. package/dist/skills/floless-app-steel-model/SKILL.md +11 -2
  25. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +95 -0
  26. package/dist/skills/floless-app-steel-takeoff/SKILL.md +142 -21
  27. package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +19 -0
  28. package/dist/skills/floless-app-tweak-contract/SKILL.md +42 -8
  29. package/dist/skills/floless-app-vectorize/SKILL.md +19 -6
  30. package/dist/skills/floless-app-workflows/SKILL.md +30 -3
  31. package/dist/skills/floless-app-workflows/references/workspace-data.md +77 -4
  32. package/dist/templates/floless-workspace-model-report.flo +77 -0
  33. package/dist/templates/revit-model.flo +111 -0
  34. package/dist/web/app.css +415 -177
  35. package/dist/web/app.js +302 -51
  36. package/dist/web/aware.js +1357 -1032
  37. package/dist/web/chat.css +692 -0
  38. package/dist/web/chat.js +2651 -0
  39. package/dist/web/commands-revit.js +42 -0
  40. package/dist/web/commands-shell.js +531 -70
  41. package/dist/web/commands-steel.js +344 -146
  42. package/dist/web/commands.js +1 -1
  43. package/dist/web/index.html +283 -77
  44. package/dist/web/instructor.js +217 -36
  45. package/dist/web/left-pane.js +636 -0
  46. package/dist/web/model-artifact-loader.js +75 -0
  47. package/dist/web/model-authoring-gestures.js +141 -0
  48. package/dist/web/model-cad-tools.js +20 -0
  49. package/dist/web/model-clip-gesture.js +148 -0
  50. package/dist/web/model-clip-list.js +156 -0
  51. package/dist/web/model-clip-session.js +274 -0
  52. package/dist/web/model-clip-three-overlay.js +295 -0
  53. package/dist/web/model-clip-three-preview.js +59 -0
  54. package/dist/web/model-editor-contract.js +519 -0
  55. package/dist/web/model-editor-revit-adapter.js +139 -0
  56. package/dist/web/model-editor-shell.js +271 -0
  57. package/dist/web/model-editor-state-recovery.js +44 -0
  58. package/dist/web/model-editor-steel-adapter.js +415 -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 +2145 -1255
  90. package/dist/web/steel-filter.html +5 -1
  91. package/dist/web/steel-model-v2-commands.js +80 -3
  92. package/dist/web/steel-split-view.js +5 -39
  93. package/dist/web/steel-view-generation.js +107 -17
  94. package/dist/web/vector-3d.html +12 -0
  95. package/dist/web/workspaces.js +2154 -283
  96. package/distribution-profile-active.mjs +2 -0
  97. package/distribution-profile-production.mjs +47 -0
  98. package/distribution-profile-shared.mjs +8 -0
  99. package/distribution-profile.mjs +18 -0
  100. package/distribution-resource-inventory.mjs +81 -0
  101. package/launch.mjs +18 -10
  102. package/log.mjs +2 -1
  103. package/managed-runtime-policy.mjs +104 -0
  104. package/model-reader-policy-active.mjs +7 -0
  105. package/network-policy-active.mjs +6 -0
  106. package/package.json +17 -2
  107. package/post-update-marker.mjs +3 -1
  108. package/rvt-production-uat-authority.mjs +60 -0
  109. package/teardown.mjs +4 -3
@@ -0,0 +1,83 @@
1
+ /* The Revit-specific Explorer taxonomy; shared shells do not know these domain labels. */
2
+ export const revitExplorerTabs = Object.freeze([
3
+ Object.freeze({ key: 'model', bodyId: 'revitExplorerClassification' }),
4
+ Object.freeze({ key: 'levels', bodyId: 'revitExplorerLevels' }),
5
+ Object.freeze({ key: 'categories', bodyId: 'revitExplorerCategories' }),
6
+ Object.freeze({ key: 'types', bodyId: 'revitExplorerTypes' }),
7
+ ]);
8
+
9
+ const supplied = (value, fallback) => typeof value === 'string' && value.trim() ? value : fallback;
10
+ const compareText = (left, right) => left.localeCompare(right, undefined, { numeric: true, sensitivity: 'base' });
11
+
12
+ function bucket(values, descriptor) {
13
+ const groups = new Map();
14
+ for (const entity of values) {
15
+ const label = supplied(descriptor.label(entity), descriptor.missing);
16
+ const sourceId = supplied(descriptor.id?.(entity), '');
17
+ // Level and Type carry source ids. Category and Family do not, so their identity is explicitly
18
+ // only a convenience grouping by provider-supplied display name.
19
+ const key = sourceId ? `${descriptor.kind}:id:${sourceId}` : `${descriptor.kind}:name:${label}`;
20
+ const current = groups.get(key) || { key, kind: descriptor.kind, label, groupedByName: !sourceId, values: [] };
21
+ current.values.push(entity); groups.set(key, current);
22
+ }
23
+ return [...groups.values()].sort((left, right) => compareText(left.label, right.label) || compareText(left.key, right.key));
24
+ }
25
+
26
+ const CLASSIFICATION = Object.freeze([
27
+ Object.freeze({ kind: 'level', label: (e) => e.levelName, id: (e) => e.levelId, missing: 'No level supplied' }),
28
+ Object.freeze({ kind: 'category', label: (e) => e.categoryName ?? e.category, missing: 'No category supplied' }),
29
+ Object.freeze({ kind: 'family', label: (e) => e.familyName ?? e.family, missing: 'No family supplied' }),
30
+ Object.freeze({ kind: 'type', label: (e) => e.typeName, id: (e) => e.typeId, missing: 'No type supplied' }),
31
+ ]);
32
+
33
+ /** Build an honest convenience index. These nodes are classifications, never signed relationships. */
34
+ export function buildRevitClassificationTree(entities) {
35
+ const build = (values, depth) => {
36
+ if (depth === CLASSIFICATION.length) {
37
+ return [...values]
38
+ .sort((left, right) => compareText(supplied(left.name, left.id), supplied(right.name, right.id)))
39
+ .map((entity) => ({ key: `element:${entity.id}`, kind: 'element', label: supplied(entity.name, supplied(entity.typeName, entity.id)), entityId: entity.id, children: [] }));
40
+ }
41
+ return bucket(values, CLASSIFICATION[depth]).map((node) => ({
42
+ key: node.key, kind: node.kind, label: node.label, groupedByName: node.groupedByName,
43
+ children: build(node.values, depth + 1),
44
+ }));
45
+ };
46
+ return build(Array.isArray(entities) ? entities : [], 0);
47
+ }
48
+
49
+ /** Source-ordered selected-entity parameter groups with the value provenance kept intact. */
50
+ export function groupRevitProperties(rows) {
51
+ const groups = new Map();
52
+ for (const row of Array.isArray(rows) ? rows : []) {
53
+ const ordinal = Number.isSafeInteger(row.groupOrdinal) ? row.groupOrdinal : Number.MAX_SAFE_INTEGER;
54
+ const key = `${ordinal}\0${supplied(row.groupId, supplied(row.groupName, 'Properties'))}`;
55
+ const group = groups.get(key) || { key, id: row.groupId || null, name: supplied(row.groupName, 'Properties'), ordinal, rows: [] };
56
+ group.rows.push(row); groups.set(key, group);
57
+ }
58
+ return [...groups.values()]
59
+ .sort((left, right) => left.ordinal - right.ordinal || compareText(left.name, right.name))
60
+ .map((group) => ({ ...group, rows: group.rows.slice().sort((left, right) => {
61
+ const a = Number.isSafeInteger(left.parameterOrdinal) ? left.parameterOrdinal : Number.MAX_SAFE_INTEGER;
62
+ const b = Number.isSafeInteger(right.parameterOrdinal) ? right.parameterOrdinal : Number.MAX_SAFE_INTEGER;
63
+ return a - b || compareText(supplied(left.name, left.parameterId), supplied(right.name, right.parameterId));
64
+ }) }));
65
+ }
66
+
67
+ /** Literal, selected-entity-only filtering; no regex execution over provider values. */
68
+ export function filterRevitPropertyGroups(groups, query) {
69
+ const needle = String(query || '').trim().toLocaleLowerCase();
70
+ if (!needle) return groups;
71
+ const includes = (value) => String(value ?? '').toLocaleLowerCase().includes(needle);
72
+ return groups.map((group) => ({
73
+ ...group,
74
+ rows: group.rows.filter((row) => [group.name, row.name, row.value, row.unit].some(includes)),
75
+ })).filter((group) => group.rows.length > 0);
76
+ }
77
+
78
+ export function revitPropertyEncodingLabel(row) {
79
+ if (row?.valueEncoding === 'provider-display') return 'Provider display';
80
+ if (row?.valueEncoding === 'source-storage') return `Source ${supplied(row.storageType, 'value')}`;
81
+ // V1 snapshots predate the explicit discriminator and are source-semantic by contract.
82
+ return row?.storageType ? `Source ${row.storageType}` : 'Imported value';
83
+ }
@@ -0,0 +1,151 @@
1
+ /*
2
+ * Durable page-side model selection.
3
+ *
4
+ * The viewport may be absent, hidden or disposed, so the application owns ordered canonical keys and
5
+ * primary intent. Providers receive immutable commits; they never become the source of application
6
+ * selection truth.
7
+ */
8
+ import { applySelectionProposal, validateSelectionCommit } from './model-viewport-state.js';
9
+
10
+ const frozen = (value) => Object.freeze(Array.isArray(value) ? value.map(frozen) : (
11
+ value && typeof value === 'object'
12
+ ? Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, frozen(item)])))
13
+ : value
14
+ ));
15
+
16
+ const normalizeKinds = (value) => new Set(Array.isArray(value) ? value : [value]);
17
+
18
+ /** @param {{registry: any, onCommit?: (commit: any, entries: any[]) => void, onPublicationError?: (error: unknown) => void}} options */
19
+ export function createModelSelectionCoordinator({ registry, onCommit = () => {}, onPublicationError = (error) => console.error('model selection subscriber failed', error) }) {
20
+ if (!registry?.registerSync || !registry?.has) throw new Error('createModelSelectionCoordinator: a current identity registry is required');
21
+ if (typeof onCommit !== 'function') throw new Error('createModelSelectionCoordinator: onCommit must be a function');
22
+ if (typeof onPublicationError !== 'function') throw new Error('createModelSelectionCoordinator: onPublicationError must be a function');
23
+ let entries = [];
24
+ let current = frozen({ revision: 0, origin: 'programmatic', operation: 'clear', keys: [], primaryKey: null });
25
+ let preparedSequence = 0;
26
+ const preparedClears = new Map();
27
+ const publicationErrors = [];
28
+
29
+ const entity = (value) => {
30
+ if (!value || typeof value.kind !== 'string' || typeof value.sourceId !== 'string') {
31
+ throw new Error('selection entity needs string kind and sourceId');
32
+ }
33
+ const receipt = registry.registerSync(value.kind, value.sourceId);
34
+ return frozen({ kind: value.kind, sourceId: value.sourceId, key: receipt.key, generation: receipt.generation,
35
+ namespace: registry.namespaceOf?.(receipt.key) ?? registry.currentNamespace?.() ?? null });
36
+ };
37
+ const unique = (values) => {
38
+ const out = [], seen = new Set();
39
+ for (const value of values) {
40
+ const item = entity(value);
41
+ if (!seen.has(item.key)) { seen.add(item.key); out.push(item); }
42
+ }
43
+ return out;
44
+ };
45
+ const notify = () => {
46
+ try { onCommit(current, frozen(entries)); }
47
+ catch (error) {
48
+ publicationErrors.push(error);
49
+ try { onPublicationError(error); } catch (_) { /* reporting is isolated too */ }
50
+ }
51
+ };
52
+ const publish = (origin, operation, preferredPrimary = null) => {
53
+ const keys = entries.map((item) => item.key);
54
+ const primaryKey = keys.length ? (keys.includes(preferredPrimary) ? preferredPrimary : keys.at(-1)) : null;
55
+ current = validateSelectionCommit({
56
+ revision: current.revision + 1, origin, operation: keys.length ? operation : 'clear', keys, primaryKey,
57
+ }, { previousRevision: current.revision, registry });
58
+ notify();
59
+ return current;
60
+ };
61
+
62
+ const validatePrepared = (prepared) => {
63
+ const token = prepared?.token;
64
+ const stored = token && preparedClears.get(token);
65
+ if (!stored || stored.prepared !== prepared) throw Object.assign(new Error('prepared selection clear is unknown or already consumed'), { code: 'E_PREPARED_CLEAR_CONSUMED' });
66
+ if (stored.baseRevision !== current.revision) throw Object.assign(new Error('prepared selection clear revision is stale'), { code: 'E_STALE_PREPARED_CLEAR' });
67
+ if (stored.namespace !== prepared.namespace) throw Object.assign(new Error('prepared selection clear namespace changed'), { code: 'E_STALE_PREPARED_CLEAR' });
68
+ return stored;
69
+ };
70
+
71
+ const api = {
72
+ replaceAll(values, origin = 'programmatic') {
73
+ entries = unique(values ?? []);
74
+ return publish(origin, entries.length ? 'replace' : 'clear');
75
+ },
76
+ replaceKinds(kinds, values, origin = 'programmatic') {
77
+ const replacing = normalizeKinds(kinds);
78
+ entries = entries.filter((item) => !replacing.has(item.kind));
79
+ const added = unique(values ?? []).filter((item) => !entries.some((old) => old.key === item.key));
80
+ entries.push(...added);
81
+ return publish(origin, entries.length ? 'replace' : 'clear', added.at(-1)?.key ?? current.primaryKey);
82
+ },
83
+ add(values, origin = 'programmatic') {
84
+ const added = unique(values ?? []).filter((item) => !entries.some((old) => old.key === item.key));
85
+ entries.push(...added);
86
+ return publish(origin, 'add', added.at(-1)?.key ?? current.primaryKey);
87
+ },
88
+ toggle(values, origin = 'programmatic') {
89
+ let lastAdded = null;
90
+ for (const item of unique(values ?? [])) {
91
+ const at = entries.findIndex((old) => old.key === item.key);
92
+ if (at >= 0) entries.splice(at, 1);
93
+ else { entries.push(item); lastAdded = item.key; }
94
+ }
95
+ return publish(origin, entries.length ? 'toggle' : 'clear', lastAdded ?? current.primaryKey);
96
+ },
97
+ remove(values, origin = 'programmatic') {
98
+ const remove = new Set(unique(values ?? []).map((item) => item.key));
99
+ entries = entries.filter((item) => !remove.has(item.key));
100
+ return publish(origin, entries.length ? 'replace' : 'clear', current.primaryKey);
101
+ },
102
+ clearKinds(kinds, origin = 'programmatic') {
103
+ const clearing = normalizeKinds(kinds);
104
+ entries = entries.filter((item) => !clearing.has(item.kind));
105
+ return publish(origin, entries.length ? 'replace' : 'clear', current.primaryKey);
106
+ },
107
+ clear(origin = 'programmatic') { entries = []; return publish(origin, 'clear'); },
108
+ prepareClearForGeneration({ namespace } = {}) {
109
+ if (typeof namespace !== 'string' || !namespace) throw new Error('prepared selection clear needs a generation namespace');
110
+ const token = `model-selection-clear.${++preparedSequence}`;
111
+ const prepared = frozen({ token, baseRevision: current.revision, namespace });
112
+ preparedClears.set(token, { prepared, baseRevision: current.revision, namespace });
113
+ return prepared;
114
+ },
115
+ validatePreparedClear(prepared) { validatePrepared(prepared); return true; },
116
+ consumePreparedClear(prepared, origin = 'programmatic') {
117
+ // Consume before checking freshness. A stale transaction is terminal and cannot be replayed
118
+ // after the caller happens to drive the coordinator back to the same revision/namespace.
119
+ const token = prepared?.token;
120
+ const stored = token && preparedClears.get(token);
121
+ if (!stored || stored.prepared !== prepared) throw Object.assign(new Error('prepared selection clear is unknown or already consumed'), { code: 'E_PREPARED_CLEAR_CONSUMED' });
122
+ preparedClears.delete(token);
123
+ if (stored.baseRevision !== current.revision || stored.namespace !== prepared.namespace) {
124
+ throw Object.assign(new Error('prepared selection clear revision is stale'), { code: 'E_STALE_PREPARED_CLEAR' });
125
+ }
126
+ entries = [];
127
+ return publish(origin, 'clear');
128
+ },
129
+ applyProposal(proposal) {
130
+ const next = applySelectionProposal(current, proposal, registry);
131
+ const old = new Map(entries.map((item) => [item.key, item]));
132
+ entries = next.keys.map((key) => {
133
+ const kept = old.get(key); if (kept) return kept;
134
+ const receipt = (proposal.operandReceipts ?? []).find((item) => item?.key === key);
135
+ const resolved = receipt ? registry.lookupQualified?.(receipt) : registry.lookup(key);
136
+ if (!resolved) throw Object.assign(new Error('proposal resolved to a stale entity'), { code: 'E_STALE_ENTITY_GENERATION' });
137
+ return frozen({ kind: resolved.kind, sourceId: resolved.sourceId, key, generation: resolved.generation,
138
+ namespace: resolved.namespace ?? registry.namespaceOf?.(key) ?? null });
139
+ });
140
+ current = next;
141
+ notify();
142
+ return current;
143
+ },
144
+ current() { return current; },
145
+ entries() { return frozen(entries); },
146
+ replay() { notify(); return current; },
147
+ publicationErrors() { return frozen(publicationErrors); },
148
+ dispose() { entries = []; preparedClears.clear(); current = frozen({ revision: 0, origin: 'programmatic', operation: 'clear', keys: [], primaryKey: null }); },
149
+ };
150
+ return Object.freeze(api);
151
+ }
@@ -0,0 +1,290 @@
1
+ /*
2
+ * Provider-neutral model selection strategies.
3
+ *
4
+ * This module owns selection gesture semantics, never DOM listeners or provider selection state.
5
+ * An input arbiter forwards events through `interceptor`; providers return neutral hit records; the
6
+ * page's model-selection-coordinator is the only object allowed to commit selection changes.
7
+ */
8
+
9
+ export const MODEL_SELECTION_TOOLS_SCHEMA = 'floless.model-selection-tools/v1';
10
+
11
+ const finite = (value) => typeof value === 'number' && Number.isFinite(value);
12
+ const frozen = (value) => Object.freeze(value);
13
+ const editable = (node) => !!node && (node.isContentEditable === true || /^(INPUT|SELECT|TEXTAREA)$/.test(node.tagName));
14
+
15
+ function entityOf(hit) {
16
+ const value = hit?.entity ?? hit;
17
+ if (!value || typeof value.kind !== 'string' || !value.kind || typeof value.sourceId !== 'string' || !value.sourceId) return null;
18
+ return frozen({ kind: value.kind, sourceId: value.sourceId });
19
+ }
20
+
21
+ function entityToken(hit) {
22
+ const entity = entityOf(hit);
23
+ return entity ? JSON.stringify([entity.kind, entity.sourceId]) : null;
24
+ }
25
+
26
+ function visibleHits(value) {
27
+ return (Array.isArray(value) ? value : []).filter((hit) => hit && hit.rawVisible !== false && hit.visible !== false);
28
+ }
29
+
30
+ function normalizeFacetFilters(value = {}) {
31
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Selection filters must be a facet object.');
32
+ const out = {};
33
+ for (const [name, accepted] of Object.entries(value)) {
34
+ if (!name) throw new TypeError('Selection facet names must be non-empty.');
35
+ const values = accepted instanceof Set ? [...accepted] : (Array.isArray(accepted) ? accepted : [accepted]);
36
+ out[name] = frozen([...new Set(values.map((item) => String(item)))]);
37
+ }
38
+ return frozen(out);
39
+ }
40
+
41
+ export function modelSelectionHitMatchesFacets(hit, filters = {}) {
42
+ for (const [name, accepted] of Object.entries(filters)) {
43
+ if (!accepted.length) return false;
44
+ const actual = hit?.facets?.[name] ?? hit?.[name];
45
+ const actualValues = Array.isArray(actual) ? actual : [actual];
46
+ if (!actualValues.some((value) => accepted.includes(String(value)))) return false;
47
+ }
48
+ return true;
49
+ }
50
+
51
+ function selectableHits(hits, filters, generationToken, filterHit) {
52
+ const currentGeneration = generationToken?.();
53
+ return visibleHits(hits).filter((hit) => {
54
+ if (hit.selectable === false || !entityOf(hit)) return false;
55
+ if (currentGeneration != null && hit.generationToken != null && hit.generationToken !== currentGeneration) return false;
56
+ return modelSelectionHitMatchesFacets(hit, filters) && filterHit(hit, filters) !== false;
57
+ });
58
+ }
59
+
60
+ function screenBounds(hit) {
61
+ const value = hit?.screenBounds ?? hit?.bounds;
62
+ if (!value || typeof value !== 'object') return null;
63
+ const left = value.left ?? value.minX; const right = value.right ?? value.maxX;
64
+ const top = value.top ?? value.minY; const bottom = value.bottom ?? value.maxY;
65
+ if (![left, right, top, bottom].every(finite)) return null;
66
+ return frozen({ left: Math.min(left, right), right: Math.max(left, right), top: Math.min(top, bottom), bottom: Math.max(top, bottom) });
67
+ }
68
+
69
+ function marqueeRect(start, end) {
70
+ const mode = end.x >= start.x ? 'enclosed' : 'crossing';
71
+ return frozen({
72
+ left: Math.min(start.x, end.x), right: Math.max(start.x, end.x),
73
+ top: Math.min(start.y, end.y), bottom: Math.max(start.y, end.y), mode,
74
+ });
75
+ }
76
+
77
+ export function modelSelectionHitsInMarquee(hits, rect) {
78
+ if (!rect || !['enclosed', 'crossing'].includes(rect.mode)) throw new TypeError('Marquee needs enclosed or crossing mode.');
79
+ return visibleHits(hits).filter((hit) => {
80
+ const bounds = screenBounds(hit); if (!bounds) return false;
81
+ if (rect.mode === 'enclosed') {
82
+ return bounds.left >= rect.left && bounds.right <= rect.right && bounds.top >= rect.top && bounds.bottom <= rect.bottom;
83
+ }
84
+ return bounds.right >= rect.left && bounds.left <= rect.right && bounds.bottom >= rect.top && bounds.top <= rect.bottom;
85
+ });
86
+ }
87
+
88
+ function prevent(event) { event?.preventDefault?.(); }
89
+ function pointer(event) { return { x: Number(event?.clientX), y: Number(event?.clientY) }; }
90
+ function toggles(event) { return event?.ctrlKey === true || event?.metaKey === true || event?.shiftKey === true; }
91
+
92
+ /**
93
+ * @param {{
94
+ * coordinator: any,
95
+ * hitsAt?: (pointer: {x:number,y:number}, event?: any) => any[],
96
+ * allHits?: () => any[],
97
+ * marqueeHits?: (rect: any) => any[],
98
+ * onHover?: (hit: any|null) => void,
99
+ * onMarquee?: (rect: any|null) => void,
100
+ * fitSelection?: () => void,
101
+ * cancelActiveTool?: () => boolean,
102
+ * filterHit?: (hit: any, filters: any) => boolean,
103
+ * generationToken?: () => any,
104
+ * hierarchy?: null|((direction: string, entries: any[]) => any[]),
105
+ * initialFilters?: Record<string, any>,
106
+ * dragThreshold?: number,
107
+ * cycleRadius?: number,
108
+ * }} options
109
+ */
110
+ export function createModelSelectionTools({
111
+ coordinator,
112
+ hitsAt = () => [],
113
+ allHits = () => [],
114
+ marqueeHits = null,
115
+ onHover = () => {},
116
+ onMarquee = () => {},
117
+ fitSelection = () => {},
118
+ cancelActiveTool = () => false,
119
+ filterHit = () => true,
120
+ generationToken = () => null,
121
+ hierarchy = null,
122
+ initialFilters = {},
123
+ dragThreshold = 5,
124
+ cycleRadius = 3,
125
+ } = {}) {
126
+ if (!coordinator || !['replaceAll', 'toggle', 'clear', 'entries'].every((name) => typeof coordinator[name] === 'function')) {
127
+ throw new Error('Model selection tools need a model-selection-coordinator.');
128
+ }
129
+ for (const [name, value] of Object.entries({ hitsAt, allHits, onHover, onMarquee, fitSelection, cancelActiveTool, filterHit, generationToken })) {
130
+ if (typeof value !== 'function') throw new TypeError(`Model selection tools: ${name} must be a function.`);
131
+ }
132
+ if (marqueeHits !== null && typeof marqueeHits !== 'function') throw new TypeError('Model selection tools: marqueeHits must be a function or null.');
133
+ if (!finite(dragThreshold) || dragThreshold < 0 || !finite(cycleRadius) || cycleRadius < 0) throw new TypeError('Model selection thresholds must be non-negative.');
134
+
135
+ let filters = normalizeFacetFilters(initialFilters);
136
+ let gesture = null; let hover = null; let cycle = null; let suppressClick = false; let destroyed = false;
137
+ const filterListeners = new Set();
138
+ const notifyFilters = () => { const state = filters; for (const listener of filterListeners) listener(state); };
139
+ const candidates = (hits) => selectableHits(hits, filters, generationToken, filterHit);
140
+ const at = (event) => visibleHits(hitsAt(pointer(event), event));
141
+ const sameEntity = (a, b) => a?.kind === b?.kind && a?.sourceId === b?.sourceId;
142
+ const isSelected = (entity) => coordinator.entries().some((entry) => sameEntity(entry, entity));
143
+ const commit = (entities, event, origin) => {
144
+ if (toggles(event)) return coordinator.toggle(entities, origin);
145
+ return coordinator.replaceAll(entities, origin);
146
+ };
147
+ const setHover = (next) => {
148
+ if (hover === next) return;
149
+ if (entityToken(hover) === entityToken(next) && hover?.generationToken === next?.generationToken) { hover = next; return; }
150
+ hover = next; onHover(next);
151
+ };
152
+ const resetCycle = () => { cycle = null; };
153
+
154
+ const chooseAt = (event) => {
155
+ const raw = at(event); const eligible = candidates(raw);
156
+ if (!eligible.length) {
157
+ resetCycle();
158
+ if (!raw.length && !toggles(event)) coordinator.clear('mesh');
159
+ return frozen({ handled: true, rawVisible: raw.length, selected: null });
160
+ }
161
+ const p = pointer(event); const fingerprint = eligible.map(entityToken).join('|');
162
+ const continuing = cycle && cycle.fingerprint === fingerprint && Math.hypot(p.x - cycle.x, p.y - cycle.y) <= cycleRadius;
163
+ const index = continuing ? (cycle.index + 1) % eligible.length : 0;
164
+ const hit = eligible[index]; cycle = { fingerprint, x: p.x, y: p.y, index };
165
+ commit([entityOf(hit)], event, 'mesh');
166
+ return frozen({ handled: true, rawVisible: raw.length, selected: hit, overlapIndex: index, overlapCount: eligible.length });
167
+ };
168
+
169
+ const finishMarquee = (event) => {
170
+ if (!gesture?.active) return false;
171
+ const rect = marqueeRect(gesture.start, pointer(event));
172
+ // Providers may pre-query candidates, but the common layer remains the authority for LTR/RTL
173
+ // geometry whenever projected bounds are present. A returned record without bounds is already
174
+ // asserted by that provider to intersect, and remains raw-visible so filters cannot cause clear.
175
+ const reported = marqueeHits ? visibleHits(marqueeHits(rect)) : null;
176
+ const raw = reported
177
+ ? reported.filter((hit) => !screenBounds(hit) || modelSelectionHitsInMarquee([hit], rect).length === 1)
178
+ : modelSelectionHitsInMarquee(allHits(), rect);
179
+ const eligible = candidates(raw);
180
+ if (eligible.length) commit(eligible.map(entityOf), event, 'mesh');
181
+ else if (!raw.length && !toggles(event)) coordinator.clear('mesh');
182
+ gesture = null; suppressClick = true; onMarquee(null); resetCycle(); prevent(event); return true;
183
+ };
184
+
185
+ const interceptor = frozen({
186
+ pointerDown(event) {
187
+ if (destroyed || event.defaultPrevented || event.button !== 0) return false;
188
+ const p = pointer(event); if (!finite(p.x) || !finite(p.y)) return false;
189
+ // If the preceding drag released outside the surface, the browser emitted no click to consume
190
+ // suppression. A genuinely new pointer sequence must never lose its eventual click.
191
+ suppressClick = false;
192
+ gesture = { pointerId: event.pointerId, start: p, current: p, active: false }; return false;
193
+ },
194
+ pointerMove(event) {
195
+ if (destroyed) return false;
196
+ const p = pointer(event); if (!finite(p.x) || !finite(p.y)) return false;
197
+ if (cycle && Math.hypot(p.x - cycle.x, p.y - cycle.y) > cycleRadius) resetCycle();
198
+ if (gesture && (gesture.pointerId == null || event.pointerId === gesture.pointerId)) {
199
+ gesture.current = p;
200
+ if (!gesture.active && Math.hypot(p.x - gesture.start.x, p.y - gesture.start.y) > dragThreshold) gesture.active = true;
201
+ if (gesture.active) { onMarquee(marqueeRect(gesture.start, p)); prevent(event); return true; }
202
+ }
203
+ setHover(candidates(at(event))[0] ?? null); return false;
204
+ },
205
+ pointerLeave() { if (!gesture?.active) setHover(null); return false; },
206
+ pointerCancel(event) {
207
+ if (!gesture || (gesture.pointerId != null && event.pointerId !== gesture.pointerId)) return false;
208
+ const active = gesture.active; gesture = null; suppressClick = active; if (active) { onMarquee(null); prevent(event); } return active;
209
+ },
210
+ windowPointerMove(event) { return interceptor.pointerMove(event); },
211
+ windowPointerUp(event) {
212
+ if (!gesture || (gesture.pointerId != null && event.pointerId !== gesture.pointerId)) return false;
213
+ if (gesture.active) return finishMarquee(event);
214
+ gesture = null; return false;
215
+ },
216
+ click(event) {
217
+ if (destroyed) return false;
218
+ if (suppressClick) { suppressClick = false; prevent(event); return true; }
219
+ gesture = null;
220
+ if (Number(event.detail) > 1) { prevent(event); return true; }
221
+ const result = chooseAt(event); prevent(event); return result;
222
+ },
223
+ doubleClick(event) {
224
+ if (destroyed) return false;
225
+ const raw = at(event); const hit = candidates(raw)[0];
226
+ if (!hit) { if (raw.length) prevent(event); return false; }
227
+ const entity = entityOf(hit); if (!isSelected(entity)) coordinator.replaceAll([entity], 'mesh');
228
+ fitSelection(); prevent(event); return true;
229
+ },
230
+ keyDown(event) {
231
+ if (destroyed || event.defaultPrevented || editable(event.target)) return false;
232
+ if ((event.ctrlKey || event.metaKey) && !event.altKey && String(event.key).toLowerCase() === 'a') {
233
+ const raw = visibleHits(allHits()); const eligible = candidates(raw);
234
+ if (eligible.length || !raw.length) coordinator.replaceAll(eligible.map(entityOf), 'mesh');
235
+ prevent(event); resetCycle(); return true;
236
+ }
237
+ if (event.key !== 'Escape') return false;
238
+ if (cancelActiveTool()) { prevent(event); return true; }
239
+ if (gesture?.active) { gesture = null; suppressClick = true; onMarquee(null); prevent(event); return true; }
240
+ if (hover) { setHover(null); prevent(event); return true; }
241
+ if (coordinator.entries().length) { coordinator.clear('mesh'); prevent(event); return true; }
242
+ return false;
243
+ },
244
+ windowBlur() {
245
+ const active = gesture?.active === true; gesture = null; suppressClick = active;
246
+ if (active) onMarquee(null); setHover(null); resetCycle(); return active;
247
+ },
248
+ orbitStart() { resetCycle(); setHover(null); },
249
+ });
250
+
251
+ const capabilities = frozen({
252
+ single: true, toggle: true, marquee: true, hover: true, selectAll: true, overlapCycle: true,
253
+ doubleClickFit: true, facets: true, hierarchy: typeof hierarchy === 'function',
254
+ });
255
+ const commands = frozen([
256
+ 'selection.single', 'selection.toggle', 'selection.marquee-window', 'selection.marquee-crossing',
257
+ 'selection.select-all', 'selection.clear', 'selection.fit',
258
+ ...(capabilities.hierarchy ? ['selection.hierarchy-parent', 'selection.hierarchy-children'] : []),
259
+ ]);
260
+
261
+ return frozen({
262
+ schema: MODEL_SELECTION_TOOLS_SCHEMA,
263
+ interceptor,
264
+ capabilities: () => capabilities,
265
+ commandInventory: () => commands,
266
+ filters: () => filters,
267
+ setFilters(next) { filters = normalizeFacetFilters(next); resetCycle(); setHover(null); notifyFilters(); return filters; },
268
+ setFacet(name, values) { filters = normalizeFacetFilters({ ...filters, [name]: values }); resetCycle(); setHover(null); notifyFilters(); return filters; },
269
+ subscribeFilters(listener) {
270
+ if (typeof listener !== 'function') throw new TypeError('Selection filter subscriber must be a function.');
271
+ filterListeners.add(listener); listener(filters); let live = true;
272
+ return () => { if (live) { live = false; filterListeners.delete(listener); } };
273
+ },
274
+ selectAt: chooseAt,
275
+ finishMarquee,
276
+ resetOverlapCycle: resetCycle,
277
+ generationChanged() { resetCycle(); setHover(null); gesture = null; suppressClick = false; onMarquee(null); },
278
+ cameraChanged() { resetCycle(); setHover(null); },
279
+ selectHierarchy(direction) {
280
+ if (!capabilities.hierarchy) return false;
281
+ const values = hierarchy(direction, coordinator.entries());
282
+ if (!Array.isArray(values)) throw new TypeError('Hierarchy selection must return entities.');
283
+ coordinator.replaceAll(values, 'mesh'); return true;
284
+ },
285
+ destroy() {
286
+ if (destroyed) return; destroyed = true; gesture = null; hover = null; cycle = null; suppressClick = false;
287
+ filterListeners.clear(); onMarquee(null); onHover(null);
288
+ },
289
+ });
290
+ }