@floless/app 0.139.1 → 0.141.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 (41) hide show
  1. package/dist/floless-server.cjs +32765 -36490
  2. package/dist/skills/floless-app-steel-takeoff/SKILL.md +8 -3
  3. package/dist/skills/floless-app-vectorize/SKILL.md +1 -1
  4. package/dist/skills/floless-app-vectorize/scripts/extract_pdf.py +7 -1
  5. package/dist/skills/floless-app-vectorize/scripts/vision_to_contract.py +7 -1
  6. package/dist/web/app.css +163 -3
  7. package/dist/web/aware.js +657 -66
  8. package/dist/web/chat.css +387 -25
  9. package/dist/web/chat.js +2005 -108
  10. package/dist/web/commands-filter.js +86 -8
  11. package/dist/web/commands-revit.js +2 -1
  12. package/dist/web/commands-shell.js +249 -13
  13. package/dist/web/commands-steel.js +34 -24
  14. package/dist/web/commands.js +19 -0
  15. package/dist/web/filter-ai-context.js +57 -0
  16. package/dist/web/filter-ai-proposal.js +87 -0
  17. package/dist/web/filter-guidance.js +8 -0
  18. package/dist/web/index.html +72 -11
  19. package/dist/web/instructor.js +231 -33
  20. package/dist/web/left-pane.js +185 -18
  21. package/dist/web/local-discovery.js +297 -0
  22. package/dist/web/model-editor-revit-adapter.js +3 -1
  23. package/dist/web/model-editor-steel-adapter.js +3 -1
  24. package/dist/web/model-editor.css +4 -4
  25. package/dist/web/model-revit-module.js +63 -0
  26. package/dist/web/model-viewport-toolbar.js +13 -1
  27. package/dist/web/model-viewport.js +16 -1
  28. package/dist/web/overlay-escape.js +79 -0
  29. package/dist/web/revit-editor.css +7 -0
  30. package/dist/web/revit-editor.html +5 -5
  31. package/dist/web/revit-editor.js +20 -10
  32. package/dist/web/steel-detail-refs.js +0 -69
  33. package/dist/web/steel-editor.html +103 -264
  34. package/dist/web/steel-filter-core.js +298 -12
  35. package/dist/web/steel-filter-hit.js +526 -0
  36. package/dist/web/steel-filter.html +1647 -75
  37. package/dist/web/steel-split-view.js +1 -1
  38. package/dist/web/vector-3d.html +3 -0
  39. package/dist/web/vector-editor.html +9 -1
  40. package/dist/web/workspaces.js +198 -25
  41. package/package.json +5 -2
@@ -0,0 +1,526 @@
1
+ /*
2
+ * steel-filter-hit.js — PURE point-to-element hit testing for the Drawing Filter (no DOM, no window).
3
+ * Unit-tested in node (server/steel-filter-hit.test.ts) AND loaded by web/steel-filter.html.
4
+ *
5
+ * WHY IT EXISTS (#1527). Hover info reads a line's layer, thickness and colour off the DOM node under
6
+ * the pointer, which only exists for lines the filter is SHOWING: a raster-backed sheet mounts nothing
7
+ * else, and a raster-less one mounts the rest as `.is-context` with pointer-events:none. So a value
8
+ * already switched off had nothing left to point at, and "which layer do I turn back ON" stayed trial
9
+ * and error. The geometry of every element is already in the drawing data (`sheets[].elements`); this
10
+ * module answers "which element is nearest this point" against that data, without drawing anything.
11
+ *
12
+ * HOW. A coarse uniform grid, built ONCE per sheet. Every path is flattened to straight segments; a
13
+ * segment longer than a cell is cut into cell-sized pieces, and each piece is filed under the (at most
14
+ * four) cells its box touches. A query then looks only at the cells within `tol` of the point. Cutting
15
+ * long segments is what keeps a sheet-wide diagonal from being filed under thousands of cells, and it
16
+ * loses nothing: the nearest point on a segment lies on SOME piece, and that piece's box contains it.
17
+ * Buckets are stored flat (CSR: one offsets array, one ids array) because a sheet at the per-sheet cap
18
+ * carries 100,000 elements, and an array per cell is a quarter of a million small allocations.
19
+ *
20
+ * A text run is a RECTANGLE (its `bbox`), at distance 0 anywhere inside it — pointing at a label means
21
+ * pointing at the label, not at its outline. It is filed as TWO rectangles when the page draws its
22
+ * glyphs outside that box, which is what a rotated run does: the producer records no rotation, so the
23
+ * view draws every run horizontally and a vertical label's glyphs run sideways out of their own
24
+ * recorded box (#1538). Both rectangles carry the same owner, so either one answers with the element.
25
+ *
26
+ * WHAT IT READS. The one path grammar the extractor emits (`M L C H V Z`, absolute — see
27
+ * server/steel-read-path-bbox.ts), plus the relative forms and `Q` because a hand-edited contract may
28
+ * carry them. An element whose `d` does not parse wholly is simply not hit-testable: a partial reading
29
+ * would name a line the pointer is not on, which is worse than naming nothing.
30
+ */
31
+
32
+ import { textBox, textDraw, textIsVertical } from './steel-filter-core.js';
33
+
34
+ /**
35
+ * Curve flattening. A curve is cut into straight pieces, and the pieces are what the pointer is
36
+ * measured against — so a piece that strays further from the curve than the hover tolerance is a point
37
+ * ON the drawn curve that reads nothing. #1527 shipped a flat eight pieces per curve, which is fine for
38
+ * a bolt circle and not for a page-sized arc: the chord of one eighth of that arc sits several units
39
+ * off it (#1538).
40
+ *
41
+ * So the piece count is chosen per curve, from how far the curve actually bends. `CURVE_TOLERANCE` is
42
+ * in the drawing's own units (PDF points on a real sheet) and sits under the hover tolerance, which is
43
+ * 4 CSS px divided by the zoom — i.e. 4 units at 1x and 0.5 at 8x. Below the old flat eight nothing
44
+ * changes, so every curve small enough for #1527's count is flattened exactly as it was.
45
+ */
46
+ export const CURVE_TOLERANCE = 0.25;
47
+ /** Never fewer pieces than #1527's flat count, whatever the arithmetic says. */
48
+ export const CURVE_MIN_STEPS = 8;
49
+ /** Nor more than this for one curve. */
50
+ export const CURVE_MAX_STEPS = 256;
51
+ /**
52
+ * And a cap on the EXTRA pieces (those above `CURVE_MIN_STEPS`) one path may spend in total. The
53
+ * builder yields between elements and cannot yield in the middle of a path, so an adaptive count with
54
+ * no per-path ceiling lets a single path of huge curves blow the 6 ms build slice — the reason
55
+ * #1527's review backed adaptive flattening out. One path costs at most `CURVE_MIN_STEPS` per curve
56
+ * (exactly what it cost before) plus this.
57
+ *
58
+ * SPENT EVENLY, never first-come. The allowance is divided by the path's own curve count before any
59
+ * of it is spent, so every curve in a path gets the same share. Handing it out in arrival order
60
+ * instead put the whole budget into the curves parsed FIRST and dropped the rest to the flat count —
61
+ * and the flat count is not a graceful floor, it is the unreadable resolution this issue is about, so
62
+ * an over-budget path silently reinstated #1538 on its later curves. The extractor puts every drawing
63
+ * item of one PDF path object into a single `d`, so a path of a hundred curves is ordinary output and
64
+ * not a hand-edited curiosity, and which curves went blind depended on where they sat in the string
65
+ * (review finding). An even share degrades the whole path together and depends on nothing but its
66
+ * contents.
67
+ */
68
+ export const CURVE_EXTRA_BUDGET = 4096;
69
+ /**
70
+ * The same allowance for a whole SHEET, which is the one that bounds memory.
71
+ *
72
+ * A per-path cap renews for every element, so on its own it bounds the un-yieldable build slice and
73
+ * nothing the index RETAINS: a sheet at the 100,000-element cap could still multiply its primitives by
74
+ * the per-curve count, and `hitIndexBuilder` holds them in ordinary JS arrays before the typed copies
75
+ * are made (Codex review). Against the ~800,000 primitives such a sheet cost before, this ceiling puts
76
+ * the worst case at ~1.06 million — a third more, not thirty times more.
77
+ *
78
+ * It is generous for any real drawing: a page-sized arc earns ~58 pieces above the flat count, so this
79
+ * covers a few thousand of them on one sheet, and a drawing with ten thousand page-sized curves is not
80
+ * one.
81
+ *
82
+ * Unlike the per-path share this IS a running total, so on a sheet that exhausts it the curves parsed
83
+ * later are the ones that degrade. That order dependence is deliberate and confined to a last-resort
84
+ * memory guard: a sheet demanding more than this has to lose something, and the alternative -- a
85
+ * second pass over every path on the sheet to divide the ceiling by its total curve count -- costs the
86
+ * scan on every ordinary drawing to make a pathological one degrade more evenly. A curve cut short by
87
+ * ANY of the three limits -- this ceiling, the per-path share or the per-curve CURVE_MAX_STEPS -- is
88
+ * counted in `index.coarse`, and the Drawing Filter shows that count beside Hover info (#1550), so the
89
+ * condition is never silent to the person pointing at the drawing.
90
+ *
91
+ * Only a path that is READ spends from it: a path `pathSegments` rejects adds no primitive to the
92
+ * index, so it takes nothing from the allowance either (see `spent` there).
93
+ */
94
+ export const SHEET_CURVE_EXTRA_BUDGET = 262_144;
95
+
96
+ /**
97
+ * A fresh spending allowance, plus the tally of curves cut short by any of the three limits (this
98
+ * allowance, a path's share, or CURVE_MAX_STEPS), committed only for paths that are read. `pathSegments` works
99
+ * without one (its per-path share still applies); a caller that wants the tally passes one in, which
100
+ * `hitIndexBuilder` always does, and surfaces as `index.coarse`.
101
+ */
102
+ export const newCurveBudget = (extra = SHEET_CURVE_EXTRA_BUDGET) => ({ extra, coarse: 0 });
103
+
104
+ /**
105
+ * Pieces needed to flatten one Bézier to within `CURVE_TOLERANCE`. `d` is the larger of the curve's
106
+ * second-difference vectors and `k` the degree's constant: uniform flattening into n pieces deviates
107
+ * from the curve by at most `k * d / n²`.
108
+ *
109
+ * The constants come from the interpolation bound `max|B - L| <= max|B''| / (8 n²)`. A quadratic's
110
+ * second derivative is the constant `2d`, giving k = 1/4; a cubic's is at most `6d`, giving k = 3/4.
111
+ * They were HALF that in the first draft of this, which is not a conservative error but an unsound
112
+ * bound — the arc in the tests below measured 0.3395 units off a 47-piece flattening the halved
113
+ * constant certified at 0.2401, so points on a drawn curve still read nothing once the zoom took the
114
+ * hover tolerance under the real deviation (Codex review). `curveDeviation` in the test file measures
115
+ * it rather than trusting either number.
116
+ *
117
+ * Returns null when the demand is not a finite number, which the caller turns into an unreadable
118
+ * path. That is NOT the same as the caller's own `Number.isFinite` check on the control points: it
119
+ * runs first, and it reads the literals in the `d` string, while this reads their second DIFFERENCE,
120
+ * which overflows out of perfectly finite literals (`M0 0L1e308 1e308C1e308 1e308 1e308 1e308 1e308
121
+ * 1e308`). Falling back to the minimum there filed a curve whose curvature is not representable at a
122
+ * resolution that means nothing, under a comment claiming it had been rejected (review finding). This
123
+ * module's own rule is that naming nothing beats naming the wrong line.
124
+ */
125
+ function curveSteps(d, k) {
126
+ const n = Math.ceil(Math.sqrt((k * d) / CURVE_TOLERANCE));
127
+ if (!Number.isFinite(n)) return null;
128
+ // The DEMAND, never clamped to CURVE_MAX_STEPS here: that cap is one of the allowances `spend` draws
129
+ // against, and a curve it cuts short has to be counted like any other. Clamped here, `spend` compared
130
+ // what it granted against a demand already cut to the cap, so a curve that wanted 652 pieces and got
131
+ // 256 -- measured 1.14 units off itself, 4.6x the tolerance -- counted nothing (#1550).
132
+ return Math.max(CURVE_MIN_STEPS, n);
133
+ }
134
+
135
+ /**
136
+ * How many curve GROUPS a path holds — the divisor for its even share of CURVE_EXTRA_BUDGET.
137
+ *
138
+ * By group, not by command letter. SVG lets one `C` carry several six-number groups and the parser
139
+ * runs a curve for each, so counting letters handed every implicit group the WHOLE path's allowance:
140
+ * a 2.4 KB path spelled that way spent 7,384 extra pieces against a cap of 4,096, and a path at
141
+ * `MAX_HIT_PATH_CHARS` could spend the sheet's allowance inside one slice the builder cannot yield out
142
+ * of -- the pointer freeze this cap exists to prevent (Codex review).
143
+ *
144
+ * The cheap character sweep comes first because most elements are straight linework and must not pay
145
+ * for the token scan at all.
146
+ */
147
+ const countCurves = (d) => {
148
+ let curved = false;
149
+ for (let i = 0; i < d.length && !curved; i++) {
150
+ const c = d[i];
151
+ curved = c === 'C' || c === 'c' || c === 'Q' || c === 'q';
152
+ }
153
+ if (!curved) return 0;
154
+ let n = 0, need = 0, seen = 0, i = 0;
155
+ while (i < d.length) {
156
+ const c = d[i];
157
+ if (COMMANDS.has(c)) {
158
+ const u = c.toUpperCase();
159
+ need = u === 'C' ? 6 : u === 'Q' ? 4 : 0; // `M` implies lineto, which spends nothing
160
+ seen = 0; i++;
161
+ continue;
162
+ }
163
+ NUM.lastIndex = i;
164
+ if (!NUM.exec(d)) { i++; continue; } // separator, or a command this parser will reject
165
+ i = NUM.lastIndex;
166
+ if (need && ++seen === need) { seen = 0; n++; }
167
+ }
168
+ return n;
169
+ };
170
+ /** At most this many cells per axis. 512² buckets is ~1 MB of offsets at the per-sheet cap. */
171
+ const MAX_GRID = 512;
172
+
173
+ const NUM = /[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/y;
174
+ const COMMANDS = new Set('MLHVCQZmlhvcqz');
175
+
176
+ /**
177
+ * Flatten a path `d` to straight segments, `[x1, y1, x2, y2, ...]`, or `null` when the string is not
178
+ * wholly understood. `Z` closes back to the subpath start.
179
+ */
180
+ export function pathSegments(d, /** @type {{ extra: number, coarse: number } | null} */ sheet = null) {
181
+ if (typeof d !== 'string' || !d) return null;
182
+ const out = [];
183
+ let i = 0, cmd = '', x = 0, y = 0, sx = 0, sy = 0, any = false;
184
+ // Every curve's own share of this path's allowance, fixed before any of it is spent.
185
+ const curves = countCurves(d);
186
+ const share = curves ? Math.floor(CURVE_EXTRA_BUDGET / curves) : 0;
187
+ // What this path has spent so far, and how many of its curves that cut short. Against the path's own
188
+ // allowance this is the GUARANTEE behind the even share, which is the POLICY: for a path whose curves
189
+ // were counted correctly `share * curves <= CURVE_EXTRA_BUDGET`, so it never binds and there is no
190
+ // cliff. It binds only if the count is ever wrong again, and then the path degrades rather than
191
+ // spending without limit -- the one property the cap exists for.
192
+ //
193
+ // Against the SHEET's allowance it is a PENDING spend, committed only once the whole path has parsed
194
+ // (the one `return out` below). Every earlier `return null` leaves the sheet untouched. Spending it as
195
+ // each curve parsed let a path that was later REJECTED -- an unsupported command, an incomplete group,
196
+ // a curvature that overflows -- keep what it had spent while contributing no primitive: 70 such paths
197
+ // left a valid arc after them at the flat count, 392 of its 401 on-curve points unhittable at 8x
198
+ // (Codex review). Within a path nothing changes: its curves still draw on what the sheet has left
199
+ // after this path's own earlier curves, exactly as they did when that was spent as it went.
200
+ let spent = 0, coarse = 0;
201
+ const n = d.length;
202
+ const skip = () => { while (i < n) { const c = d.charCodeAt(i); if (c === 32 || c === 44 || c === 9 || c === 10 || c === 13) i++; else break; } };
203
+ const num = () => {
204
+ skip();
205
+ NUM.lastIndex = i;
206
+ const m = NUM.exec(d);
207
+ if (!m) return NaN;
208
+ i = NUM.lastIndex;
209
+ return Number(m[0]);
210
+ };
211
+ const seg = (x1, y1, x2, y2) => { out.push(x1, y1, x2, y2); };
212
+ /**
213
+ * `curveSteps`, drawn against BOTH allowances: this path's EVEN SHARE of its own (so one path stays
214
+ * inside the build slice it cannot yield out of, and every curve in it degrades together), and what
215
+ * is left of the sheet's (so the primitives every path leaves behind stay bounded in total) -- and
216
+ * under the per-curve `CURVE_MAX_STEPS`. Whichever is smallest binds. None can go negative, so `steps`
217
+ * is never below `CURVE_MIN_STEPS` and a curve is never dropped for want of budget — but a curve that
218
+ * got less than it asked for, from ANY of the three, is COUNTED (and the count committed with the
219
+ * spend), because a coarser flattening is exactly the condition that leaves a drawn curve unhittable
220
+ * and nothing else on the index would record it. The page tells the user about it (#1550). Returns
221
+ * null when the curve's own demand is not finite.
222
+ */
223
+ const spend = (dev, k) => {
224
+ const want = curveSteps(dev, k);
225
+ if (want === null) return null;
226
+ const cap = Math.min(share, CURVE_EXTRA_BUDGET - spent, sheet ? sheet.extra - spent : Infinity);
227
+ const steps = Math.min(want, CURVE_MAX_STEPS, CURVE_MIN_STEPS + cap);
228
+ if (steps < want) coarse++;
229
+ // `share` is per curve and does NOT run down: it is this path's allowance divided by its own curve
230
+ // count, so an ordinary path's counts depend on nothing that came before them. `spent` against the
231
+ // two allowances is the running guarantee behind it.
232
+ spent += steps - CURVE_MIN_STEPS;
233
+ return steps;
234
+ };
235
+ while (true) {
236
+ skip();
237
+ if (i >= n) break;
238
+ const c = d[i];
239
+ if (COMMANDS.has(c)) { cmd = c; i++; }
240
+ else if (!cmd || cmd === 'Z' || cmd === 'z') return null; // a number with no command to own it
241
+ const rel = cmd === cmd.toLowerCase();
242
+ const ox = rel ? x : 0, oy = rel ? y : 0;
243
+ switch (cmd.toUpperCase()) {
244
+ case 'Z':
245
+ if (x !== sx || y !== sy) seg(x, y, sx, sy);
246
+ x = sx; y = sy;
247
+ break;
248
+ case 'M': {
249
+ const a = num(), b = num();
250
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
251
+ x = ox + a; y = oy + b; sx = x; sy = y; any = true;
252
+ cmd = rel ? 'l' : 'L'; // implicit lineto after the first pair
253
+ break;
254
+ }
255
+ case 'L': {
256
+ const a = num(), b = num();
257
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
258
+ const nx = ox + a, ny = oy + b; seg(x, y, nx, ny); x = nx; y = ny;
259
+ break;
260
+ }
261
+ case 'H': {
262
+ const a = num();
263
+ if (!Number.isFinite(a)) return null;
264
+ const nx = ox + a; seg(x, y, nx, y); x = nx;
265
+ break;
266
+ }
267
+ case 'V': {
268
+ const b = num();
269
+ if (!Number.isFinite(b)) return null;
270
+ const ny = oy + b; seg(x, y, x, ny); y = ny;
271
+ break;
272
+ }
273
+ case 'C': {
274
+ const v = [num(), num(), num(), num(), num(), num()];
275
+ if (!v.every(Number.isFinite)) return null;
276
+ const x1 = ox + v[0], y1 = oy + v[1], x2 = ox + v[2], y2 = oy + v[3], x3 = ox + v[4], y3 = oy + v[5];
277
+ const steps = spend(Math.max(
278
+ Math.hypot(x - 2 * x1 + x2, y - 2 * y1 + y2),
279
+ Math.hypot(x1 - 2 * x2 + x3, y1 - 2 * y2 + y3)), 3 / 4);
280
+ if (steps === null) return null; // curvature not representable -- the whole path is unreadable
281
+ let px = x, py = y;
282
+ for (let k = 1; k <= steps; k++) {
283
+ const t = k / steps, u = 1 - t;
284
+ const qx = u * u * u * x + 3 * u * u * t * x1 + 3 * u * t * t * x2 + t * t * t * x3;
285
+ const qy = u * u * u * y + 3 * u * u * t * y1 + 3 * u * t * t * y2 + t * t * t * y3;
286
+ seg(px, py, qx, qy); px = qx; py = qy;
287
+ }
288
+ x = x3; y = y3;
289
+ break;
290
+ }
291
+ case 'Q': {
292
+ const v = [num(), num(), num(), num()];
293
+ if (!v.every(Number.isFinite)) return null;
294
+ const x1 = ox + v[0], y1 = oy + v[1], x2 = ox + v[2], y2 = oy + v[3];
295
+ const steps = spend(Math.hypot(x - 2 * x1 + x2, y - 2 * y1 + y2), 1 / 4);
296
+ if (steps === null) return null; // curvature not representable -- the whole path is unreadable
297
+ let px = x, py = y;
298
+ for (let k = 1; k <= steps; k++) {
299
+ const t = k / steps, u = 1 - t;
300
+ const qx = u * u * x + 2 * u * t * x1 + t * t * x2;
301
+ const qy = u * u * y + 2 * u * t * y1 + t * t * y2;
302
+ seg(px, py, qx, qy); px = qx; py = qy;
303
+ }
304
+ x = x2; y = y2;
305
+ break;
306
+ }
307
+ default:
308
+ return null;
309
+ }
310
+ }
311
+ if (!any) return null;
312
+ // The whole path is read, so its spend is real: commit it to the sheet now, and never before.
313
+ if (sheet) { sheet.extra -= spent; sheet.coarse += coarse; }
314
+ return out;
315
+ }
316
+
317
+ /** A text run's RECORDED rectangle, normalised, or null: `textBox`, the box the page anchors the run in. */
318
+ const textRect = (el) => (el ? textBox(el.bbox) : null);
319
+
320
+ /**
321
+ * The SECOND rectangle for a text run: where `textDraw` says the page paints the glyphs of a ROTATED
322
+ * run, or null. A rotated run is the one case it exists for (#1538): the producer records no rotation,
323
+ * so the page draws every run horizontally from its box's bottom-left corner, and the glyphs of a tall,
324
+ * narrow box run sideways OUT of it, so most of a plainly visible label read nothing. It is also null
325
+ * when that rectangle lies wholly inside `box` (a two-glyph run), where it would answer nothing the
326
+ * recorded one does not.
327
+ *
328
+ * An UNROTATED run never gets one, because its recorded box contains it by construction: `textDraw`
329
+ * anchors it at the normalised box's bottom-left corner and caps its width at the box's width. The one
330
+ * place its glyphs can still rise past the box is the top, when the box is shorter than
331
+ * `TEXT_MIN_FONT` and the floor draws the glyphs taller than recorded, and that overhang is exactly
332
+ * what must NOT be filed: 3/32" plot text is about 6.8 pt, routine rather than exotic, and filing it let
333
+ * a label answer for a pointer up to 8 units outside its own box, stealing hovers from lines drawn
334
+ * beside it and haloing ordinary labels with two boxes (review finding). The recorded box is the
335
+ * measured glyph span; the floor is only a legibility minimum for drawing it. (A box of zero width or
336
+ * height measured no span at all; it keeps the one degenerate rectangle it always had.)
337
+ *
338
+ * Kept SEPARATE rather than unioned with the recorded box, which is the shape #1527's review tried and
339
+ * backed out: the union of a title-block stamp's tall box and its sideways run is a rectangle that
340
+ * swallows every line inside the stamp, and a rectangle is at distance 0 all the way through.
341
+ */
342
+ export function textRunRect(el, box) {
343
+ const bbox = el && el.bbox, text = el && el.text;
344
+ if (!textIsVertical(bbox, text)) return null;
345
+ // Already normalised: the run rises from the box's bottom-left corner and extends to its right.
346
+ const r = textDraw(bbox, text, el.size).run;
347
+ if (!r || !r.every(Number.isFinite)) return null;
348
+ return box && r[0] >= box[0] && r[1] >= box[1] && r[2] <= box[2] && r[3] <= box[3] ? null : r;
349
+ }
350
+
351
+ /** How much work the builder does between checks of the clock: this many elements, or primitives. */
352
+ const BUILD_STRIDE = 64;
353
+ /**
354
+ * A path longer than this is not hit-testable. The extractor's paths are bounded far below it (see
355
+ * MAX_PATH_CHARS in server/steel-read-path-bbox.ts); a hand-edited contract's are not, and the builder
356
+ * cannot yield in the middle of parsing one path, so an unbounded one could freeze the pointer for
357
+ * however long it takes to parse. Such an element counts as `skipped`.
358
+ */
359
+ export const MAX_HIT_PATH_CHARS = 65_536;
360
+
361
+ /**
362
+ * Build the grid for one sheet's elements, a slice at a time.
363
+ *
364
+ * A GENERATOR, because at the per-sheet cap the build is a couple of hundred milliseconds of work, and
365
+ * done in one go that is a frozen pointer the first time Hover info needs it -- exactly the lag this
366
+ * feature must not have. Each `next()` does roughly `budgetMs` of work (by `now()`), so the page can
367
+ * spread it across frames; `buildHitIndex` below drains it in one go for callers that do not care.
368
+ * The generator's RETURN value is the index. `index.skipped` counts the elements that could not be read
369
+ * (no parseable `d`, no usable bbox), and `index.coarse` the curves flattened more coarsely than their
370
+ * own tolerance asks -- because the sheet ran out of allowance, the path's share ran out, or the curve
371
+ * wanted more than CURVE_MAX_STEPS. That is the one condition that leaves a drawn curve unhittable, so
372
+ * the page reads it and says so beside Hover info (#1550).
373
+ */
374
+ export function* hitIndexBuilder(elements, budgetMs = Infinity, now = () => Date.now()) {
375
+ const els = Array.isArray(elements) ? elements : [];
376
+ // ONE curve allowance for the whole sheet, spent by every path in it -- see SHEET_CURVE_EXTRA_BUDGET.
377
+ const budget = newCurveBudget();
378
+ let sliceStart = now();
379
+ const spent = () => now() - sliceStart >= budgetMs;
380
+ // Pass 1: every piece of geometry as a primitive. kind 0 = segment, 1 = rectangle.
381
+ const prim = []; // x1, y1, x2, y2 per primitive
382
+ const kind = [];
383
+ const owner = [];
384
+ let skipped = 0;
385
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
386
+ const grow = (a, b) => { if (a < minX) minX = a; if (a > maxX) maxX = a; if (b < minY) minY = b; if (b > maxY) maxY = b; };
387
+ for (let e = 0; e < els.length; e++) {
388
+ if (e % BUILD_STRIDE === 0 && spent()) { yield; sliceStart = now(); }
389
+ const el = els[e];
390
+ if (el && el.kind === 'text') {
391
+ const r = textRect(el);
392
+ if (!r) { skipped++; continue; }
393
+ prim.push(r[0], r[1], r[2], r[3]); kind.push(1); owner.push(e);
394
+ grow(r[0], r[1]); grow(r[2], r[3]);
395
+ const run = textRunRect(el, r);
396
+ if (run) {
397
+ prim.push(run[0], run[1], run[2], run[3]); kind.push(1); owner.push(e);
398
+ grow(run[0], run[1]); grow(run[2], run[3]);
399
+ }
400
+ continue;
401
+ }
402
+ const s = el && typeof el.d === 'string' && el.d.length <= MAX_HIT_PATH_CHARS ? pathSegments(el.d, budget) : null;
403
+ if (!s) { skipped++; continue; }
404
+ for (let k = 0; k < s.length; k += 4) {
405
+ prim.push(s[k], s[k + 1], s[k + 2], s[k + 3]); kind.push(0); owner.push(e);
406
+ grow(s[k], s[k + 1]); grow(s[k + 2], s[k + 3]);
407
+ }
408
+ }
409
+ const count = kind.length;
410
+ if (!count) return { count: 0, skipped, coarse: budget.coarse, elements: els };
411
+ const W = Math.max(maxX - minX, 1e-9), H = Math.max(maxY - minY, 1e-9);
412
+ // Roughly two primitives per cell, on a grid shaped like the drawing, capped per axis.
413
+ const target = Math.max(1, Math.sqrt(count / 2));
414
+ const aspect = W / H;
415
+ const gx = Math.max(1, Math.min(MAX_GRID, Math.round(target * Math.sqrt(aspect))));
416
+ const gy = Math.max(1, Math.min(MAX_GRID, Math.round(target / Math.sqrt(aspect))));
417
+ const cw = W / gx, ch = H / gy;
418
+ const cellX = (v) => Math.min(gx - 1, Math.max(0, Math.floor((v - minX) / cw)));
419
+ const cellY = (v) => Math.min(gy - 1, Math.max(0, Math.floor((v - minY) / ch)));
420
+ const cells = gx * gy;
421
+ // Every cell a primitive passes through, each ONCE. A segment is walked in pieces no longer than a
422
+ // cell on either axis, and each piece's box names at most four cells -- so a sheet-wide diagonal
423
+ // touches a thin band of cells, not the thousands its own box would cover. `stamp` drops the cells
424
+ // consecutive pieces share, so a cell lists a primitive once however many pieces cross it.
425
+ const stamp = new Int32Array(cells).fill(-1);
426
+ const visit = (p, fn) => {
427
+ const x1 = prim[4 * p], y1 = prim[4 * p + 1], x2 = prim[4 * p + 2], y2 = prim[4 * p + 3];
428
+ const steps = kind[p] === 1 ? 1 : Math.max(1, Math.ceil(Math.max(Math.abs(x2 - x1) / cw, Math.abs(y2 - y1) / ch)));
429
+ let px = x1, py = y1;
430
+ for (let k = 1; k <= steps; k++) {
431
+ const qx = k === steps ? x2 : x1 + ((x2 - x1) * k) / steps;
432
+ const qy = k === steps ? y2 : y1 + ((y2 - y1) * k) / steps;
433
+ const a = cellX(Math.min(px, qx)), b = cellX(Math.max(px, qx));
434
+ const c0 = cellY(Math.min(py, qy)), c1 = cellY(Math.max(py, qy));
435
+ for (let cy = c0; cy <= c1; cy++) {
436
+ for (let cx = a; cx <= b; cx++) {
437
+ const c = cy * gx + cx;
438
+ if (stamp[c] !== p) { stamp[c] = p; fn(c); }
439
+ }
440
+ }
441
+ px = qx; py = qy;
442
+ }
443
+ };
444
+ const start = new Uint32Array(cells + 1);
445
+ for (let p = 0; p < count; p++) {
446
+ if (p % BUILD_STRIDE === 0 && spent()) { yield; sliceStart = now(); }
447
+ visit(p, (c) => { start[c + 1]++; });
448
+ }
449
+ for (let c = 0; c < cells; c++) start[c + 1] += start[c];
450
+ const ids = new Uint32Array(start[cells]);
451
+ const fill = start.slice(0, cells);
452
+ stamp.fill(-1);
453
+ for (let p = 0; p < count; p++) {
454
+ if (p % BUILD_STRIDE === 0 && spent()) { yield; sliceStart = now(); }
455
+ visit(p, (c) => { ids[fill[c]++] = p; });
456
+ }
457
+ return {
458
+ count, skipped, coarse: budget.coarse, elements: els,
459
+ minX, minY, maxX, maxY, cw, ch, gx, gy, start, ids,
460
+ prim: Float64Array.from(prim), kind: Uint8Array.from(kind), owner: Uint32Array.from(owner),
461
+ };
462
+ }
463
+
464
+ /** Build the whole grid at once. The result is opaque to callers — pass it to `hitTest`. */
465
+ export function buildHitIndex(elements) {
466
+ const it = hitIndexBuilder(elements);
467
+ let r = it.next();
468
+ while (!r.done) r = it.next();
469
+ return r.value;
470
+ }
471
+
472
+ function distSeg(px, py, x1, y1, x2, y2) {
473
+ const dx = x2 - x1, dy = y2 - y1;
474
+ const len = dx * dx + dy * dy;
475
+ let t = len > 0 ? ((px - x1) * dx + (py - y1) * dy) / len : 0;
476
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
477
+ const ex = x1 + t * dx - px, ey = y1 + t * dy - py;
478
+ return Math.sqrt(ex * ex + ey * ey);
479
+ }
480
+
481
+ function distRect(px, py, x0, y0, x1, y1) {
482
+ const ex = px < x0 ? x0 - px : px > x1 ? px - x1 : 0;
483
+ const ey = py < y0 ? y0 - py : py > y1 ? py - y1 : 0;
484
+ return Math.sqrt(ex * ex + ey * ey);
485
+ }
486
+
487
+ /**
488
+ * The element nearest (x, y) within `tol` (both in the elements' own coordinate frame), or null.
489
+ * Returns `{ el, index, dist }`. On an exact tie the LATER element wins, because it is the one painted
490
+ * on top.
491
+ *
492
+ * `prefer(el)`, when given, ranks first: any preferred element within `tol` beats every other, and the
493
+ * nearest wins only among equals. The page prefers what the filter is SHOWING, so a switched-off line
494
+ * or label under the pointer can never steal a hover or a click from a line that is actually drawn
495
+ * there -- a switched-off label's box is at distance 0 all over, and would otherwise win every time.
496
+ */
497
+ export function hitTest(index, x, y, tol, prefer) {
498
+ if (!index || !index.count || !Number.isFinite(x) || !Number.isFinite(y) || !(tol >= 0)) return null;
499
+ const { minX, minY, maxX, maxY, cw, ch, gx, gy, start, ids, prim, kind, owner } = index;
500
+ // Rejected against the drawing's real bounds, never against cell arithmetic: `maxX / cw` can land a
501
+ // hair past the last cell in floating point, and a point just beyond a line's END was then refused.
502
+ if (x + tol < minX || x - tol > maxX || y + tol < minY || y - tol > maxY) return null;
503
+ const clampX = (v) => Math.min(gx - 1, Math.max(0, Math.floor((v - minX) / cw)));
504
+ const clampY = (v) => Math.min(gy - 1, Math.max(0, Math.floor((v - minY) / ch)));
505
+ const x0 = clampX(x - tol), x1 = clampX(x + tol), y0 = clampY(y - tol), y1 = clampY(y + tol);
506
+ let best = -1, bestD = Infinity, bestP = false;
507
+ for (let cy = y0; cy <= y1; cy++) {
508
+ for (let cx = x0; cx <= x1; cx++) {
509
+ const c = cy * gx + cx;
510
+ for (let k = start[c]; k < start[c + 1]; k++) {
511
+ // A primitive listed in several of these cells is measured more than once; the answer is the
512
+ // same each time, so that costs a few multiplications and never changes the result.
513
+ const p = ids[k];
514
+ const ax = prim[4 * p], ay = prim[4 * p + 1], bx = prim[4 * p + 2], by = prim[4 * p + 3];
515
+ const dd = kind[p] === 1 ? distRect(x, y, ax, ay, bx, by) : distSeg(x, y, ax, ay, bx, by);
516
+ if (dd > tol) continue;
517
+ const e = owner[p];
518
+ if (e === best) { if (dd < bestD) bestD = dd; continue; }
519
+ const pe = !!(prefer && prefer(index.elements[e]));
520
+ if (bestP && !pe) continue;
521
+ if ((pe && !bestP) || dd < bestD || (dd === bestD && e > best)) { bestD = dd; best = e; bestP = pe; }
522
+ }
523
+ }
524
+ }
525
+ return best < 0 ? null : { el: index.elements[best], index: best, dist: bestD };
526
+ }