@floless/app 0.140.0 → 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.
@@ -62,6 +62,9 @@
62
62
  --stage:hsl(222.2 84% 4.9%);--stage-text:hsl(210 40% 98%);--stage-panel:hsl(217.2 32.6% 11%);--stage-line:hsl(217.2 32.6% 17.5%);
63
63
  --stage-btn:hsl(217.2 32.6% 17.5%);--stage-btn-hover:hsl(217.2 32.6% 22%);--stage-ctrl:hsl(217.2 32.6% 17.5%);
64
64
  --stage-shadow:0 4px 14px rgba(0,0,0,.45);
65
+ /* The dark --mut, pinned for text ON the stage. The page's --mut turns mid-grey in light theme, and on
66
+ the always-dark stage that put the hover chip's 11px labels at ~3.7:1 (review finding). */
67
+ --stage-mut:hsl(215 20.2% 65.1%);
65
68
  --banner-shadow:0 -4px 18px rgba(0,0,0,.45); /* the conflict bar, thrown UPWARD from the page foot */
66
69
  }
67
70
  /* Light — the same slate/blue ramp as the shell's [data-theme="light"] (web/app.css), re-expressed
@@ -243,6 +246,8 @@ button:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
243
246
  .signoff-caption{margin:8px 0 14px;color:var(--mut);font-size:11px;line-height:1.4}
244
247
  .signoff-caption[hidden]{display:none}
245
248
  .signoff-actions{display:flex;justify-content:flex-end;gap:8px;flex:none}
249
+ .signoff-save-status{align-self:center;margin-right:auto;color:var(--mut);font-size:11.5px}
250
+ .signoff-save-status:empty{display:none}
246
251
  .signoff-actions button[hidden]{display:none}
247
252
  /* Themed tooltip — replaces native title= so no light OS tooltip leaks onto the dark theme. */
248
253
  /* Above EVERY surface it can be shown over, the sign-off overlay (z-index 90) included: a tooltip
@@ -324,6 +329,14 @@ button:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
324
329
  deliberately reuses button:disabled's own .5/cursor:default rather than inventing a third muted-row
325
330
  treatment beside .textlayer (.55) and .facet.dim (.4). */
326
331
  .opts label.novalue{opacity:.5;cursor:default}
332
+ /* A layer FloLess did not read (#990): every line on it was left out as annotation, so no element
333
+ stands behind the row and a tick would select nothing. Functionally the same refusal as .novalue, so
334
+ it shares .novalue's opacity instead of adding a tier; what tells the two apart is the tag, which
335
+ says so without a hover. The tag is sized off the row's own 12px text and uses only existing tokens. */
336
+ .opts label.notread{opacity:.5;cursor:default}
337
+ /* The tag INHERITS the row's text colour rather than taking a dimmer token: it already sits inside the
338
+ row's .5 opacity, and a second dimming left the one cue that needs no hover at ~1.8:1. */
339
+ .opts .tag-notread{flex:none;padding:0 6px;border:1px solid var(--mut);border-radius:9px;color:inherit;font-size:10px;line-height:15px;white-space:nowrap}
327
340
  input[type=checkbox][aria-disabled="true"]{cursor:default}
328
341
  /* Fully custom checkbox — the native unchecked widget is a white/grey square that breaks the dark baseline. */
329
342
  input[type=checkbox]{-webkit-appearance:none;appearance:none;width:14px;height:14px;flex:none;border:1px solid var(--ctrl-border);border-radius:3px;background:transparent;cursor:pointer;margin:0;vertical-align:middle}
@@ -341,18 +354,43 @@ input:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
341
354
  border:revert;background:revert;background-image:none}
342
355
  }
343
356
  .facet.dim{opacity:.4} .facet.dim .opts,.facet.dim .acts{pointer-events:none}
357
+ /* The per-list search. type=text, NOT type=search: Chromium paints its own light cancel glyph inside a
358
+ search field, the one native widget this surface would otherwise leak; the clear button below is ours.
359
+ Field recipe is .sheet-trigger's (--bg fill, --ctrl-border, --brand focus ring) — no new tokens. It
360
+ stays usable on a dimmed facet on purpose: finding a row is worth doing before you tick Match on. */
361
+ .facet-search{position:relative;margin:0 0 8px}
362
+ .facet-search[hidden]{display:none}
363
+ .facet-search-input{width:100%;box-sizing:border-box;background:var(--bg);color:var(--text);border:1px solid var(--ctrl-border);border-radius:6px;padding:5px 26px 5px 8px;font:12px var(--ui)}
364
+ .facet-search-input::placeholder{color:var(--mut)}
365
+ .facet-search-input:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
366
+ .facet-search-clear{position:absolute;top:50%;right:3px;transform:translateY(-50%);width:20px;height:20px;padding:0;display:flex;align-items:center;justify-content:center;background:transparent;border:0;color:var(--mut);font-size:11px;border-radius:4px}
367
+ .facet-search-clear:hover{background:var(--btn-hover);color:var(--text)}
368
+ .facet-search-clear[hidden]{display:none}
369
+ .facet-search-count{margin:-2px 0 6px;color:var(--mut);font-size:11px}
370
+ .facet-search-count[hidden]{display:none}
371
+ /* A row the search hides stays in the DOM — syncFacetChecks and markHotRows address rows by index, so
372
+ removing one would silently shift every checkbox after it. A class, never [hidden]: `.opts label`
373
+ sets display:flex, which beats the UA's [hidden] rule by origin. The one exception: a row Hover info
374
+ or the popover has lit stays visible, or the readout would point at a row nobody can see. */
375
+ .opts label.q-hide{display:none}
376
+ .opts label.q-hide.hot-row{display:flex}
344
377
  /* Two light-only corrections. An UNCHECKED checkbox here is a bare 1px ring on transparent, which
345
378
  on the light rail all but disappears — app.css fills its own checkbox for the same reason, so the
346
379
  transparent one is the outlier. And .textlayer's .55 is not symmetric across grounds: it composites
347
380
  to 4.7:1 on the dark panel but 3.8:1 on the light one, and these rows still carry a live checkbox. */
348
- [data-theme="light"] input[type=checkbox]{background:var(--bg)}
381
+ [data-theme="light"] input[type=checkbox]:not(:checked){background-color:var(--bg)}
349
382
  [data-theme="light"] .opts label.textlayer{opacity:.7}
350
383
  /* .novalue gets the same lift, and for the same reason .textlayer needed one: opacity does not
351
384
  composite symmetrically across grounds, so .5 that reads as "quiet" on the dark panel reads as
352
385
  "barely there" on the light one. This is the row LEAST able to afford that — it is the one
353
386
  carrying an explanation of why it cannot be ticked. */
354
387
  [data-theme="light"] .opts label.novalue{opacity:.65}
388
+ [data-theme="light"] .opts label.notread{opacity:.65}
355
389
  .hint{color:var(--mut);font-size:11px;line-height:1.5}
390
+ .filter-help{border:1px solid var(--line);background:var(--bg);border-radius:8px;padding:11px;display:grid;gap:9px}
391
+ .filter-help h2{margin:0!important;color:var(--text)!important;text-transform:none!important;font-size:12px!important;letter-spacing:0!important}
392
+ .filter-help p{margin:0;line-height:1.45;color:var(--mut);font-size:11px}
393
+ .filter-help .scope{color:var(--text);font-size:12px}
356
394
  /* #count is the footer's only child since #603 took the Fit/Zoom buttons out of the rail, so the
357
395
  flex row that used to wrap around them is gone with them — as are #count's width:100% and
358
396
  margin-bottom, which existed only to push the count onto its own line above those wrapped
@@ -361,11 +399,40 @@ footer{margin-top:auto;border-top:1px solid var(--line);padding-top:12px}
361
399
  #count{font-size:11px;color:var(--mut)}
362
400
  #count b{color:var(--text)}
363
401
  #stage{flex:1;position:relative;background:var(--stage);min-width:0}
364
- #canvas{width:100%;height:100%;cursor:grab;touch-action:none;display:block}
402
+ #canvas{width:100%;height:100%;cursor:grab;touch-action:none;display:block;position:relative;will-change:transform}
365
403
  #canvas.dragging{cursor:grabbing}
366
- #canvas image.bg{opacity:.28;pointer-events:none}
404
+ /* TWO stacked SVGs sharing one viewBox (#1527), and the split is what keeps Hover info smooth at the
405
+ per-sheet cap. #canvas carries only the linework -- up to 100,000 paths -- and is promoted to its own
406
+ compositor layer (will-change above), so it is painted once and then only moved; #under, beneath it,
407
+ carries what CHANGES while the pointer sweeps: the background raster and the hover halo. With the halo
408
+ inside #canvas, every halo change re-painted and re-layerised all 100,000 paths -- measured in the
409
+ real browser at the cap, 50-80ms of main thread per line crossed. #under is inert to the pointer;
410
+ #canvas stays the one event target, and setVB keeps the two viewBoxes identical. */
411
+ #under{position:absolute;inset:0;width:100%;height:100%;display:block;pointer-events:none}
412
+ #under image.bg{opacity:.28;pointer-events:none}
367
413
  #canvas path.el{pointer-events:stroke}
368
- #canvas text.el{pointer-events:all;cursor:pointer;user-select:none}
414
+ #canvas text.el{pointer-events:all;user-select:none}
415
+ /* "Pointing here reads this line." The canvas is cursor:grab everywhere, so an element under the
416
+ pointer looked exactly like empty stage and click-to-sample was only ever found by accident — the
417
+ report this slice answers. crosshair is the standard sample/pick cursor; `copy` was rejected because
418
+ its plus badge promises that clicking ADDS the value, and clicking opens a popover. It replaces
419
+ text.el's old cursor:pointer for the same reason the popover's three rows read alike: one gesture
420
+ must not wear two affordances depending on whether it lands on a line or a label.
421
+ `:not(.dragging)` so #canvas.dragging's grabbing still wins mid-pan. The honest residual: a press on
422
+ an element STILL starts a pan (the pointerdown handler arms a drag unconditionally), so the
423
+ crosshair means "pointing here tells you something", never "this is a click target only".
424
+ `.is-context` is pointer-events:none and so never gets it — correct, because an element the filter
425
+ is hiding cannot be sampled at all. Unconditional, NOT gated on Hover info: it is the cheapest fix
426
+ to the reported complaint and it teaches click-to-sample to someone who never turns the mode on. */
427
+ #canvas:not(.dragging) path.el:hover,#canvas:not(.dragging) text.el:hover{cursor:crosshair}
428
+ /* The hovered element's casing, painted UNDER the linework — #hot lives in #under, the SVG stacked
429
+ beneath #canvas — so the line keeps its own colour and the swatch in the readout still
430
+ agrees with the stroke on screen. A recolour to --brand was rejected outright: PALETTE[0] IS
431
+ hsl(217 91% 60%), the same value as --brand, so a blue line highlighted blue is invisible. Drawn as
432
+ a CLONE rather than a class on the node so the drawing itself is never altered, and so a probe can
433
+ assert the halo's `d` equals the hovered element's. No dasharray on the clone: a casing with gaps
434
+ in it reads as two highlights. */
435
+ #hot path,#hot text,#hot rect{stroke:var(--stage-text);stroke-opacity:.42;stroke-width:7;vector-effect:non-scaling-stroke;stroke-linecap:round;stroke-linejoin:round;fill:none;pointer-events:none}
369
436
  /* Raster-less baked sheets cannot retain the confidential background. Keep their full vector sheet as
370
437
  an explicit, non-interactive fallback; raster-backed sheets mount selected vectors only. */
371
438
  #canvas .el.is-context{opacity:.2;pointer-events:none}
@@ -376,7 +443,9 @@ footer{margin-top:auto;border-top:1px solid var(--line);padding-top:12px}
376
443
  like there: it wears the stage's dark furniture (see :root), and #empty.show covers the stage —
377
444
  so on a light theme it was a dark pill floating on a light pane, an artifact of two correct
378
445
  decisions meeting. `~` and not a descendant selector: they are siblings inside #stage. */
379
- #empty.show ~ #zoombar{display:none}
446
+ #empty.show ~ #zoombar,
447
+ #empty.show ~ #hoverbar,
448
+ #empty.show ~ #hoverNote{display:none}
380
449
  #empty>div{max-width:44ch}
381
450
  #empty h1{margin:0;font-size:16px;font-weight:600;color:var(--text)}
382
451
  #empty .empty-body{margin:8px 0 0;line-height:1.55;color:var(--mut)}
@@ -386,7 +455,10 @@ body.publication-blocked #panel,
386
455
  body.publication-blocked #panelRail,
387
456
  body.publication-blocked #panelStub,
388
457
  body.publication-blocked #canvas,
389
- body.publication-blocked #zoombar{display:none}
458
+ body.publication-blocked #under,
459
+ body.publication-blocked #zoombar,
460
+ body.publication-blocked #hoverbar,
461
+ body.publication-blocked #hoverNote{display:none}
390
462
  body.publication-blocked #stage{display:flex}
391
463
  body.publication-blocked #empty{position:static;flex:1}
392
464
  /* max-width earns its place: #zoombar is absolutely positioned with only a LEFT offset, so nothing
@@ -423,6 +495,14 @@ body.publication-blocked #empty{position:static;flex:1}
423
495
  containment container-type brings would not reach it. It is left undone as a judgement call, not
424
496
  a blocked one: it is a second layout mechanism on this surface to serve a window width at which
425
497
  the drawing area shows nothing at all.
498
+ EVERY FIGURE ABOVE WAS MEASURED WITH TWO BUTTONS. Hover info added a third plus a divider, which
499
+ moves the width at which the bar first wraps; the re-measured value is recorded here, next to the
500
+ figures it supersedes, rather than left for the next reader to trust stale numbers.
501
+ THREE-BUTTON MEASUREMENT (real browser, 770px window with the Filters panel at its 520px max): the
502
+ bar is 240px on one row and first wraps once #stage is narrower than ~264px (its width plus the two
503
+ 12px insets) -- one row at a 290px stage, two rows at 250px, every button fully visible and inside
504
+ the stage in both. Measured above 768px on purpose: below it the harness emulates a touch device,
505
+ where `@media not (hover:hover)` hides Hover info outright and the bar is back to two buttons.
426
506
  On the button rule: min-width:0 and overflow:hidden are ALTERNATIVE ways to defeat a flex item's
427
507
  content-based automatic minimum size, not a pair — measured by toggling each, and removing either
428
508
  one alone still let the button shrink to 46px, while removing BOTH pinned it at its 86px content
@@ -435,6 +515,98 @@ body.publication-blocked #empty{position:static;flex:1}
435
515
  #zoombar{position:absolute;left:12px;bottom:12px;max-width:calc(100% - 24px);overflow:hidden;display:flex;flex-wrap:wrap;gap:6px;background:var(--stage-panel);border:1px solid var(--stage-line);border-radius:8px;padding:6px 8px;box-shadow:var(--stage-shadow)}
436
516
  #zoombar button{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;background:var(--stage-btn);border-color:var(--stage-ctrl);color:var(--stage-text)}
437
517
  #zoombar button:hover{background:var(--stage-btn-hover)}
518
+ /* Hover info is a READ tool, not a framing control -- the divider says so, so the bar reads as the
519
+ framing pair plus one canvas tool rather than three commands of one kind. aria-hidden: it is
520
+ decoration, and the buttons' own names already say what each does. */
521
+ #zoombar .zb-sep{width:1px;align-self:stretch;background:var(--stage-line);flex:none}
522
+ /* Hover info ON. It reuses button.primary's exact fill — the "this is active" language the page
523
+ already speaks — so the pressed state costs no new colour. aria-pressed rather than a switch
524
+ component: this surface ships checkboxes and buttons and nothing else, and inventing a third
525
+ control vocabulary is precisely what the locked baseline forbids. */
526
+ #zoombar button[aria-pressed="true"]{background:var(--brand);border-color:var(--brand);color:var(--brand-ink)}
527
+ #zoombar button[aria-pressed="true"]:hover{background:var(--brand-hover)}
528
+ /* Forced colors flattens the brand fill, so the pressed state needs a cue that is not a colour. */
529
+ @media (forced-colors:active){#zoombar button[aria-pressed="true"]{outline:2px solid currentColor;outline-offset:-3px}}
530
+ /* The readout: a chip ANCHORED at the line being read. An earlier cut of this slice docked it in the
531
+ stage's top-right corner and the second review took that apart on the task itself: finding the one
532
+ layer to untick is a fast sweep across many lines, and a corner readout costs an eye trip from the
533
+ line to the corner and back on every candidate -- the very cost the mode exists to remove.
534
+ The two objections that sent it to the corner are answered by WHEN it moves, not where it sits:
535
+ it is placed once when the hovered ELEMENT changes, never per pointermove, so there is no
536
+ flicker, and it sits 14px below-right of the point where the line was entered (flipping left/up
537
+ at the stage edge -- see placeChip), off the stroke it names (5px while the mode is on).
538
+ Three rows, the same key / swatch / value grid as #eye, so the readout and the popover a click
539
+ opens read as one surface at two sizes.
540
+ pointer-events:none is LOAD-BEARING: it floats over #canvas, and a press landing on it would
541
+ neither pan nor sample. NO transition, deliberately -- a fade per element is flicker by another
542
+ name; do not "improve" this with one. */
543
+ #hoverbar{position:absolute;left:0;top:0;display:grid;grid-template-columns:auto auto minmax(0,1fr);gap:4px 8px;align-items:center;max-width:min(360px, calc(100% - 16px));background:var(--stage-panel);border:1px solid var(--stage-line);border-radius:8px;padding:8px 10px;box-shadow:var(--stage-shadow);color:var(--stage-text);font-size:12px;pointer-events:none;z-index:40}
544
+ /* Explicit and load-bearing: the author display:grid above beats the UA's [hidden] rule by origin. */
545
+ #hoverbar[hidden]{display:none}
546
+ #hoverbar .hb-k{color:var(--stage-mut);font-size:11px;text-transform:uppercase;letter-spacing:.06em}
547
+ #hoverbar .hb-v{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:flex;min-width:0}
548
+ /* A layer name clips from the WRONG END under a single ellipsised span. Real names look like
549
+ `114078-X_2nd Floor Framing Plan|S-ANNO-BEAM-STEL`, where every layer on a sheet shares the prefix
550
+ and the tail after the last `|` is the entire discriminator -- so `...Framing Plan|S-...` shows forty
551
+ characters that are identical on every row and none of the one part that differs. The prefix is
552
+ muted and takes the clipping; the tail never shrinks. */
553
+ #hoverbar .hb-pre{color:var(--stage-mut);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
554
+ #hoverbar .hb-tail{flex:none;white-space:nowrap}
555
+ #hoverbar .hb-sw{width:12px;height:12px;border-radius:3px;border:1px solid var(--stage-ctrl);flex:none}
556
+ /* "not in the list": the value is real, but the Filters panel has no row to light for it — said here,
557
+ on the readout, rather than leaving the user hunting a list for a row that does not exist. */
558
+ #hoverbar .hb-norow{color:var(--stage-mut);margin-left:6px;flex:none;white-space:nowrap}
559
+ #hoverbar .hb-norow[hidden]{display:none}
560
+ /* A line the filter has switched off (#1527): read out exactly like a shown one, plus this. Its own row
561
+ across the whole grid, not a suffix -- a suffix would compete with the layer tail for the one line
562
+ that must never clip. The muted-trailing-note idiom `.hb-norow` already set, not a badge. */
563
+ #hoverbar .hb-off{grid-column:1/-1;color:var(--stage-mut);font-size:11px}
564
+ #hoverbar .hb-off[hidden]{display:none}
565
+ /* While Hover info is on, the WHOLE drawing takes the crosshair, not just the stroke under it:
566
+ the per-element rule above only fires once the pointer is already on a line, so on its own it
567
+ advertises nothing about the mode. With the mode on, "am I on a line" is answered by the halo
568
+ instead. */
569
+ #canvas.hoverinfo:not(.dragging){cursor:crosshair}
570
+ /* While Hover info is on, the linework takes NO pointer input at all (#1527). What the pointer is on is
571
+ answered by the hit test over the drawing data (steel-filter-hit.js) -- within 4 CSS px of ANY line,
572
+ shown or switched off -- so the browser's own per-path hit test, 100,000 paths deep at the cap, is
573
+ work whose answer nobody reads. It replaces the 5px stroke this mode used to draw lines at, which
574
+ existed only to widen a 2.2px DOM hit target to about +/-2.5px; the data hit test's +/-4px is wider
575
+ at every zoom and costs no repaint. ONLY once that sheet's grid is built (`.hit-ready`): until then the
576
+ mounted lines keep answering through the DOM exactly as before, or the mode would go blind for the
577
+ first fraction of a second on a large sheet (Codex review). */
578
+ /* On the ELEMENTS, not the group: `path.el` / `text.el` set pointer-events themselves, and an explicit
579
+ value on a child beats one inherited from #overlay (review finding -- a group-level rule did nothing). */
580
+ #canvas.hoverinfo.hit-ready #overlay .el{pointer-events:none}
581
+ /* A label's casing is a box around its glyphs, not a stroke along a line: a thinner outline reads as a
582
+ frame rather than a blob. */
583
+ #hot rect{stroke-width:2}
584
+ /* A switched-off line's GHOST (#1527): the line's own shape, in its layer colour, faint, at the overlay's
585
+ normal weight -- painted inside #hot on top of the casing and under the linework. On a raster-backed
586
+ sheet a switched-off line is not mounted at all, so without it the casing would be a halo around
587
+ nothing. The casing itself is deliberately the SAME as a shown line's: it is the only cue on screen
588
+ that something is there, and a dimmer or dashed one would starve exactly that. The stroke colour is
589
+ set inline from the layer, which beats the #hot rule above by origin. It paints OVER the casing,
590
+ because it comes after it inside #hot. */
591
+ #hot path.hot-ghost{stroke-opacity:.45;stroke-width:2.2}
592
+ /* A pointer affordance on a device with no pointer is dead chrome — and hiding only the button would
593
+ strand a persisted-ON readout with nothing able to switch it off, so both go. The script checks the
594
+ same query before it binds anything. */
595
+ @media not (hover:hover){#hoverInfo,#hoverbar,#hoverNote{display:none}}
596
+ /* #1550: "some curves on this sheet can't be read everywhere". The stage furniture #zoombar wears, with
597
+ the amber left rail .signoff-notice uses as this page's "at risk" signal -- no new colour. The rail
598
+ alone carries the amber: the title stays --stage-text, because the light theme's --warn is too dark
599
+ to read as text on this panel (which is dark on both themes). `bottom` is set by syncHoverNote from
600
+ #zoombar's real height, so the note sits directly above the Hover info toggle it qualifies. */
601
+ #hoverNote{position:absolute;left:12px;bottom:58px;max-width:min(360px, calc(100% - 24px));background:var(--stage-panel);border:1px solid var(--stage-line);border-left:3px solid var(--warn);border-radius:0 8px 8px 0;padding:8px 10px;box-shadow:var(--stage-shadow);color:var(--stage-mut);font-size:12px;line-height:1.5;pointer-events:none;z-index:30}
602
+ #hoverNote[hidden]{display:none}
603
+ #hoverNote b{display:block;color:var(--stage-text);font-weight:600;margin-bottom:2px}
604
+ /* The hovered element's own row in each facet: the checkbox the user is about to untick, lit where it
605
+ sits. Reuses the option-row hover fill and the left-accent idiom .sheet-option.selected already
606
+ carries — no new colour, no new shape. This is the half of the feature that answers the actual
607
+ complaint: reading a 46-character layer name off the chip and then hunting it by eye in a 40-row list
608
+ is the same trial and error, relocated. */
609
+ #panel .opts label.hot-row{background:var(--btn);border-radius:4px;box-shadow:inset 2px 0 0 var(--brand)}
438
610
  /* eyedropper popover */
439
611
  #eye{position:fixed;display:none;z-index:50;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px;box-shadow:var(--shadow-lg);min-width:210px}
440
612
  #eye.show{display:block}
@@ -445,6 +617,19 @@ body.publication-blocked #empty{position:static;flex:1}
445
617
  #eye .erow .sw{width:12px;height:12px;border-radius:3px;border:1px solid var(--ctrl-border);flex:none}
446
618
  #eye .erow button{font-size:11px;padding:2px 7px}
447
619
  #eye .eall{margin-top:8px;width:100%}
620
+ #eye .eall[hidden]{display:none}
621
+ /* The pick is a line the filter has switched off (#1527). One muted line under the header, which stays
622
+ "Picked element" for every pick. */
623
+ #eye .eoff{font-size:11px;color:var(--mut);margin:-4px 0 6px}
624
+ /* The ORIGINAL-drawing read (#1528): the same popover, read-only. It names what the source PDF has at a
625
+ clicked empty spot, so it is capped in width (a layer name there can be 60+ characters) and carries one
626
+ muted sentence saying what FloLess did with it. The stepper sits in the header beside the close button,
627
+ styled as that button is: no second scroll container, no new colour. */
628
+ #eye.identify{max-width:340px}
629
+ #eye .enote{font-size:11px;color:var(--mut);line-height:1.45;margin-top:6px}
630
+ #eye .estep{display:flex;align-items:center;gap:4px;margin-left:auto;margin-right:6px;text-transform:none;letter-spacing:0}
631
+ #eye .estep[hidden]{display:none}
632
+ #eye .estep button{padding:0 6px;font-size:12px;line-height:18px}
448
633
  </style>
449
634
  </head>
450
635
  <body>
@@ -489,6 +674,11 @@ body.publication-blocked #empty{position:static;flex:1}
489
674
  </header>
490
675
  <div id="app">
491
676
  <aside id="panel">
677
+ <section class="filter-help" id="filterHelp">
678
+ <h2>What should this read see?</h2>
679
+ <p class="scope" id="filterScope"></p>
680
+ <p id="filterCanvasRule"></p>
681
+ </section>
492
682
  <section id="modes">
493
683
  <h2>Match on</h2>
494
684
  <!-- The id sits on the INPUT, not on the wrapping <label>. Instructor's `activate()` (the `?`
@@ -500,18 +690,44 @@ body.publication-blocked #empty{position:static;flex:1}
500
690
  <label><input type="checkbox" name="dim" value="layer" data-command-id="filter.match-on" checked /> Layer</label>
501
691
  <label><input type="checkbox" name="dim" value="thickness" data-command-id="filter.match-on" /> Thickness</label>
502
692
  <label><input type="checkbox" name="dim" value="color" data-command-id="filter.match-on" /> Color</label>
503
- <p class="hint">Checked criteria must all match (AND).</p>
693
+ <p class="hint">Checked properties must all match. Use these controls to correct the selection.</p>
504
694
  </section>
505
695
  <section class="facet" id="facet-layers">
506
696
  <h2>Layers <span class="acts"><button data-command-id="filter.facet-all" data-all="layers">all</button><button data-command-id="filter.facet-none" data-none="layers">none</button></span></h2>
697
+ <!-- Shown only on a list long enough to need it (see FACET_SEARCH_MIN). While a query is on, this
698
+ list's all/none act on the MATCHING rows only, and say how many — the owner's call. -->
699
+ <div class="facet-search" hidden>
700
+ <label class="sr-only" for="facet-layers-q">Search layers</label>
701
+ <input type="text" id="facet-layers-q" class="facet-search-input" data-facet="layers" data-command-id="filter.facet-search" placeholder="Search layers…" autocomplete="off" spellcheck="false" />
702
+ <button type="button" class="facet-search-clear" data-clear="layers" data-command-id="filter.facet-search-clear" aria-label="Clear search" data-tip="Clear the search and show the whole list" hidden>✕</button>
703
+ </div>
704
+ <p class="facet-search-count" id="facet-layers-count" role="status" aria-live="polite" hidden></p>
705
+ <!-- #990: how many layers FloLess did not read. Filled by buildFacet; hidden when there are none. -->
706
+ <p class="hint facet-notread" id="facet-layers-notread" hidden></p>
507
707
  <div class="opts"></div>
508
708
  </section>
509
709
  <section class="facet" id="facet-thicknesses">
510
710
  <h2>Thicknesses <span class="acts"><button data-command-id="filter.facet-all" data-all="thicknesses">all</button><button data-command-id="filter.facet-none" data-none="thicknesses">none</button></span></h2>
711
+ <!-- Shown only on a list long enough to need it (see FACET_SEARCH_MIN). While a query is on, this
712
+ list's all/none act on the MATCHING rows only, and say how many — the owner's call. -->
713
+ <div class="facet-search" hidden>
714
+ <label class="sr-only" for="facet-thicknesses-q">Search thicknesses</label>
715
+ <input type="text" id="facet-thicknesses-q" class="facet-search-input" data-facet="thicknesses" data-command-id="filter.facet-search" placeholder="Search thicknesses…" autocomplete="off" spellcheck="false" />
716
+ <button type="button" class="facet-search-clear" data-clear="thicknesses" data-command-id="filter.facet-search-clear" aria-label="Clear search" data-tip="Clear the search and show the whole list" hidden>✕</button>
717
+ </div>
718
+ <p class="facet-search-count" id="facet-thicknesses-count" role="status" aria-live="polite" hidden></p>
511
719
  <div class="opts"></div>
512
720
  </section>
513
721
  <section class="facet" id="facet-colors">
514
722
  <h2>Colors <span class="acts"><button data-command-id="filter.facet-all" data-all="colors">all</button><button data-command-id="filter.facet-none" data-none="colors">none</button></span></h2>
723
+ <!-- Shown only on a list long enough to need it (see FACET_SEARCH_MIN). While a query is on, this
724
+ list's all/none act on the MATCHING rows only, and say how many — the owner's call. -->
725
+ <div class="facet-search" hidden>
726
+ <label class="sr-only" for="facet-colors-q">Search colours</label>
727
+ <input type="text" id="facet-colors-q" class="facet-search-input" data-facet="colors" data-command-id="filter.facet-search" placeholder="Search colours…" autocomplete="off" spellcheck="false" />
728
+ <button type="button" class="facet-search-clear" data-clear="colors" data-command-id="filter.facet-search-clear" aria-label="Clear search" data-tip="Clear the search and show the whole list" hidden>✕</button>
729
+ </div>
730
+ <p class="facet-search-count" id="facet-colors-count" role="status" aria-live="polite" hidden></p>
515
731
  <div class="opts"></div>
516
732
  </section>
517
733
  <!-- Viewport controls do NOT live here. This panel is about WHICH ELEMENTS are shown (the
@@ -540,8 +756,15 @@ body.publication-blocked #empty{position:static;flex:1}
540
756
  <button data-command-id="filter.panel-collapse" type="button" id="panelGrip" aria-controls="panel" aria-expanded="true" aria-label="Collapse Filters panel" data-tip="Collapse Filters panel"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="m10 3-5 5 5 5"/></svg></button>
541
757
  </div>
542
758
  <main id="stage">
543
- <svg id="canvas" preserveAspectRatio="xMidYMid meet">
759
+ <svg id="under" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
544
760
  <image class="bg"></image>
761
+ <!-- The hover casing. In #under, the SVG stacked BENEATH #canvas, so the halo goes under the
762
+ linework and the line keeps its own colour (see #under's CSS for why it is a separate SVG).
763
+ It sits OUTSIDE #overlay, so buildOverlay()'s replaceChildren() never removes the group;
764
+ buildOverlay empties it on purpose, via hoverClear(). -->
765
+ <g id="hot" fill="none" aria-hidden="true"></g>
766
+ </svg>
767
+ <svg id="canvas" preserveAspectRatio="xMidYMid meet">
545
768
  <g id="overlay" fill="none"></g>
546
769
  </svg>
547
770
  <div id="empty" role="status" aria-live="polite">
@@ -564,16 +787,43 @@ body.publication-blocked #empty{position:static;flex:1}
564
787
  <p class="hint" style="margin-top:8px;max-width:340px">Ask your terminal AI to prepare the Drawing Filter. Its layers, line weights and colours will appear here automatically when ready.</p>
565
788
  </div>
566
789
  </div>
567
- <!-- The ONLY fit/zoom controls. Labels stay terse so both stay fully legible before the bar's
790
+ <!-- The ONLY fit/zoom controls -- plus, after the divider, Hover info, which is a canvas READ tool
791
+ rather than a framing one (so "only fit/zoom" still holds of the framing pair). Labels stay terse so all three stay fully legible before the bar's
568
792
  max-width cap (see its CSS) starts compressing them in a narrow Workspaces pane — the cap
569
793
  means longer text costs legibility, never an overhanging bar. "Zoom steel" not "Steel": a
570
794
  bare noun read as a category, not a command. data-tip (never title=) carries the full
571
795
  sentence. -->
572
- <div id="zoombar"><button id="fit2" data-command-id="filter.fit" data-tip="Fit the whole page in view">Fit</button><button id="zoomsteel2" data-command-id="filter.zoom-steel" data-tip="Zoom to fit the steel elements on this sheet">Zoom steel</button></div>
796
+ <div id="zoombar"><button id="fit2" data-command-id="filter.fit" data-tip="Fit the whole page in view">Fit</button><button id="zoomsteel2" data-command-id="filter.zoom-steel" data-tip="Zoom to fit the steel elements on this sheet">Zoom steel</button><span class="zb-sep" aria-hidden="true"></span><button id="hoverInfo" type="button" aria-pressed="false" data-command-id="filter.hover-info" data-tip="Point at any line or label, shown or switched off, to read its layer, thickness and colour — and light up its rows in the Filters panel. Click a switched-off line to see what to tick to bring it back. Background-only linework, on layers the drawing read never picked up, can’t be read by pointing; click an empty spot to ask the original drawing what is there, where the original drawing is available.">Hover info</button></div>
797
+ <!-- The hover readout, anchored at the line it names (see #hoverbar's CSS for why it is not docked).
798
+ Hidden until the pointer is on a line with the mode on; hidden again when it leaves the line, or
799
+ when a click opens the popover (which then says the same thing).
800
+ aria-hidden, and NO live region. This page already carries polite live regions — #saved and
801
+ #saveRequiredStatus beside the stat chip among them; announcing a new layer name on every target change would talk straight
802
+ over "Ready — press Save filter". Everything here is a visual mirror of what the facet rows
803
+ already expose accessibly, and the toggle's aria-pressed carries the only state a screen
804
+ reader needs. -->
805
+ <div id="hoverbar" hidden aria-hidden="true">
806
+ <span class="hb-k">Layer</span><span class="hb-sw" id="hbLayerSw"></span><span class="hb-v"><span class="hb-pre" id="hbLayerPre"></span><span class="hb-tail" id="hbLayer">—</span><span class="hb-norow" id="hbLayerNo" hidden>· not in the list</span></span>
807
+ <span class="hb-k">Thickness</span><span></span><span class="hb-v"><span id="hbThick">—</span><span class="hb-norow" id="hbThickNo" hidden>· not in the list</span></span>
808
+ <span class="hb-k">Color</span><span class="hb-sw" id="hbColorSw"></span><span class="hb-v"><span id="hbColor">—</span><span class="hb-norow" id="hbColorNo" hidden>· not in the list</span></span>
809
+ <span class="hb-off" id="hbOff" hidden></span>
810
+ </div>
811
+ <!-- #1550. Said whenever Hover info is on and some curves on THIS sheet could not be traced in full,
812
+ so pointing at parts of them may read nothing: without it, a curve going quiet under the pointer
813
+ looks exactly like "no line here". Stacked on #zoombar, beside the toggle it qualifies, and
814
+ hidden with it. Not interactive and not dismissible: it goes away with the mode or the sheet,
815
+ and a dismissed warning would stay dismissed while the curves were still unreadable.
816
+ The VISIBLE note is aria-hidden; screen readers get the same words from #hoverNoteLive, a polite
817
+ status that is ALWAYS in the tree and only has its text set and cleared. A live region that
818
+ itself appears out of display:none is not reliably announced (review finding), text inserted
819
+ into one already present is. It changes only on a sheet switch or a mode toggle, so it cannot
820
+ talk over the hover readout the way a per-target region would. -->
821
+ <div id="hoverNote" aria-hidden="true" hidden><b id="hoverNoteTitle"></b><span id="hoverNoteBody"></span></div>
822
+ <div id="hoverNoteLive" class="sr-only" role="status" aria-live="polite"></div>
573
823
  </main>
574
824
  </div>
575
825
  <div id="eye">
576
- <div class="ehead"><span>Picked element</span><button id="eyeClose" style="padding:0 6px">✕</button></div>
826
+ <div class="ehead"><span id="eyeTitle">Picked element</span><span class="estep" id="eyeStep" hidden><button type="button" id="eyePrev" data-command-id="filter.identify-step" data-tip="Show the previous line at this spot" aria-label="Previous line at this spot">‹</button><span id="eyeStepLabel" aria-live="polite"></span><button type="button" id="eyeNext" data-command-id="filter.identify-step" data-tip="Show the next line at this spot" aria-label="Next line at this spot">›</button></span><button id="eyeClose" style="padding:0 6px">✕</button></div>
577
827
  <div id="eyeBody"></div>
578
828
  <button class="eall primary" id="eyeAddAll" data-command-id="filter.eyedropper-add">Add all to filter</button>
579
829
  </div>
@@ -594,6 +844,7 @@ body.publication-blocked #empty{position:static;flex:1}
594
844
  <div class="signoff-list" id="signoffList"></div>
595
845
  <p class="signoff-caption" id="signoffCaption">Row counts are elements, not split by page role. The total above is lines this read may dismiss.</p>
596
846
  <div class="signoff-actions">
847
+ <span id="signoffSaveStatus" class="signoff-save-status" role="status" aria-live="polite"></span>
597
848
  <button id="signoffCancel" data-command-id="filter.signoff-cancel">Cancel</button>
598
849
  <button id="signoffApprove" class="primary" data-command-id="filter.signoff-approve">Approve these exclusions</button>
599
850
  <button id="signoffClose" data-command-id="filter.signoff-close" hidden>Close</button>
@@ -608,14 +859,22 @@ body.publication-blocked #empty{position:static;flex:1}
608
859
  The reporter tells the shell which surface is on screen (so the `?` sheet can put this
609
860
  screen's commands first) and forwards `?`/F1 up, because a keydown inside an iframe never
610
861
  reaches the shell's own handler. This surface arms nothing, so its snapshot is just its identity — see commands-filter.js. -->
862
+ <script src="filter-guidance.js"></script>
611
863
  <script src="commands.js"></script>
612
864
  <script src="commands-filter.js"></script>
613
865
  <script src="instructor-reporter.js"></script>
614
866
  <script>window.InstructorReporter.mount({ surface: 'steel-filter' });</script>
867
+ <!-- An Esc this page leaves unused closes the shell's editor overlay (#1571). -->
868
+ <script src="overlay-escape.js"></script>
869
+ <!-- While the sign-off dialog is up, Esc is the dialog's even when it does nothing (a save in flight ignores it). -->
870
+ <script>window.OverlayEscape.mount({ idle: function () { var o = document.getElementById('signoffOverlay'); return !o || o.hidden; } });</script>
615
871
 
616
872
  <script type="module">
617
- import { matchesActive, modeDims, canonicalMode, selFromFilter, eyedropperAdd, countShown, liveOverlayElements, bgRect, textFontSize, applySelToFilter, hasUnsupportedSingleSheetFilter, normalizeFilter, liveUpdateAction, statChip, newMutationId, sheetLabel, dismissibleFacetValues, FACET_DIMS, FACET_DIM_BY_CONTROL, MODE_ORDER, facetKey, NOTE_TEXT } from './steel-filter-core.js';
873
+ import { matchesActive, modeDims, canonicalMode, selFromFilter, eyedropperAdd, eyedropperHas, eyedropperRemove, countShown, liveOverlayElements, bgRect, textBox, textDraw, textString, applySelToFilter, hasUnsupportedSingleSheetFilter, normalizeFilter, liveUpdateAction, statChip, newMutationId, sheetLabel, dismissibleFacetValues, switchOffBlockers, FACET_DIMS, FACET_DIM_BY_CONTROL, MODE_ORDER, facetKey, facetRowIndicesFor, NOTE_TEXT, coarseCurveNote } from './steel-filter-core.js';
618
874
  import { checkpointStandard } from './checkpoint-standard.js';
875
+ import { filterAiBlockedLayerKeys, filterAiTouchesUnreadLayer, parseFilterAiProposal } from './filter-ai-proposal.js';
876
+ import { readOnlyFilterContext, rankFilterControls, filterViewFingerprint } from './filter-ai-context.js';
877
+ import { hitIndexBuilder, hitTest, textRunRect } from './steel-filter-hit.js';
619
878
 
620
879
  const APP_ID = new URLSearchParams(location.search).get('app') || '';
621
880
  // Workspaces use a project-keyed contract; an empty project id is the app-keyed workflow surface.
@@ -638,7 +897,8 @@ const safeColor = c => /^#[0-9a-fA-F]{3,8}$/.test(String(c)) ? c : 'transparent'
638
897
 
639
898
  const svg = document.getElementById('canvas');
640
899
  const overlay = document.getElementById('overlay');
641
- const bgImg = svg.querySelector('image.bg');
900
+ const under = document.getElementById('under');
901
+ const bgImg = under.querySelector('image.bg');
642
902
  const countEl = document.getElementById('count');
643
903
  const savedEl = document.getElementById('saved');
644
904
  const saveRequiredStatus = document.getElementById('saveRequiredStatus');
@@ -651,6 +911,7 @@ let mode = 'layer';
651
911
  let nodes = []; // [{ node, el }]
652
912
  let layerColor = {};
653
913
  let dirty = false;
914
+ let savedState = '';
654
915
  let serverEtag = null; // the server's tag for the contract we loaded
655
916
  let conflicted = false; // latched once a save is refused, so a second click does not re-fire it
656
917
  let sheets = []; // normalizeFilter(F).sheets — per-sheet geometry
@@ -659,6 +920,329 @@ let parseWarned = false; // latch, so a broken stream cannot spam the console
659
920
  let checkpointSaveBlocked = false; // a half-completed checkpoint must reload before it can be retried safely
660
921
  let saveInFlight = false; // parent checkpoint polling must not re-enable Save during the queued write
661
922
 
923
+ const filterHelp = window.FilterGuidance;
924
+ document.getElementById('filterScope').textContent = filterHelp.scope;
925
+ document.getElementById('filterCanvasRule').textContent = filterHelp.canvas;
926
+ // AI help about this filter lives in the shell's AI Chat panel; this page has no chat surface of its own. It owns
927
+ // the drawing, so it captures the context, keeps each request's base selection, and applies or undoes
928
+ // a reviewed suggestion; the chat reaches all of that through `window.__floFilterAi` below.
929
+ let filterAiFocused = null;
930
+ let filterAiSheetEpoch = 0; // Navigation changes the evidence used for a Change suggestion, even when facets are global.
931
+ let filterAiUndo = null;
932
+ // One record per request sent from THIS page instance. A reload or another window has none, so a
933
+ // suggestion shown in the chat can never be applied against a selection it was not made from.
934
+ const filterAiRecords = new Map();
935
+ const FILTER_AI_UNKNOWN = 'This suggestion was made before the Drawing Filter was last opened or reloaded. Ask again from the current filter to apply it.';
936
+ const FILTER_AI_EDITED = 'You edited the selection after applying this suggestion, so Undo is no longer available. Your edits remain.';
937
+ let filterAiNotifyQueued = false;
938
+ /** Tell the shell's AI Chat that something it shows about this filter may have changed. */
939
+ function notifyFilterAi(){
940
+ if(filterAiNotifyQueued) return;
941
+ filterAiNotifyQueued = true;
942
+ queueMicrotask(() => {
943
+ filterAiNotifyQueued = false;
944
+ try { if(window.parent !== window) window.parent.dispatchEvent(new CustomEvent('floless:filter-ai-changed')); }
945
+ catch { /* a detached or cross-origin parent has no chat to repaint */ }
946
+ });
947
+ }
948
+ function retireFilterAiUndo(reason){
949
+ if(!filterAiUndo) return;
950
+ const record = filterAiRecords.get(filterAiUndo.requestId);
951
+ filterAiUndo = null;
952
+ if(record && reason) record.note = reason;
953
+ notifyFilterAi();
954
+ }
955
+ function retireFilterAiUndoOnSelectionChange(before){
956
+ if(!before || !filterAiUndo) return false;
957
+ const after=filterAiSelectionCopy();
958
+ const changed=before.mode !== after.mode || ['layers','thicknesses','colors'].some(facet =>
959
+ before[facet].size !== after[facet].size || [...before[facet]].some(value => !after[facet].has(value)));
960
+ if(changed) retireFilterAiUndo(FILTER_AI_EDITED);
961
+ return changed;
962
+ }
963
+ function focusFilterFacet(dim,label,key=facetKey(dim,label)){
964
+ filterAiFocused = {dimension:dim,label:String(label).slice(0,100),key};
965
+ notifyFilterAi();
966
+ }
967
+
968
+ function filterAiSnapshot(instruction=''){
969
+ if(!F || !sel) return { ready:false, note:'The drawing filter has not loaded yet.' };
970
+ const maxControls = 600;
971
+ const controls = [];
972
+ // The same canonical refusal Change uses, so a Question never advises a tick the row refuses.
973
+ const blockedLayerKeys = filterAiBlockedLayerKeys(F);
974
+ for(const dim of MODE_ORDER){
975
+ const descriptor = FACET_DIMS[dim];
976
+ const selected = sel[descriptor.control];
977
+ for(const row of F[descriptor.control] || []){
978
+ const key = facetKey(dim, row[descriptor.rowKey]);
979
+ controls.push({ dimension:dim, value:key === undefined ? null : (typeof key === 'string' ? key.slice(0,100) : key),
980
+ label:String(row[descriptor.rowKey] ?? '').slice(0,100), checked:key !== undefined && selected.has(key),
981
+ count:Number(row.count) || 0, notRead:dim === 'layer' && key !== undefined && blockedLayerKeys.has(key) });
982
+ }
983
+ }
984
+ const sheet = sheets[active];
985
+ const textSamples = [];
986
+ let textTotal = 0;
987
+ for(const el of (sheet?.elements || [])){
988
+ if(el.kind !== 'text' || !String(el.text || '').trim()) continue;
989
+ textTotal++;
990
+ if(textSamples.length >= 40) continue;
991
+ textSamples.push({ text:String(el.text).slice(0,120), layer:String(el.layer || '').slice(0,100), selected:matchesActive(el,mode,sel) });
992
+ }
993
+ return { ready:true, project:PROJECT, app:APP_ID, revisionRequest:revisionRequest || null,
994
+ sheet:sheetLabel(sheet, active), sheetCount:sheets.length, mode,
995
+ controls:rankFilterControls(controls,instruction,filterAiFocused).slice(0,maxControls), controlTotal:controls.length,
996
+ sheetTextSamples:textSamples, textTotal,
997
+ focusedControl:filterAiFocused,
998
+ pickedElement:eyeEl ? {kind:eyeEl.kind,layer:eyeEl.layer,text:eyeEl.text || null,w:eyeEl.w,color:eyeEl.color} : null };
999
+ }
1000
+ function filterAiReadOnlyContext(instruction){
1001
+ return readOnlyFilterContext(filterAiSnapshot(instruction), instruction, filterHelp.scope);
1002
+ }
1003
+ function filterAiProjectLabel(){
1004
+ return window.parent !== window ? window.parent.flolessBridge?.requestScopeLabel?.(PROJECT) || PROJECT : PROJECT;
1005
+ }
1006
+ function filterAiChangeContext(instruction){
1007
+ if(!F || !sel) throw new Error('The Drawing Filter is still loading. Try again when its layers appear.');
1008
+ const facts = [filterHelp.scope, ('Sheet '+sheetLabel(sheets[active],active)+'; matching criteria '+mode+'. Checked properties must all match.').slice(0,500)];
1009
+ const controlRows = [];
1010
+ const blockedLayerKeys = filterAiBlockedLayerKeys(F);
1011
+ for(const dim of ['layer','thickness','color']){
1012
+ const descriptor = FACET_DIMS[dim];
1013
+ for(const row of F[descriptor.control] || []){
1014
+ const key = facetKey(dim,row[descriptor.rowKey]);
1015
+ if(key === undefined || String(key).length > 90) continue;
1016
+ if(dim === 'layer' && blockedLayerKeys.has(key)) continue;
1017
+ controlRows.push({dimension:dim,key,row,label:String(key),checked:sel[descriptor.control].has(key)});
1018
+ }
1019
+ }
1020
+ const rankedRows = rankFilterControls(controlRows,instruction,filterAiFocused);
1021
+ let chunk = '';
1022
+ let listed = 0;
1023
+ const allowed = new Set();
1024
+ for(const {dimension:dim,key,row} of rankedRows){
1025
+ const descriptor = FACET_DIMS[dim];
1026
+ const entry = JSON.stringify([dim,key,sel[descriptor.control].has(key),Number(row.count)||0]);
1027
+ if(entry.length > 470) continue;
1028
+ if(chunk && chunk.length + entry.length + 1 > 490){ facts.push('Controls '+chunk); chunk = ''; }
1029
+ if(facts.length >= 9) break;
1030
+ chunk += (chunk ? ',' : '') + entry;
1031
+ listed++;
1032
+ allowed.add(dim+'\0'+String(key));
1033
+ }
1034
+ if(chunk) facts.push('Controls '+chunk);
1035
+ if(listed < rankedRows.length) facts.push('Only '+listed+' of '+rankedRows.length+' controls are listed, prioritised by this question and likely steel evidence. Do not claim a complete audit. Propose only listed controls.');
1036
+ // Every Drawing Filter message takes this path, so a question about a layer FloLess did not read
1037
+ // still gets the fact. Informational only: those layers are never in `allowed`, so none can be applied.
1038
+ // Whole names only, the ones the message names first (longest first, so S-ANNO-TEXT leads TEXT
1039
+ // when the message names S-ANNO-TEXT), so the one asked about is never cut off.
1040
+ if(blockedLayerKeys.size){
1041
+ const asked = String(instruction).toLowerCase();
1042
+ const rank = key => asked.includes(String(key).toLowerCase()) ? -String(key).length : 1;
1043
+ const unread = [...blockedLayerKeys].sort((a,b) => rank(a) - rank(b));
1044
+ let names = '', shown = 0;
1045
+ for(const key of unread){
1046
+ const next = (names ? names+', ' : '')+JSON.stringify(key);
1047
+ if(next.length > 420) break;
1048
+ names = next; shown++;
1049
+ }
1050
+ if(shown) facts.push('Not read by FloLess, so they cannot be changed here: '+names
1051
+ +(shown < unread.length ? ' (and '+(unread.length-shown)+' more)' : ''));
1052
+ }
1053
+ const texts = filterAiSnapshot().sheetTextSamples || [];
1054
+ if(texts.length) facts.push(('Text samples, incomplete: '+texts.slice(0,7).map(row=>JSON.stringify([row.layer,row.text,row.selected])).join(',')).slice(0,500));
1055
+ if(facts.length > 12) throw new Error('This filter has too many values for one AI message. Ask about one specific layer instead.');
1056
+ return { context:{ subject:instruction, commandId:'filter.ask-ai-change', surface:'steel-filter', tone:'idle', facts }, allowed };
1057
+ }
1058
+ function filterAiSelectionCopy(){
1059
+ return { mode, layers:new Set(sel.layers), thicknesses:new Set(sel.thicknesses), colors:new Set(sel.colors) };
1060
+ }
1061
+ function filterAiLocalFingerprint(){
1062
+ return sel ? filterViewFingerprint(active,filterAiSelectionCopy()) : null;
1063
+ }
1064
+ function filterAiSelected(state,dim,value){ return state[FACET_DIMS[dim].control].has(value); }
1065
+ /** Capture this filter's context and base selection, then create the read-only guide request. */
1066
+ async function createFilterAiRequest(kind, text){
1067
+ const instruction = String(text ?? '').trim();
1068
+ if(kind !== 'question' && kind !== 'change') return { ok:false, message:'FloLess could not send this message. Nothing was sent. Send it again.' };
1069
+ if(!instruction) return { ok:false, message:'Write a question or the change you want first. Nothing was sent.' };
1070
+ if(instruction.length > 300) return { ok:false, message:'Shorten your message to 300 characters, then send it again. Nothing was sent.' };
1071
+ if(!F || !sel) return { ok:false, message:'The Drawing Filter is still loading. Try again when its layers appear. Nothing was sent.' };
1072
+ let context, allowed = null;
1073
+ try {
1074
+ if(kind === 'change') ({ context, allowed } = filterAiChangeContext(instruction));
1075
+ else context = filterAiReadOnlyContext(instruction);
1076
+ } catch(error) { return { ok:false, message:error instanceof Error ? error.message : 'This filter cannot be described to AI right now. Nothing was sent.' }; }
1077
+ const record = { kind, base:filterAiSelectionCopy(), etag:serverEtag, revisionRequest, allowed,
1078
+ sheetEpoch:filterAiSheetEpoch, localFingerprint:filterAiLocalFingerprint(), disposition:'pending', note:'' };
1079
+ // A deadline, so a request that never settles cannot leave AI Chat's Send blocked.
1080
+ const controller = new AbortController();
1081
+ const deadline = setTimeout(() => controller.abort(), 15000);
1082
+ let response, created = null;
1083
+ try {
1084
+ response = await fetch('/api/guide', { method:'POST', headers:{'content-type':'application/json'}, signal:controller.signal,
1085
+ body:JSON.stringify({ appId:APP_ID, ...(PROJECT ? { project:PROJECT, projectLabel:filterAiProjectLabel() } : {}), instructorContext:context }) });
1086
+ created = await response.json().catch(() => null);
1087
+ } catch {
1088
+ // A deadline and a lost connection look alike here: either way the request may or may not exist.
1089
+ return { ok:false, message:'FloLess could not confirm whether this request started. Check Requests before sending it again.' };
1090
+ }
1091
+ finally { clearTimeout(deadline); }
1092
+ if(!response.ok) return { ok:false, status:response.status, reason:created?.reason ?? null,
1093
+ message:'FloLess could not start this request. Nothing was sent. Send it again; if it still fails, reload the Drawing Filter.' };
1094
+ if(!created?.request?.id) return { ok:false, message:'FloLess could not start this request. Nothing was sent. Send it again; if it still fails, reload the Drawing Filter.' };
1095
+ filterAiRecords.set(created.request.id, record);
1096
+ return { ok:true, request:created.request };
1097
+ }
1098
+ /**
1099
+ * Refusals shared by the chat card (inspectFilterAi) and applyFilterAi, so the card offers Apply only
1100
+ * when Apply would go ahead. Apply adds only the record's own kind / already-handled checks.
1101
+ */
1102
+ function filterAiApplyCheck(record, proposal){
1103
+ // The confirmation lists what THIS selection dismisses; a programmatic activation (the chat, or
1104
+ // Instructor) still lands here, so refuse rather than change `sel` under it.
1105
+ if(!signoffOverlay.hidden) return { ok:false, message:'Close the dismissal confirmation first. Nothing was applied.' };
1106
+ if(record.sheetEpoch !== filterAiSheetEpoch) return { ok:false, message:'This suggestion was made on another sheet view. Ask again on this sheet to apply it.' };
1107
+ if(saveInFlight || conflicted || checkpointSaveBlocked || serverEtag !== record.etag || revisionRequest !== record.revisionRequest)
1108
+ return { ok:false, message:'This suggestion is out of date. Ask again to get a current one.' };
1109
+ let parsed;
1110
+ try { parsed = parseFilterAiProposal(JSON.stringify(proposal), F, record.allowed); }
1111
+ catch(error) { return { ok:false, message:error instanceof Error ? error.message : 'This suggestion cannot be used with this filter. Ask again.' }; }
1112
+ if(filterAiTouchesUnreadLayer(parsed,F))
1113
+ return { ok:false, message:'This suggestion includes a layer FloLess did not read. Nothing was applied. Ask your terminal AI to inspect that source layer if it holds steel.' };
1114
+ // A suggestion is a three-way merge: leave every user edit made during the AI request alone.
1115
+ for(const item of parsed.changes){
1116
+ const before = filterAiSelected(record.base,item.dimension,item.value);
1117
+ const now = filterAiSelected(sel,item.dimension,item.value);
1118
+ if(now !== before && now !== item.on)
1119
+ return { ok:false, message:'You changed a suggested value while AI was answering. Review the selection and ask again.' };
1120
+ }
1121
+ if(parsed.mode !== null && mode !== record.base.mode && mode !== parsed.mode)
1122
+ return { ok:false, message:'You changed Match on while AI was answering. Review it and ask again.' };
1123
+ // Never let a suggestion leave the required read with no selected drawing lines. Tried on a copy, so
1124
+ // the card can say so before anyone clicks.
1125
+ const trial = filterAiSelectionCopy();
1126
+ for(const item of parsed.changes){
1127
+ const target = trial[FACET_DIMS[item.dimension].control];
1128
+ if(item.on) target.add(item.value); else target.delete(item.value);
1129
+ }
1130
+ const trialMode = parsed.mode ?? mode;
1131
+ if(!sheets.some(sheet => (sheet.elements || []).some(el => matchesActive(el, trialMode, trial))))
1132
+ return { ok:false, message:'This suggestion would select no drawing lines. Nothing was applied. Ask again with a different request.' };
1133
+ return { ok:true, proposal:parsed };
1134
+ }
1135
+ function inspectFilterAi(requestId, proposal){
1136
+ const record = filterAiRecords.get(requestId);
1137
+ if(!record) return { known:false, applicable:false, reason:FILTER_AI_UNKNOWN };
1138
+ const result = { known:true, kind:record.kind, disposition:record.disposition, note:record.note,
1139
+ undo:filterAiUndo?.requestId === requestId, applicable:false, reason:null, stale:false };
1140
+ if(record.kind === 'question'){
1141
+ result.stale = serverEtag !== record.etag || revisionRequest !== record.revisionRequest
1142
+ || filterAiLocalFingerprint() !== record.localFingerprint;
1143
+ return result;
1144
+ }
1145
+ if(record.disposition !== 'pending') return result;
1146
+ const check = filterAiApplyCheck(record, proposal);
1147
+ result.applicable = check.ok;
1148
+ result.reason = check.ok ? null : check.message;
1149
+ return result;
1150
+ }
1151
+ function applyFilterAi(requestId, proposalValue){
1152
+ const record = filterAiRecords.get(requestId);
1153
+ if(!record || record.kind !== 'change') return { ok:false, message:FILTER_AI_UNKNOWN };
1154
+ if(record.disposition !== 'pending') return { ok:false, message:'This suggestion has already been handled.' };
1155
+ const check = filterAiApplyCheck(record, proposalValue);
1156
+ if(!check.ok) return { ok:false, message:check.message };
1157
+ const proposal = check.proposal;
1158
+ const previous = filterAiSelectionCopy(), wasDirty = dirty, wasSavedState = savedState;
1159
+ const checkpointIdentity = [revisionRequest, revisionFilterSavedEtag, revisionCheckpointGeneration, revisionCheckpointEvidenceGeneration];
1160
+ const applied = [];
1161
+ for(const item of proposal.changes){
1162
+ const target = sel[FACET_DIMS[item.dimension].control];
1163
+ const was = target.has(item.value);
1164
+ if(was === item.on) continue;
1165
+ if(item.on) target.add(item.value); else target.delete(item.value);
1166
+ applied.push({ ...item, before:was });
1167
+ }
1168
+ const appliedMode = proposal.mode !== null && proposal.mode !== mode;
1169
+ if(appliedMode) mode = proposal.mode;
1170
+ record.disposition = 'applied';
1171
+ if(applied.length || appliedMode){
1172
+ // markDirty retires any EARLIER Undo; this one is recorded before the repaint, so a repaint that
1173
+ // throws still leaves the changed ticks undoable.
1174
+ markDirty();
1175
+ filterAiUndo = { requestId, changes:applied, modeBefore:previous.mode, modeAfter:mode, appliedMode,
1176
+ etag:serverEtag, revisionRequest, previous, wasDirty, wasSavedState, checkpointIdentity };
1177
+ record.note = 'Applied to the selection. Not saved yet. Press Save filter when you’re ready.';
1178
+ if(appliedMode) document.querySelectorAll('input[name=dim]').forEach(cb => { cb.checked = modeDims(mode).includes(cb.value); });
1179
+ syncFacetChecks(); apply();
1180
+ }else record.note = 'Your selection already matches this suggestion. Nothing was changed or saved.';
1181
+ notifyFilterAi();
1182
+ return { ok:true, message:record.note };
1183
+ }
1184
+ function undoFilterAi(requestId){
1185
+ const undo = filterAiUndo;
1186
+ const record = filterAiRecords.get(requestId);
1187
+ if(!undo || !record || undo.requestId !== requestId) return { ok:false, message:record?.note || 'Undo is no longer available for this suggestion.' };
1188
+ // Same rule as Apply; Undo stays available for when the confirmation closes.
1189
+ if(!signoffOverlay.hidden) return { ok:false, message:'Close the dismissal confirmation first. Nothing was undone.' };
1190
+ if(saveInFlight || conflicted || checkpointSaveBlocked || serverEtag !== undo.etag
1191
+ || revisionRequest !== undo.revisionRequest
1192
+ || undo.checkpointIdentity.some((value,index) => value !== [revisionRequest,revisionFilterSavedEtag,revisionCheckpointGeneration,revisionCheckpointEvidenceGeneration][index])){
1193
+ retireFilterAiUndo('The filter was saved or changed elsewhere, so Undo is no longer available. Review the current selection.');
1194
+ return { ok:false, message:record.note };
1195
+ }
1196
+ for(const item of undo.changes){
1197
+ const target = sel[FACET_DIMS[item.dimension].control];
1198
+ if(target.has(item.value) !== item.on) continue; // user changed this value later
1199
+ if(item.before) target.add(item.value); else target.delete(item.value);
1200
+ }
1201
+ if(undo.appliedMode && mode === undo.modeAfter) mode = undo.modeBefore;
1202
+ document.querySelectorAll('input[name=dim]').forEach(cb => { cb.checked = modeDims(mode).includes(cb.value); });
1203
+ syncFacetChecks(); apply();
1204
+ const restored = mode === undo.previous.mode && ['layers','thicknesses','colors'].every(facet =>
1205
+ sel[facet].size === undo.previous[facet].size
1206
+ && [...sel[facet]].every(value => undo.previous[facet].has(value)));
1207
+ if(restored && !undo.wasDirty && !undo.preserveDirtyOnUndo){ dirty = false; setSaved(undo.wasSavedState); syncRequiredSaveCue(); }
1208
+ else markDirty(false);
1209
+ retireFilterAiUndo();
1210
+ record.disposition = 'undone';
1211
+ record.note = restored
1212
+ ? undo.preserveDirtyOnUndo ? 'Change undone. A stored filter tick still needs Save to clear it.'
1213
+ : undo.wasDirty ? 'Change undone. Your earlier unsaved changes remain.' : 'Change undone. The selection is back to what it was before Apply. Nothing was saved.'
1214
+ : 'Change undone where possible. Your later edits remain unsaved.';
1215
+ notifyFilterAi();
1216
+ return { ok:true, message:record.note };
1217
+ }
1218
+ function keepFilterAi(requestId){
1219
+ const record = filterAiRecords.get(requestId);
1220
+ if(!record || record.kind !== 'change') return { ok:false, message:FILTER_AI_UNKNOWN };
1221
+ if(record.disposition !== 'pending') return { ok:false, message:'This suggestion has already been handled.' };
1222
+ record.disposition = 'kept';
1223
+ record.note = 'Kept the current selection. No changes were made.';
1224
+ notifyFilterAi();
1225
+ return { ok:true, message:record.note };
1226
+ }
1227
+ function filterAiSummary(){
1228
+ if(document.getElementById('empty').classList.contains('show')) return { state:'unavailable' };
1229
+ if(!F || !sel) return { state:'loading' };
1230
+ return { state:'ready', sheet:sheetLabel(sheets[active], active), sheetCount:sheets.length,
1231
+ focused:filterAiFocused ? { dimension:filterAiFocused.dimension, label:filterAiFocused.label } : null };
1232
+ }
1233
+ // Same-origin bridge for the shell's AI Chat. Every call is synchronous except createRequest, and each
1234
+ // call that acts on a suggestion re-checks the live page state itself, so a stale chat card can only
1235
+ // ever be refused.
1236
+ window.__floFilterAi = Object.freeze({
1237
+ summary:filterAiSummary,
1238
+ createRequest:createFilterAiRequest,
1239
+ forget(requestId){ filterAiRecords.delete(String(requestId)); },
1240
+ inspect:(requestId, proposal) => inspectFilterAi(String(requestId), proposal),
1241
+ apply:(requestId, proposal) => applyFilterAi(String(requestId), proposal),
1242
+ undo:(requestId) => undoFilterAi(String(requestId)),
1243
+ keep:(requestId) => keepFilterAi(String(requestId)),
1244
+ });
1245
+
662
1246
  /**
663
1247
  * The project's steel catalogue and display units, stated where the last human stop is.
664
1248
  *
@@ -791,6 +1375,8 @@ function displayUnitsFrameMatches(m){
791
1375
  }
792
1376
 
793
1377
  function setSaved(state){
1378
+ savedState = state;
1379
+ notifyFilterAi();
794
1380
  // The state→(class, label) map is `statChip` in steel-filter-core.js, where it is table-tested.
795
1381
  const { cls, text, badge } = statChip(state);
796
1382
  savedEl.className = 'stat ' + cls;
@@ -916,7 +1502,9 @@ savedEl.onclick = reopenChipExplanation;
916
1502
  savedEl.addEventListener('keydown', e => {
917
1503
  if(e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar'){ e.preventDefault(); reopenChipExplanation(); }
918
1504
  });
919
- function markDirty(){
1505
+ function markDirty(retireAiUndo=true,preserveOnUndo=false){
1506
+ if(retireAiUndo && filterAiUndo) retireFilterAiUndo(FILTER_AI_EDITED);
1507
+ if(!retireAiUndo && preserveOnUndo && filterAiUndo) filterAiUndo.preserveDirtyOnUndo = true;
920
1508
  dirty = true; saveBtn.disabled = checkpointSaveBlocked; setSaved('dirty');
921
1509
  if(revisionRequest) syncRequiredSaveCue();
922
1510
  }
@@ -928,7 +1516,7 @@ function setRequiredSaveCue(checkpoint, ready){
928
1516
  if(checkpoint){
929
1517
  saveBtn.setAttribute('aria-describedby', 'saveRequiredStatus');
930
1518
  saveBtn.setAttribute('data-tip', ready
931
- ? 'Required next step: save this Drawing Filter, then return to the terminal AI that prepared it and tell it to continue'
1519
+ ? 'Required next step: save this Drawing Filter. A linked AI Chat continues automatically; an external terminal session needs your follow-up there.'
932
1520
  : 'Select at least one drawing line in the filter before saving');
933
1521
  if(ready) saveBtn.removeAttribute('data-blocked-reason');
934
1522
  else saveBtn.setAttribute('data-blocked-reason', 'Select at least one drawing line in the Drawing Filter before saving.');
@@ -975,6 +1563,8 @@ function setFilterEditingLocked(locked){
975
1563
  else app.removeAttribute('aria-busy');
976
1564
  if(locked) eye.setAttribute('aria-busy', 'true');
977
1565
  else eye.removeAttribute('aria-busy');
1566
+ // Save start/finish changes whether a suggestion in AI Chat can be applied.
1567
+ notifyFilterAi();
978
1568
  }
979
1569
 
980
1570
  // Same-origin parent bridge: polling may complete, fail, or clear a checkpoint while this editor has
@@ -998,11 +1588,12 @@ window.__floRevisionCheckpoint = {
998
1588
  revisionCheckpointGeneration += 1;
999
1589
  }
1000
1590
  revisionCheckpointEvidenceGeneration += 1;
1591
+ retireFilterAiUndo('The required drawing checkpoint changed, so Undo is no longer available. Review the current selection.');
1001
1592
  // The sign-off list belongs to the exact request + saved evidence that opened it. A same-request
1002
1593
  // E1→E2/E1→empty transition is just as invalidating as request replacement: otherwise an old
1003
1594
  // exclusion decision or dismissed refusal can be approved against the newer checkpoint.
1004
1595
  retireSignOffForCheckpointChange();
1005
- checkpointSaveBlocked = false;
1596
+ checkpointSaveBlocked = false; notifyFilterAi();
1006
1597
  // Reload-only recovery belongs to the exact checkpoint that failed. Retire it on either identity
1007
1598
  // or evidence change while preserving the user's facet selections and ordinary dirty state.
1008
1599
  const recovery = document.getElementById('conflictBanner');
@@ -1011,7 +1602,7 @@ window.__floRevisionCheckpoint = {
1011
1602
  lastBanner = undefined;
1012
1603
  // `conflicted` belongs to the refused conditional write that produced this recovery surface.
1013
1604
  // An unrelated external-edit conflict has no requiredRecovery marker and remains untouched.
1014
- conflicted = false;
1605
+ conflicted = false; notifyFilterAi();
1015
1606
  }
1016
1607
  revisionRequest = nextRequest;
1017
1608
  revisionFilterSavedEtag = nextSavedEtag;
@@ -1157,6 +1748,7 @@ function initLiveUpdates(){
1157
1748
  });
1158
1749
  if(a.act === 'ignore') return;
1159
1750
  if(a.act === 'connected'){ seenConnected = true; return; }
1751
+ if(a.act !== 'own-echo') retireFilterAiUndo('The filter changed outside this panel, so Undo is no longer available. Review the current selection.');
1160
1752
  if(a.act === 'gap'){
1161
1753
  // The stream reconnected, so any write during the gap is lost with no replay. We cannot know whether
1162
1754
  // one happened, only that we would not have seen it — so resync rather than assume.
@@ -1169,7 +1761,7 @@ function initLiveUpdates(){
1169
1761
  ownWrites.splice(0, a.drop);
1170
1762
  // Adopt the tag the server minted for our own write, so a PUT that succeeded while its response was
1171
1763
  // lost cannot leave `serverEtag` stale and 412 the user's next save against their own change.
1172
- if(a.adoptEtag) serverEtag = a.adoptEtag;
1764
+ if(a.adoptEtag){ serverEtag = a.adoptEtag; notifyFilterAi(); }
1173
1765
  return;
1174
1766
  }
1175
1767
  if(a.act === 'banner'){
@@ -1329,6 +1921,7 @@ function publicationEmptyState(code){
1329
1921
  }
1330
1922
 
1331
1923
  function showEmpty(msg, publicationBlocked = false, detail = ''){
1924
+ notifyFilterAi();
1332
1925
  const e = document.getElementById('empty');
1333
1926
  document.body.classList.toggle('publication-blocked', publicationBlocked);
1334
1927
  const body = e.querySelector('.empty-body');
@@ -1515,7 +2108,13 @@ document.addEventListener('pointerdown', e => {
1515
2108
  // estimator pages through framing plans constantly; a false "unsaved changes" prompt on read-only
1516
2109
  // browsing is worse than not persisting the viewed-sheet index). `active` is written on the next Save.
1517
2110
  function setSheet(i){
2111
+ const previousSheet = active;
1518
2112
  active = Math.min(Math.max(0, i|0), sheets.length - 1);
2113
+ if(active !== previousSheet){
2114
+ // Any sheet switch retires applicability of earlier suggestions: they stay readable in AI Chat.
2115
+ filterAiSheetEpoch++;
2116
+ notifyFilterAi();
2117
+ }
1519
2118
  const sh = sheets[active] || {};
1520
2119
  const pg = (sh.page && sh.page.w > 0 && sh.page.h > 0) ? sh.page : { w: 1000, h: 1000 }; // guard empty page → no NaN viewBox
1521
2120
  svg.setAttribute('viewBox', `0 0 ${pg.w} ${pg.h}`);
@@ -1537,6 +2136,12 @@ function setSheet(i){
1537
2136
  }
1538
2137
 
1539
2138
  function buildOverlay(){
2139
+ // FIRST: the halo lives outside #overlay and outlives replaceChildren(), and the element it marks may
2140
+ // not even be mounted after this. Clearing also resets `hoverEl`, without which the `el === hoverEl`
2141
+ // guard in `hoverShow` would swallow the next read — `nodes` re-maps the SAME element records, so the
2142
+ // object identity survives the rebuild even though the DOM node does not.
2143
+ // Unconditional for the same reason as closeEye: rows lit by the popover carry no `hoverEl`.
2144
+ hoverClear();
1540
2145
  overlay.replaceChildren();
1541
2146
  const rasterContext = hasRasterContext();
1542
2147
  // The raster is the full, quiet sheet context. Mount only the selected vectors: a large PDF can
@@ -1546,15 +2151,19 @@ function buildOverlay(){
1546
2151
  let n;
1547
2152
  if(el.kind === 'text'){
1548
2153
  n = document.createElementNS(SVGNS, 'text');
1549
- const b = el.bbox || [0,0,0,0];
1550
- n.setAttribute('x', b[0]); n.setAttribute('y', b[3] || b[1]);
1551
- // Sized by textFontSize, not by the bbox height: on a rotated run the height is the string
1552
- // LENGTH, and taking it verbatim rendered title-block text at font-size 373 (#591). It fixes
1553
- // the SIZE only — a vertical run is still drawn horizontally, because the producer records no
1554
- // rotation direction to draw it with.
1555
- n.setAttribute('font-size', textFontSize(b, el.text));
2154
+ // Anchor and size from textDraw, which is ALSO what the hit test files the run under and what
2155
+ // paintHot haloes (#1538) — one derivation, so what the pointer finds is by construction what
2156
+ // was painted. The anchor is the NORMALISED box's bottom-left corner, so the glyphs rise into
2157
+ // the recorded box whichever corner it was recorded from. Sized by textFontSize inside it, not
2158
+ // by the bbox height: on a rotated run the height is the string LENGTH, and taking it verbatim
2159
+ // rendered title-block text at font-size 373 (#591). The PDF's own size (`el.size`) wins when the
2160
+ // producer recorded it. It fixes the SIZE only — a rotated run is still drawn horizontally,
2161
+ // because the producer records no rotation direction to draw it with.
2162
+ const draw = textDraw(el.bbox, el.text, el.size);
2163
+ n.setAttribute('x', draw.x); n.setAttribute('y', draw.baseline);
2164
+ n.setAttribute('font-size', draw.size);
1556
2165
  n.setAttribute('fill', layerColor[el.layer] || '#cbd5e1');
1557
- n.textContent = el.text || '';
2166
+ n.textContent = textString(el.text);
1558
2167
  } else {
1559
2168
  n = document.createElementNS(SVGNS, 'path');
1560
2169
  n.setAttribute('d', el.d || '');
@@ -1569,6 +2178,7 @@ function buildOverlay(){
1569
2178
  overlay.appendChild(n);
1570
2179
  return { node: n, el };
1571
2180
  });
2181
+ syncHitReady();
1572
2182
  }
1573
2183
 
1574
2184
  function hasRasterContext(){ return !!((sheets[active] && sheets[active].page) || {}).bg_b64; }
@@ -1591,7 +2201,19 @@ const NO_VALUE_REASON = (facet) => 'This ' + FACET_NOUN[facet] + '’s value isn
1591
2201
  * so nothing could persist it. Distinct copy, because the fix is different — the drawing set's
1592
2202
  * control lists are incomplete, not its values malformed. */
1593
2203
  const NO_ROW_REASON = (facet) => 'This ' + FACET_NOUN[facet] + ' isn’t in the filter’s list, so it can’t be ticked or saved. Ask your terminal AI to re-read the drawing so every value on the sheets gets a control.';
2204
+ /**
2205
+ * A layer FloLess did NOT read (#990): the extractor withheld every line on it as annotation, so the
2206
+ * row has no elements behind it and a tick would select nothing. Before this the row looked exactly
2207
+ * like a layer the human had chosen to leave off. One sentence, for the same reason NO_VALUE_REASON is
2208
+ * one: the hover tip, the screen-reader description and Instructor's blocked reason must not drift.
2209
+ * It says what happened, why, and what to do - and it does not promise a re-read, because nothing can
2210
+ * force one of these layers in yet.
2211
+ */
2212
+ const NOT_READ_REASON = 'FloLess didn’t read this layer’s lines. Its name marks it as annotation — text, dimensions or a title block — and those are left out to keep the drawing read within its size limit. You can still see them in the sheet image behind, but there’s nothing here to tick. If this layer actually holds steel, tell your terminal AI which one, so it knows those lines weren’t read.';
2213
+ /** Only a LAYER row can be not-read, and only when the extractor said so - never inferred from the name. */
2214
+ const rowNotRead = (facet, it) => facet === 'layers' && !!it && it.notRead === true;
1594
2215
  let noValueSeq = 0;
2216
+ let notReadSeq = 0;
1595
2217
 
1596
2218
  /**
1597
2219
  * How a thickness reads on screen: the CANONICAL width, because that is the value being decided —
@@ -1703,7 +2325,22 @@ function facetOnWouldChange(facet){
1703
2325
  const s = setOf(facet);
1704
2326
  return (F[facet] || []).some(it => {
1705
2327
  const key = facetRowKey(facet, it);
1706
- return it.on !== (key !== undefined && s.has(key));
2328
+ return it.on !== (key !== undefined && !rowNotRead(facet, it) && s.has(key));
2329
+ });
2330
+ }
2331
+ // The same question asked only of the rows an action actually touched. A separate function rather than
2332
+ // a second parameter on the one above, because that one is also handed straight to `.some(...)`, which
2333
+ // would feed it an array index. A searched all/none acts on the matching rows only; asked of the WHOLE
2334
+ // list, a hidden row with an unusable value and a stored tick made an all over already-ticked matches
2335
+ // mark the filter dirty, and the Save that followed rewrote that hidden row after the button had promised
2336
+ // hidden rows are left alone (Codex review).
2337
+ function facetOnWouldChangeIn(facet, indices){
2338
+ const s = setOf(facet);
2339
+ const items = F[facet] || [];
2340
+ return indices.some(i => {
2341
+ const it = items[i];
2342
+ const key = facetRowKey(facet, it);
2343
+ return it.on !== (key !== undefined && !rowNotRead(facet, it) && s.has(key));
1707
2344
  });
1708
2345
  }
1709
2346
 
@@ -1720,35 +2357,129 @@ function facetOnWouldChange(facet){
1720
2357
  * what Instructor reads. When NOTHING in the list can be moved, they refuse outright.
1721
2358
  */
1722
2359
  function syncFacetBulk(facet){
1723
- const items = F[facet] || [];
1724
- const usable = items.filter(it => facetRowKey(facet, it) !== undefined).length;
2360
+ const all = F[facet] || [];
2361
+ // While a search is on, all/none act on the MATCHING rows only — the owner's decision, over a design
2362
+ // review that recommended the whole list. It is made unmistakable rather than left to be discovered:
2363
+ // each button carries the count it will act on, and its tip says it does not change the rows the search
2364
+ // hides. That promise is about the BUTTON, deliberately: Save has always cleared a stored tick on a row
2365
+ // whose value the filter cannot use (that row says so itself), hidden or not, and that clean-up is
2366
+ // Save's, not this button's (operator decision after Codex review). On a
2367
+ // revision read the exclusion sign-off still lists everything switched off before Save, so a surprise
2368
+ // here is caught before it is recorded.
2369
+ const q = facetQuery[facet];
2370
+ const idx = facetScope(facet);
2371
+ const items = idx.map(i => all[i]);
2372
+ const noValue = items.filter(it => facetRowKey(facet, it) === undefined).length;
2373
+ // A not-read row (#990) has a perfectly good key, so the key test alone counted it usable and "all"
2374
+ // claimed to tick a row whose tick selects nothing. setAllFacet skips it for the same reason.
2375
+ const notRead = items.filter(it => facetRowKey(facet, it) !== undefined && rowNotRead(facet, it)).length;
2376
+ const usable = items.length - noValue - notRead;
1725
2377
  for(const attr of ['data-all', 'data-none']){
1726
2378
  const button = document.querySelector(`[${attr}="${facet}"]`);
1727
2379
  if(!button) continue;
2380
+ const word = attr === 'data-all' ? 'all' : 'none';
2381
+ const verb = attr === 'data-all' ? 'ticks' : 'unticks';
2382
+ button.textContent = q ? word + ' (' + items.length + ')' : word;
2383
+ const scope = q ? `This ${verb} only the ${items.length} ${plural(facet, items.length)} matching “${q}” — it doesn’t change rows your search hides.` : '';
2384
+ if(q && items.length === 0){
2385
+ const why = `No ${FACET_NOUN[facet]} matches “${q}”, so this does nothing. Change or clear the search.`;
2386
+ button.setAttribute('aria-disabled', 'true');
2387
+ button.setAttribute('data-blocked-reason', why);
2388
+ button.setAttribute('data-tip', why);
2389
+ continue;
2390
+ }
1728
2391
  if(usable === items.length){
1729
2392
  button.removeAttribute('aria-disabled');
1730
2393
  button.removeAttribute('data-blocked-reason');
1731
- button.removeAttribute('data-tip');
2394
+ if(scope) button.setAttribute('data-tip', scope); else button.removeAttribute('data-tip');
1732
2395
  continue;
1733
2396
  }
1734
- const verb = attr === 'data-all' ? 'ticks' : 'unticks';
1735
- const reason = usable === 0
1736
- ? `No ${FACET_NOUN[facet]} in this list has a value the filter can use, so this does nothing. ${NO_VALUE_REASON(facet)}`
1737
- : `This ${verb} the ${usable} usable ${FACET_NOUN[facet]}${usable === 1 ? '' : 's'} — ${items.length - usable} in this list ${items.length - usable === 1 ? 'has a value' : 'have values'} the filter can’t use.`;
2397
+ // With no not-read row in scope this is the copy it always was, word for word.
2398
+ const reason = !notRead ? (usable === 0
2399
+ ? `No ${FACET_NOUN[facet]} in ${q ? 'these matches' : 'this list'} has a value the filter can use, so this does nothing. ${NO_VALUE_REASON(facet)}`
2400
+ : `This ${verb} the ${usable} usable ${FACET_NOUN[facet]}${usable === 1 ? '' : 's'}${q ? ` matching “${q}”` : ''} — ${items.length - usable} ${q ? 'of them' : 'in this list'} ${items.length - usable === 1 ? 'has a value' : 'have values'} the filter can’t use.${q ? ' It doesn’t change rows your search hides.' : ''}`)
2401
+ : notReadBulkReason(facet, { verb, q, usable, noValue, notRead });
1738
2402
  if(usable === 0) button.setAttribute('aria-disabled', 'true'); else button.removeAttribute('aria-disabled');
1739
2403
  button.setAttribute('data-blocked-reason', reason);
1740
2404
  button.setAttribute('data-tip', reason);
1741
2405
  }
1742
2406
  }
1743
2407
 
2408
+ /** The bulk tip when the scope holds layers FloLess did not read (#990): it names how many it skips and
2409
+ * why, so "all" never appears to tick a row it cannot. */
2410
+ function notReadBulkReason(facet, { verb, q, usable, noValue, notRead }){
2411
+ const where = q ? ` matching “${q}”` : '';
2412
+ const skipped = [`${notRead} ${notRead === 1 ? 'wasn’t' : 'weren’t'} read by FloLess (tagged “not read”)`];
2413
+ if(noValue) skipped.push(`${noValue} ${noValue === 1 ? 'has a value' : 'have values'} the filter can’t use`);
2414
+ const hides = q ? ' It doesn’t change rows your search hides.' : '';
2415
+ if(usable === 0) return `Nothing${where || ' in this list'} can be ${verb === 'ticks' ? 'ticked' : 'unticked'} — ${skipped.join(', and ')}, so this does nothing.${hides}`;
2416
+ return `This ${verb} the ${usable} usable ${plural(facet, usable)}${where} and skips the rest: ${skipped.join(', and ')}.${hides}`;
2417
+ }
2418
+
2419
+ /* ── the per-list search ───────────────────────────────────────────────────────────────────────── */
2420
+ // A list this short is scanned at a glance; a search box on it is only another control. Layers are the
2421
+ // real case (40–300+ rows on a real set); thicknesses and colours usually stay under it.
2422
+ const FACET_SEARCH_MIN = 10;
2423
+ const facetQuery = { layers: '', thicknesses: '', colors: '' };
2424
+ const plural = (facet, n) => n === 1 ? FACET_NOUN[facet] : ({ layers: 'layers', thicknesses: 'thicknesses', colors: 'colours' })[facet];
2425
+ /** Every word must appear in the row's displayed text, in any order: "beam stel" finds S-ANNO-BEAM-STEL. */
2426
+ function queryMatches(text, q){
2427
+ const t = String(text || '').toLowerCase();
2428
+ return q.toLowerCase().split(/\s+/).filter(Boolean).every(tok => t.includes(tok));
2429
+ }
2430
+ /** Indices of the rows the search leaves in scope — every row when there is no query. */
2431
+ function facetScope(facet){
2432
+ const items = F[facet] || [];
2433
+ const q = facetQuery[facet];
2434
+ if(!q) return items.map((_, i) => i);
2435
+ const rows = document.querySelectorAll(`#facet-${facet} .opts label`);
2436
+ const out = [];
2437
+ items.forEach((_, i) => { const row = rows[i]; if(row && queryMatches(row.dataset.q, q)) out.push(i); });
2438
+ return out;
2439
+ }
2440
+ function applyFacetQuery(facet){
2441
+ const items = F[facet] || [];
2442
+ const wrap = document.querySelector(`#facet-${facet} .facet-search`);
2443
+ const input = document.getElementById(`facet-${facet}-q`);
2444
+ const count = document.getElementById(`facet-${facet}-count`);
2445
+ const clear = document.querySelector(`[data-clear="${facet}"]`);
2446
+ if(!wrap || !input || !count) return;
2447
+ const offered = items.length >= FACET_SEARCH_MIN;
2448
+ wrap.hidden = !offered;
2449
+ if(!offered && facetQuery[facet]){ facetQuery[facet] = ''; input.value = ''; }
2450
+ const q = facetQuery[facet];
2451
+ const inScope = new Set(facetScope(facet));
2452
+ document.querySelectorAll(`#facet-${facet} .opts label`).forEach((row, i) => row.classList.toggle('q-hide', !inScope.has(i)));
2453
+ if(clear) clear.hidden = !q;
2454
+ count.hidden = !q;
2455
+ // "12 of 212", not "12": on a long list the denominator is what says nothing is missing, only hidden.
2456
+ count.textContent = !q ? '' : inScope.size ? `${inScope.size} of ${items.length}` : `No ${plural(facet, 2)} match “${q}”.`;
2457
+ }
2458
+ function setFacetQuery(facet, q){
2459
+ facetQuery[facet] = String(q || '').trim();
2460
+ applyFacetQuery(facet);
2461
+ syncFacetBulk(facet);
2462
+ }
2463
+
1744
2464
  function buildFacet(facet, items, label){
1745
2465
  const dim = FACET_DIM_BY_CONTROL[facet];
1746
2466
  const box = document.querySelector(`#facet-${facet} .opts`);
1747
2467
  box.replaceChildren();
2468
+ // The list-level count of not-read layers (#990). At 68 of 190 layers on a real set this is the
2469
+ // common case, not an edge one, and a tag per row does not answer "why are there so many".
2470
+ const notReadHint = document.getElementById(`facet-${facet}-notread`);
2471
+ if(notReadHint){
2472
+ const n = items.filter(it => facetRowKey(facet, it) !== undefined && rowNotRead(facet, it)).length;
2473
+ notReadHint.hidden = !n;
2474
+ notReadHint.textContent = n ? `${n} ${n === 1 ? 'layer wasn’t' : 'layers weren’t'} read — ${n === 1 ? 'its name marks it' : 'their names mark them'} as annotation. ${n === 1 ? 'It’s' : 'They’re'} tagged “not read” below.` : '';
2475
+ }
1748
2476
  for(const it of items){
1749
2477
  const val = it[FACET_DIMS[dim].rowKey];
1750
2478
  const key = facetRowKey(facet, it);
1751
2479
  const isText = facet === 'layers' && it.drawable === false;
2480
+ // Only a row with a usable key can be not-read: a row with no value is refused for THAT reason,
2481
+ // which is the one its copy explains.
2482
+ const notRead = key !== undefined && rowNotRead(facet, it);
1752
2483
  const wrap = document.createElement('label');
1753
2484
  // The no-value case is tested BEFORE `isText` on purpose: a layer row can be both undrawable and
1754
2485
  // wrong-typed, and if .textlayer won it would render as an ordinary muted row with a checkbox that
@@ -1759,6 +2490,9 @@ function buildFacet(facet, items, label){
1759
2490
  if(key === undefined){
1760
2491
  wrap.className = 'novalue';
1761
2492
  wrap.setAttribute('data-tip', NO_VALUE_REASON(facet));
2493
+ } else if(notRead){
2494
+ wrap.className = 'notread';
2495
+ wrap.setAttribute('data-tip', NOT_READ_REASON);
1762
2496
  } else if(isText) wrap.className = 'textlayer';
1763
2497
  const cb = document.createElement('input');
1764
2498
  cb.type = 'checkbox';
@@ -1773,7 +2507,8 @@ function buildFacet(facet, items, label){
1773
2507
  // node, and the checkbox is what a pointer lands on. (`vector.show-kind` keeps the label carrier
1774
2508
  // for now — a different surface, and not this slice's to change.)
1775
2509
  cb.setAttribute('data-command-id', 'filter.facet-toggle');
1776
- cb.checked = key !== undefined && setOf(facet).has(key);
2510
+ cb.addEventListener('focus', () => focusFilterFacet(dim, String(val), key));
2511
+ cb.checked = key !== undefined && !notRead && setOf(facet).has(key);
1777
2512
  cb.value = String(val);
1778
2513
  // syncFacetChecks(), not just this one box: two rows whose values canonicalise the same (a
1779
2514
  // `#ABC123` beside a `#abc123`) are ONE selection value, so the sibling must move with it rather
@@ -1805,7 +2540,7 @@ function buildFacet(facet, items, label){
1805
2540
  // Snap the box back, and mark dirty when the row's STORED flag disagrees with what Save will
1806
2541
  // write. Otherwise the refusal copy promises "saving will clear its tick" on a page whose Save
1807
2542
  // button nothing can enable.
1808
- cb.addEventListener('change', () => { cb.checked = false; if(facetOnWouldChange(facet)) markDirty(); });
2543
+ cb.addEventListener('change', () => { cb.checked = false; if(facetOnWouldChange(facet)) markDirty(false,it.on !== false); });
1809
2544
  // Appended to the LIST, not to the row. A <label> wrapping an input contributes its text to that
1810
2545
  // input's accessible NAME, and `.sr-only` clips a node visually without removing it from the
1811
2546
  // accname computation - so parking the sentence inside `wrap` made the checkbox announce the
@@ -1814,6 +2549,23 @@ function buildFacet(facet, items, label){
1814
2549
  // a sibling works and announces once, as a description.
1815
2550
  box.appendChild(why);
1816
2551
  }
2552
+ else if(notRead){
2553
+ // The .novalue refusal pattern, for a different cause (see NOT_READ_REASON): aria-disabled so
2554
+ // the row stays reachable by Tab, hover and Instructor, and a click puts the box back - to
2555
+ // UNTICKED, always. `selFromFilter` never selects a not-read layer, so a tick stored before the
2556
+ // layer was flagged shows unticked and Save writes it off (#1579: a tick here claimed a layer
2557
+ // was included when nothing of it was read). As with .novalue, the refused click marks dirty
2558
+ // when that stored tick is still waiting to be cleared, so the clean-up has a route to a Save.
2559
+ const why = document.createElement('span');
2560
+ why.className = 'sr-only';
2561
+ why.id = 'notread-' + facet + '-' + notReadSeq++;
2562
+ why.textContent = NOT_READ_REASON;
2563
+ cb.setAttribute('aria-disabled', 'true');
2564
+ cb.setAttribute('aria-describedby', why.id);
2565
+ cb.setAttribute('data-blocked-reason', NOT_READ_REASON);
2566
+ cb.addEventListener('change', () => { cb.checked = false; if(facetOnWouldChange(facet)) markDirty(); });
2567
+ box.appendChild(why);
2568
+ }
1817
2569
  else cb.addEventListener('change', () => { const s = setOf(facet); cb.checked ? s.add(key) : s.delete(key); syncFacetChecks(); markDirty(); apply(); });
1818
2570
  // NOTE: the per-row handler always marks dirty — a click on a live row IS an edit, even when the
1819
2571
  // resulting flag matches what was stored (the user re-ticked what they just unticked). Only the
@@ -1829,6 +2581,16 @@ function buildFacet(facet, items, label){
1829
2581
  wrap.appendChild(sw);
1830
2582
  }
1831
2583
  wrap.appendChild(document.createTextNode(' ' + label(it) + ' '));
2584
+ if(notRead){
2585
+ const tag = document.createElement('span');
2586
+ tag.className = 'tag-notread';
2587
+ tag.textContent = 'not read';
2588
+ wrap.appendChild(tag);
2589
+ }
2590
+ // What the search matches: the text the row DISPLAYS, so what the user types matches what they read
2591
+ // (a thickness is "0.4 pt", not its raw width). The "not read" tag is displayed text too, so
2592
+ // searching for it finds exactly the layers FloLess left out.
2593
+ wrap.dataset.q = (String(label(it)) + (notRead ? ' not read' : '')).toLowerCase();
1832
2594
  const c = document.createElement('em'); c.textContent = it.count;
1833
2595
  // The count spans the WHOLE drawing set — schedule and detail sheets included — while the canvas
1834
2596
  // stat chip counts only what is shown on THIS sheet. Two numbers that count different things are
@@ -1838,6 +2600,9 @@ function buildFacet(facet, items, label){
1838
2600
  wrap.appendChild(c);
1839
2601
  box.appendChild(wrap);
1840
2602
  }
2603
+ // After a rebuild (a live update re-runs initFromFilter) the rows are new, so the query is re-applied
2604
+ // to them — and dropped if the list is now too short to carry a search box at all.
2605
+ applyFacetQuery(facet);
1841
2606
  syncFacetBulk(facet);
1842
2607
  }
1843
2608
 
@@ -1848,13 +2613,17 @@ function syncFacetChecks(){
1848
2613
  cbs.forEach((cb, i) => {
1849
2614
  const it = items[i]; if(!it) return;
1850
2615
  const key = facetRowKey(facet, it);
1851
- cb.checked = key !== undefined && setOf(facet).has(key);
2616
+ cb.checked = key !== undefined && !rowNotRead(facet, it) && setOf(facet).has(key);
1852
2617
  });
1853
2618
  }
1854
2619
  }
1855
2620
 
1856
2621
  function apply(){
1857
- if(eyeEl && !matchesActive(eyeEl, mode, sel)) closeEye();
2622
+ // Every selection, mode, sheet and contract repaint runs through here; AI Chat re-checks with it.
2623
+ notifyFilterAi();
2624
+ // A shown pick that stops matching has just left the drawing from under its popover, so it closes. A
2625
+ // pick that was switched off when it was picked (#1527) never was on the drawing: it stays, redrawn.
2626
+ if(eyeEl && !eyeOff && !matchesActive(eyeEl, mode, sel)) closeEye();
1858
2627
  const rasterContext = hasRasterContext();
1859
2628
  buildOverlay();
1860
2629
  if(!rasterContext) for(const { node, el } of nodes){
@@ -1863,7 +2632,7 @@ function apply(){
1863
2632
  node.setAttribute('aria-hidden', String(contextOnly));
1864
2633
  }
1865
2634
  const cur = (sheets[active] && sheets[active].elements) || [];
1866
- let html = '<b>' + countShown(cur, mode, sel) + '</b> selected of <b>' + cur.length + '</b> · complete ' + (rasterContext ? 'drawing' : 'vector drawing') + ' shown as context';
2635
+ let html = '<b>' + countShown(cur, mode, sel) + '</b> selected of <b>' + cur.length + '</b> on this sheet · ' + (rasterContext ? 'Dim drawing' : 'Dim vector drawing') + ' is context only';
1867
2636
  if(sheets.length > 1){
1868
2637
  let sa = 0, ta = 0;
1869
2638
  for(const s of sheets){ const els = s.elements || []; sa += countShown(els, mode, sel); ta += els.length; }
@@ -1874,6 +2643,14 @@ function apply(){
1874
2643
  document.getElementById('facet-layers').classList.toggle('dim', !dims.has('layer'));
1875
2644
  document.getElementById('facet-thicknesses').classList.toggle('dim', !dims.has('thickness'));
1876
2645
  document.getElementById('facet-colors').classList.toggle('dim', !dims.has('color'));
2646
+ // A popover still open after the rebuild is describing a selection that has just moved under it — a
2647
+ // box unticked in the panel, a Match-on criterion toggled. Redraw it IN PLACE: stale, it offered
2648
+ // − Remove for a value already unticked (a click then removed nothing and still marked the filter
2649
+ // unsaved), a Remove tip claiming "won't change the drawing" for a criterion now matched, and a hidden
2650
+ // Add all over a value that was now addable (review finding). buildOverlay() above has also just
2651
+ // cleared the halo and rows, and this puts them back on the pick. No re-scroll: the user may be working
2652
+ // in the very list it would move.
2653
+ if(eyeEl) openEyedropper(eyeAt.x, eyeAt.y, eyeEl, { rescroll: false });
1877
2654
  }
1878
2655
 
1879
2656
  // --- modes + all/none ---
@@ -1889,7 +2666,22 @@ document.querySelectorAll('input[name=dim]').forEach(cb => cb.addEventListener('
1889
2666
  // the reason set by `syncFacetBulk`, both of which ARE tested.
1890
2667
  document.querySelectorAll('[data-all]').forEach(b => b.addEventListener('click', () => { if(b.getAttribute('aria-disabled') !== 'true') setAllFacet(b.dataset.all, true); }));
1891
2668
  document.querySelectorAll('[data-none]').forEach(b => b.addEventListener('click', () => { if(b.getAttribute('aria-disabled') !== 'true') setAllFacet(b.dataset.none, false); }));
2669
+ document.querySelectorAll('.facet-search-input').forEach(input => {
2670
+ input.addEventListener('input', () => setFacetQuery(input.dataset.facet, input.value));
2671
+ // Esc clears a non-empty search and keeps focus here; an empty one lets Esc go wherever it was going.
2672
+ input.addEventListener('keydown', e => {
2673
+ if(e.key !== 'Escape' || !input.value) return;
2674
+ e.preventDefault(); e.stopPropagation();
2675
+ input.value = ''; setFacetQuery(input.dataset.facet, '');
2676
+ });
2677
+ });
2678
+ document.querySelectorAll('[data-clear]').forEach(b => b.addEventListener('click', () => {
2679
+ const input = document.getElementById(`facet-${b.dataset.clear}-q`);
2680
+ if(input){ input.value = ''; input.focus(); }
2681
+ setFacetQuery(b.dataset.clear, '');
2682
+ }));
1892
2683
  function setAllFacet(facet, on){
2684
+ const beforeSelection=filterAiUndo ? filterAiSelectionCopy() : null;
1893
2685
  const s = setOf(facet);
1894
2686
  const items = F[facet] || [];
1895
2687
  // CANONICAL keys, exactly as the per-row handler and the eyedropper add them. Adding a raw value
@@ -1907,15 +2699,408 @@ function setAllFacet(facet, on){
1907
2699
  // promise "saving will clear its tick" had no route to a save at all.
1908
2700
  //
1909
2701
  // So the question is the honest one: would Save write a different `on` than the row holds now?
1910
- for(const it of items){ const key = facetRowKey(facet, it); if(key !== undefined){ on ? s.add(key) : s.delete(key); } }
1911
- syncFacetChecks(); if(facetOnWouldChange(facet)) markDirty(); apply();
2702
+ // In SCOPE only: while this list is being searched, the rows the search hides are left as they are
2703
+ // (see syncFacetBulk, which tells the user so on the button itself).
2704
+ const scope = facetScope(facet);
2705
+ // Bulk controls obey the same not-read refusal as individual rows (#990).
2706
+ for(const i of scope){ const key = facetRowKey(facet, items[i]); if(key !== undefined && !rowNotRead(facet, items[i])){ on ? s.add(key) : s.delete(key); } }
2707
+ const selectionChanged=retireFilterAiUndoOnSelectionChange(beforeSelection);
2708
+ syncFacetChecks(); if(facetOnWouldChangeIn(facet, scope)) markDirty(selectionChanged); apply();
1912
2709
  }
1913
2710
 
1914
2711
  // --- eyedropper: pick a line/label -> popover, + Add each / Add all ---
1915
2712
  const eye = document.getElementById('eye');
1916
2713
  let eyeEl = null;
1917
- function openEyedropper(clientX, clientY, el){
2714
+ // Was the open pick a line the filter had switched OFF when it was picked (#1527)? Such a pick was never on
2715
+ // the drawing, so it must not close the moment apply() sees it still does not match.
2716
+ let eyeOff = false;
2717
+ // Hover info's state lives up here with the eyedropper's rather than down in its own block, because
2718
+ // buildOverlay() and closeEye() both clear it and a `let` declared in that later block would be in its
2719
+ // temporal dead zone for any call that ran before the block evaluated.
2720
+ let hoverOn = false, hoverEl = null;
2721
+
2722
+ /* -- Hover info: read layer / thickness / colour off whatever the pointer is over -----------------
2723
+ WHAT THIS ANSWERS. Click-to-sample was undiscoverable -- found by accident -- and with hundreds of
2724
+ layer rows, working out which layer a line belongs to was one click per candidate. Left on, this
2725
+ mode names the line under the pointer in a chip beside it, haloes it, and lights up its row in each
2726
+ facet, so the checkbox to untick is already glowing when the eye gets there. A click then opens #eye,
2727
+ whose − Remove unticks it without the trip to the panel at all.
2728
+
2729
+ SWITCHED-OFF LINES TOO (#1527). buildOverlay mounts just the matching vectors on a raster-backed
2730
+ sheet and marks the rest `.is-context` (pointer-events:none) on a raster-less one, so the DOM can only
2731
+ ever name a line the filter is SHOWING -- which answered "what do I switch off" and left "what do I
2732
+ turn back on" as trial and error. Every element's geometry is still in `sheets[active].elements`, so
2733
+ the pointer is matched against that DATA instead (steel-filter-hit.js: a grid built once per sheet,
2734
+ probed at most once per frame), for every line, shown or not: while the mode is on the linework takes
2735
+ no pointer input at all. A switched-off line reads out like a shown one plus a "switched off" note,
2736
+ with its halo and a faint ghost of it drawn into #hot from its `d`; a click on it opens #eye, whose
2737
+ + Add ticks the value back on.
2738
+
2739
+ WHAT IT STILL CANNOT DO, said here and in the command's `why` rather than glossed: linework the
2740
+ drawing read never emitted -- annotation layers that exist only in the background raster -- is not in
2741
+ the data, so there is nothing to match against (#990/#1528).
2742
+
2743
+ READ-ONLY, on purpose. Click still opens #eye, which owns the actions; a readout beside the pointer
2744
+ could not hold a button you could reach, and two surfaces offering the same actions is two places
2745
+ to keep honest. The panel row -- highlighted, otherwise unmodified -- is the control.
2746
+
2747
+ COST. ONE pointermove listener, rAF-throttled to one read per frame; the read is a grid lookup over
2748
+ the few cells within 4px of the pointer (well under a millisecond at the per-sheet cap), and the grid
2749
+ is built once per sheet, in few-millisecond slices, on first use. Sweeping ALONG a line does no DOM
2750
+ work at all (`el === hoverEl`); crossing onto another costs a halo in #under, a handful of text and
2751
+ style writes, one querySelectorAll per facet (three) with a class toggle per row, and one layout read
2752
+ to place the chip. The halo is in #under, not #canvas, because in #canvas every halo change re-painted
2753
+ all 100,000 paths at the cap (see #under's CSS). The row walk is the only part that grows with the
2754
+ drawing set (three lists, a few hundred labels, once per line crossed); it is left plain rather than
2755
+ cached because the cache would have to be invalidated from inside buildFacet, and a stale row map
2756
+ highlights the WRONG checkbox -- a silent wrong answer in place of a measurable cost.
2757
+ The mode is OFF by default because a halo and a readout are stage noise to opt into, not because
2758
+ leaving it on costs frames. Say that plainly rather than letting anyone believe otherwise. */
2759
+ const hoverbar = document.getElementById('hoverbar');
2760
+ const hoverBtn = document.getElementById('hoverInfo');
2761
+ const hot = document.getElementById('hot');
2762
+ const hbLayerPre = document.getElementById('hbLayerPre'), hbLayer = document.getElementById('hbLayer');
2763
+ const hbLayerSw = document.getElementById('hbLayerSw');
2764
+ const hbThick = document.getElementById('hbThick');
2765
+ const hbColor = document.getElementById('hbColor'), hbColorSw = document.getElementById('hbColorSw');
2766
+ const hbOff = document.getElementById('hbOff');
2767
+ const hbNo = { layer: document.getElementById('hbLayerNo'), thickness: document.getElementById('hbThickNo'), color: document.getElementById('hbColorNo') };
2768
+ // Its own key. NOT folded into `floless:filter-panel`, which is the rail IIFE's private state.
2769
+ const HOVER_LS = 'floless:filter-hoverinfo';
2770
+ // A pointer affordance needs a pointer — asked LIVE, never once at load. A 2-in-1 leaving tablet mode (or
2771
+ // a mouse plugged in) gains hover after load: a load-time answer left the CSS showing a button no listener
2772
+ // was bound to. Losing hover with the mode persisted ON left svg.hoverinfo set, lines at 5px and nothing
2773
+ // visible able to turn it off (review finding). The CSS hides the button and the chip on the same query.
2774
+ const HOVER_MQ = typeof window.matchMedia === 'function' ? window.matchMedia('(hover: hover)') : null;
2775
+ const canHover = () => !HOVER_MQ || HOVER_MQ.matches;
2776
+
2777
+ /**
2778
+ * A layer name, split so the part that actually identifies it survives the ellipsis.
2779
+ *
2780
+ * Real names look like `114078-X_2nd Floor Framing Plan|S-ANNO-BEAM-STEL`: every layer on a sheet
2781
+ * shares the prefix and the TAIL is the whole discriminator. A single ellipsised span clips from the
2782
+ * right, so it would have rendered `114078-X_2nd Floor Framing Plan|S-...` -- forty characters of the
2783
+ * one thing that is the same on every row, and none of the one thing that differs. The prefix is
2784
+ * muted and clipped; the tail is never clipped.
2785
+ */
2786
+ function layerParts(name){
2787
+ const s = name === undefined || name === null ? '' : String(name);
2788
+ const cut = s.lastIndexOf('|');
2789
+ return cut < 0 ? { pre: '', tail: s } : { pre: s.slice(0, cut + 1), tail: s.slice(cut + 1) };
2790
+ }
2791
+
2792
+ function hoverClear(){
2793
+ hoverEl = null;
2794
+ hot.replaceChildren();
2795
+ for(const row of document.querySelectorAll('#panel .opts label.hot-row')) row.classList.remove('hot-row');
2796
+ hbLayerPre.textContent = ''; hbLayer.textContent = '\u2014';
2797
+ hbThick.textContent = '\u2014'; hbColor.textContent = '\u2014';
2798
+ hbLayerSw.style.background = 'transparent'; hbColorSw.style.background = 'transparent';
2799
+ for(const dim of MODE_ORDER) hbNo[dim].hidden = true;
2800
+ hbOff.hidden = true; hbOff.textContent = '';
2801
+ hoverbar.hidden = true;
2802
+ }
2803
+
2804
+ /**
2805
+ * Anchor the chip at the point where the pointer entered the line: 14px below-right, flipped left or
2806
+ * up when that would run past the stage edge, never closer than 8px to it. Called only when the
2807
+ * hovered ELEMENT changes, so sliding along one line leaves it exactly where it is.
2808
+ * Without coordinates (the linkedom harness) it is left where it is; the placement is covered by the
2809
+ * real browser pass.
2810
+ */
2811
+ function placeChip(clientX, clientY){
2812
+ if(typeof clientX !== 'number' || typeof clientY !== 'number') return;
2813
+ const stage = document.getElementById('stage');
2814
+ if(!stage || typeof stage.getBoundingClientRect !== 'function') return;
2815
+ const r = stage.getBoundingClientRect(), w = hoverbar.offsetWidth, h = hoverbar.offsetHeight;
2816
+ const GAP = 14, PAD = 8;
2817
+ let left = clientX - r.left + GAP, top = clientY - r.top + GAP;
2818
+ if(left + w > r.width - PAD) left = clientX - r.left - GAP - w;
2819
+ if(top + h > r.height - PAD) top = clientY - r.top - GAP - h;
2820
+ hoverbar.style.left = Math.max(PAD, left) + 'px';
2821
+ hoverbar.style.top = Math.max(PAD, top) + 'px';
2822
+ }
2823
+
2824
+ /**
2825
+ * The halo, mounted into #hot (which paints UNDER the linework -- see #under's CSS), drawn from the
2826
+ * element's DATA, never from a mounted node (#1527). A switched-off line has no node at all on a
2827
+ * raster-backed sheet, and the hit test that finds every line answers with the element record, not a
2828
+ * node -- so every halo is drawn the one way, and nothing is ever added to the overlay.
2829
+ *
2830
+ * A path gets a casing whose `d` IS the element's, so a probe can assert the halo is on the line the
2831
+ * readout names rather than merely that something lit up; no dasharray, because a casing with gaps in it
2832
+ * reads as two highlights. A switched-off path also gets a faint GHOST of the line in its own layer
2833
+ * colour, since on a raster-backed sheet the casing would otherwise surround nothing. A text run is not
2834
+ * stroked (stroking glyph outlines at 7px paints a blob over the label): it gets a rounded box from its
2835
+ * recorded bbox, normalised by textBox -- the same box the hit test uses, and the box an unrotated run's
2836
+ * glyphs are painted in, whichever corner it was recorded from (textDraw anchors from it). When the
2837
+ * glyphs are DRAWN outside that box, which only a rotated run does, the run gets a second
2838
+ * box of its own (#1538) -- again the same rectangle the hit test answered from, so the halo lands on
2839
+ * the glyphs the pointer was actually over. Two boxes rather than one around both: the union of a
2840
+ * title-block stamp's tall box and its sideways run is a rectangle over everything in between, which
2841
+ * would halo the whole stamp for a hover on one label in it.
2842
+ */
2843
+ function paintHot(el, off){
2844
+ if(el.kind === 'text'){
2845
+ // A box without four finite corners has no rectangle to halo (the hit test cannot file it either);
2846
+ // normalising one anyway painted NaN rects, and a console error, for a label hovered before the grid.
2847
+ const box = textBox(el.bbox);
2848
+ if(!box){ hot.replaceChildren(); return; }
2849
+ const run = textRunRect(el, box);
2850
+ hot.replaceChildren(...(run ? [box, run] : [box]).map(hotRect));
2851
+ return;
2852
+ }
2853
+ const casing = document.createElementNS(SVGNS, 'path');
2854
+ casing.setAttribute('d', el.d || '');
2855
+ if(!off){ hot.replaceChildren(casing); return; }
2856
+ const ghost = document.createElementNS(SVGNS, 'path');
2857
+ ghost.setAttribute('d', el.d || '');
2858
+ ghost.setAttribute('class', 'hot-ghost');
2859
+ ghost.style.stroke = layerColor[el.layer] || '#3b82f6';
2860
+ if(el.dashed) ghost.setAttribute('stroke-dasharray', '7 4');
2861
+ hot.replaceChildren(casing, ghost);
2862
+ }
2863
+
2864
+ /** One padded, rounded halo box from a normalised rectangle -- the shape a text run is haloed with. */
2865
+ function hotRect([x0, y0, x1, y1]){
2866
+ const pad = 2, r = document.createElementNS(SVGNS, 'rect');
2867
+ r.setAttribute('x', x0 - pad); r.setAttribute('y', y0 - pad);
2868
+ r.setAttribute('width', (x1 - x0) + 2 * pad); r.setAttribute('height', (y1 - y0) + 2 * pad);
2869
+ r.setAttribute('rx', 2);
2870
+ return r;
2871
+ }
2872
+
2873
+ /**
2874
+ * The "switched off" note, in the chip and at the top of the popover: that, and nothing else (#1527).
2875
+ * WHY a line is off, and what to tick, is said by the popover's own rows -- + Add on an unticked value,
2876
+ * a refused + Add with its reason on one that cannot be ticked -- which already explain themselves.
2877
+ * Per-case recovery prose here was wrong three times in review (one Add promised for a line off on two
2878
+ * values; "untick X" for a line blocked on a second criterion too), so there is none.
2879
+ */
2880
+ const OFF_NOTE = 'Switched off';
2881
+
2882
+ /**
2883
+ * After + Add or Add all on a pick: the ONE rule for whether the popover stays. A switched-off pick
2884
+ * that is STILL off -- it had more than one reason (see `switchOffBlockers`), or one no Add can clear --
2885
+ * keeps it open, redrawn by apply() to show what is left. Anything else closes it, as before.
2886
+ */
2887
+ function closeEyeUnlessStillOff(el){
2888
+ if(eyeOff && eyeEl === el && switchOffBlockers(el, mode, sel, F).length) return;
2889
+ closeEye();
2890
+ }
2891
+
2892
+ /**
2893
+ * The element's row(s) in each of the three facets, matched on the CANONICAL key — every row that shares
2894
+ * the key, since the panel moves them together. Returns the lit rows per dimension so callers can say
2895
+ * when there were none, and scroll to the first.
2896
+ * Rows are addressed by index because buildFacet emits exactly one <label> per item, in list order —
2897
+ * the same parity syncFacetChecks relies on.
2898
+ */
2899
+ function markHotRows(el){
2900
+ const lit = {};
2901
+ for(const dim of MODE_ORDER){
2902
+ const hits = new Set(facetRowIndicesFor(F, dim, el));
2903
+ const rows = document.querySelectorAll('#facet-' + FACET_DIMS[dim].control + ' .opts label');
2904
+ lit[dim] = [];
2905
+ rows.forEach((row, k) => { const on = hits.has(k); row.classList.toggle('hot-row', on); if(on) lit[dim].push(row); });
2906
+ }
2907
+ return lit;
2908
+ }
2909
+
2910
+ function hoverShow(el, clientX, clientY, off = false){
2911
+ if(el === hoverEl) return; // sweeping ALONG one line must cost nothing -- and must not move the chip
2912
+ hoverEl = el;
2913
+ const parts = layerParts(el.layer);
2914
+ hbLayerPre.textContent = parts.pre;
2915
+ hbLayer.textContent = parts.tail || '\u2014';
2916
+ hbLayerSw.style.background = safeColor(layerColor[el.layer]);
2917
+ // An em dash for exactly the cases #eye hides the Thickness row for -- text has no stroke width, a
2918
+ // hairline has no meaningful one. Three slots stay three slots; only the value moves.
2919
+ hbThick.textContent = eyeOffers(el, 'thickness') ? thicknessLabel(el.w) : '\u2014';
2920
+ hbColor.textContent = el.color === undefined || el.color === null ? '\u2014' : String(el.color);
2921
+ hbColorSw.style.background = safeColor(el.color);
2922
+ paintHot(el, off);
2923
+ hbOff.hidden = !off; hbOff.textContent = off ? OFF_NOTE : '';
2924
+ const lit = markHotRows(el);
2925
+ // Say it when a value the chip names has no row to light: that is a producer gap (the filter's lists
2926
+ // were not built from every value on the sheets), and silence here sends the user scanning a long list
2927
+ // for a row that is not there. Only for a dimension the chip actually shows a value for — a text run's
2928
+ // thickness is an em dash, not a missing row.
2929
+ // Only for a value that EXISTS: a line carrying no colour shows an em dash, and "not in the list"
2930
+ // beside a dash claims a missing row for a value that was never there (Codex review). A value that is
2931
+ // present but malformed has no canonical key either; the popover's refusal explains that one.
2932
+ for(const dim of MODE_ORDER){
2933
+ const present = facetKey(dim, el[FACET_DIMS[dim].elementKey]) !== undefined;
2934
+ hbNo[dim].hidden = !eyeOffers(el, dim) || !present || lit[dim].length > 0;
2935
+ }
2936
+ // Unhidden BEFORE it is placed: a hidden box measures 0x0, and the edge flip needs its real size.
2937
+ hoverbar.hidden = false;
2938
+ placeChip(clientX, clientY);
2939
+ }
2940
+
2941
+ function setHoverInfo(on, persist = true){
2942
+ hoverOn = !!on && canHover();
2943
+ hoverBtn.setAttribute('aria-pressed', String(hoverOn));
2944
+ svg.classList.toggle('hoverinfo', hoverOn);
2945
+ // Turning it OFF clears; turning it ON shows nothing until the pointer is on a line.
2946
+ if(!hoverOn) hoverClear();
2947
+ syncHoverNote();
2948
+ // `persist:false` when the DEVICE changed rather than the user: losing hover must not forget that they
2949
+ // want the mode on the next time a mouse is there.
2950
+ if(persist){ try{ localStorage.setItem(HOVER_LS, hoverOn ? '1' : '0'); }catch{ /* private mode */ } }
2951
+ }
2952
+
2953
+ /* -- #1527: the hit test over the drawing DATA, for lines the DOM cannot name ----------------------
2954
+ One grid per sheet, keyed by the sheet's elements array so a reloaded or live-updated sheet (a new
2955
+ array) gets a fresh one and the old one is collected. Built on first use rather than at load, so a
2956
+ page that never turns Hover info on never pays for it -- and built in SLICES of a few milliseconds,
2957
+ one task each, because at the per-sheet cap the whole build is a couple of hundred milliseconds, and
2958
+ done in one go that is a frozen pointer at exactly the moment the user starts pointing. Until it is
2959
+ ready the probe finds nothing, and the mounted (shown) lines keep reading from the DOM -- #canvas lacks
2960
+ `.hit-ready`, so they still take the pointer; when it lands, the last place the pointer asked about
2961
+ is read at once, so a pointer that has stopped moving is not left waiting. */
2962
+ const HIT_PX = 4; // how far off a line still counts as pointing at it, in CSS px
2963
+ const HIT_SLICE_MS = 6; // work per build slice: well inside a 16ms frame
2964
+ const hitIndexCache = new WeakMap(); // elements array -> finished index
2965
+ let hitBuild = null; // { els, it } -- the one build in flight, if any
2966
+ let hitPending = null; // the last { x, y } a probe asked about while no index was ready
2967
+ /**
2968
+ * What `probeAt` answers while the sheet's grid is still building: NOT "nothing here". A click that
2969
+ * read this as "nothing here" asked the original drawing about a spot that holds a switched-off line
2970
+ * FloLess read, and the user never got its + Add (review finding, #1527 × #1528). */
2971
+ const HIT_PENDING = Object.freeze({ pending: true });
2972
+ function hitIndexFor(sheet){
2973
+ const els = sheet && sheet.elements;
2974
+ if(!Array.isArray(els)) return null;
2975
+ const ix = hitIndexCache.get(els);
2976
+ if(ix) return ix;
2977
+ if(!hitBuild || hitBuild.els !== els){
2978
+ const b = hitBuild = { els, it: hitIndexBuilder(els, HIT_SLICE_MS, () => performance.now()) };
2979
+ setTimeout(() => hitBuildStep(b), 0);
2980
+ }
2981
+ return null;
2982
+ }
2983
+ /**
2984
+ * `.hit-ready` on #canvas -- the switch that hands every pointer read to the grid -- is DERIVED, never
2985
+ * reset by hand: true exactly when the grid of the sheet now on screen is built. It is re-derived
2986
+ * whenever the overlay is mounted (buildOverlay, which every sheet switch and selection change runs)
2987
+ * and when a build finishes, so no path can leave a new sheet's lines inert under an old sheet's flag
2988
+ * (review finding: a flag cleared "on the next probe" did exactly that across a keyboard sheet switch).
2989
+ */
2990
+ function hitReady(){
2991
+ const els = sheets[active] && sheets[active].elements;
2992
+ return Array.isArray(els) && hitIndexCache.has(els);
2993
+ }
2994
+ function syncHitReady(){ svg.classList.toggle('hit-ready', hitReady()); syncHoverNote(); }
2995
+ /**
2996
+ * #1550. Say so when the sheet on screen has curves its grid could not trace in full (`index.coarse`):
2997
+ * pointing at parts of those can read nothing, more of them once zoomed in, and with nothing on screen
2998
+ * that is indistinguishable from "there is no line here". Derived like `.hit-ready` and re-derived at the same
2999
+ * two moments -- an overlay mount (every sheet switch) and a finished build -- plus a mode toggle, so it
3000
+ * can never describe another sheet's grid. Shown only while Hover info is on: it qualifies that mode and
3001
+ * nothing else on the page reads the grid.
3002
+ */
3003
+ function syncHoverNote(){
3004
+ const els = sheets[active] && sheets[active].elements;
3005
+ const ix = hoverOn && Array.isArray(els) ? hitIndexCache.get(els) : null;
3006
+ const note = ix && ix.coarse > 0 ? coarseCurveNote(ix.coarse, identifyAvailable()) : null;
3007
+ const box = document.getElementById('hoverNote'), live = document.getElementById('hoverNoteLive');
3008
+ if(!box) return;
3009
+ const said = note ? note.title + '. ' + note.body : '';
3010
+ // Only a CHANGE is written to the live region, so a re-derive that finds the same note (every overlay
3011
+ // mount runs this) does not announce it again.
3012
+ if(live && live.textContent !== said) live.textContent = said;
3013
+ if(!note){ box.hidden = true; return; }
3014
+ document.getElementById('hoverNoteTitle').textContent = note.title;
3015
+ document.getElementById('hoverNoteBody').textContent = note.body;
3016
+ box.hidden = false;
3017
+ placeHoverNote();
3018
+ }
3019
+ /**
3020
+ * Directly above #zoombar, whatever height it has settled at. The bar is a wrapping flex row, so a
3021
+ * narrower stage can wrap it onto a second line while the note is up -- measured once at show time, the
3022
+ * note then sat ON the bar (review finding). So it is re-placed whenever the bar's size changes.
3023
+ */
3024
+ function placeHoverNote(){
3025
+ const box = document.getElementById('hoverNote'), bar = document.getElementById('zoombar');
3026
+ if(!box || box.hidden || !bar || !bar.offsetHeight) return;
3027
+ box.style.bottom = (12 + bar.offsetHeight + 6) + 'px';
3028
+ }
3029
+ if(typeof ResizeObserver === 'function' && document.getElementById('zoombar')){
3030
+ new ResizeObserver(placeHoverNote).observe(document.getElementById('zoombar'));
3031
+ }
3032
+ // Each build runs its OWN loop and stops the moment it is superseded (a sheet switch mid-build), so two
3033
+ // builds never share one generator and the per-task slice stays what HIT_SLICE_MS says (review finding).
3034
+ function hitBuildStep(b){
3035
+ if(hitBuild !== b) return;
3036
+ const r = b.it.next();
3037
+ if(!r.done){ setTimeout(() => hitBuildStep(b), 0); return; }
3038
+ hitIndexCache.set(b.els, r.value);
3039
+ hitBuild = null;
3040
+ syncHitReady();
3041
+ const at = hitPending; hitPending = null; // cleared by any press too: see pointerdown below
3042
+ if(at && hoverOn && !drag && !eye.classList.contains('show') && !hoverEl && sheets[active] && sheets[active].elements === b.els) hoverAt(at.x, at.y);
3043
+ }
3044
+ /**
3045
+ * The element nearest the pointer within HIT_PX, among ALL of the sheet's elements, shown or not --
3046
+ * null when nothing is there, or HIT_PENDING while the sheet's grid is still being built. Screen to drawing through the overlay's own CTM, so the viewBox, the letterboxing of
3047
+ * preserveAspectRatio and the zoom are all accounted for, and the tolerance is the same 4 CSS px at
3048
+ * any zoom.
3049
+ */
3050
+ function probeAt(clientX, clientY){
3051
+ const ctm = typeof overlay.getScreenCTM === 'function' ? overlay.getScreenCTM() : null;
3052
+ if(!ctm) return null;
3053
+ const ix = hitIndexFor(sheets[active]);
3054
+ if(!ix){ hitPending = { x: clientX, y: clientY }; return HIT_PENDING; }
3055
+ const inv = ctm.inverse();
3056
+ const x = inv.a * clientX + inv.c * clientY + inv.e;
3057
+ const y = inv.b * clientX + inv.d * clientY + inv.f;
3058
+ const scale = Math.hypot(ctm.a, ctm.b);
3059
+ if(!(scale > 0)) return null;
3060
+ // Shown lines first: a switched-off line or label within reach never takes the pointer from a drawn one.
3061
+ return hitTest(ix, x, y, HIT_PX / scale, el => matchesActive(el, mode, sel));
3062
+ }
3063
+ /** Read out whatever the probe finds at this point, or clear the readout when it finds nothing. */
3064
+ function hoverAt(clientX, clientY){
3065
+ const hit = probeAt(clientX, clientY);
3066
+ if(hit === HIT_PENDING) return; // re-read at this point when the grid lands (hitBuildStep)
3067
+ if(!hit){ if(hoverEl) hoverClear(); return; }
3068
+ hoverShow(hit.el, clientX, clientY, !matchesActive(hit.el, mode, sel));
3069
+ }
3070
+ /**
3071
+ * A click off every mounted line (with Hover info on, that is every click once the grid is ready).
3072
+ * It picks what the readout names: a shown line within reach, or one the filter has switched off
3073
+ * (#1527). Only a spot with nothing FloLess read there asks the ORIGINAL drawing (#1528).
3074
+ *
3075
+ * While the grid is still building (a fraction of a second on a large sheet) the answer is not
3076
+ * "nothing here", so the click must NOT ask the original drawing -- that asked it about a spot holding
3077
+ * a switched-off line FloLess read (review finding). It does exactly what it did before #1527: a shown
3078
+ * line under the pointer is still a mounted DOM target and the pointerup handler picks it before this
3079
+ * runs; anything else just closes the popover. Nothing is held for later: a deferred click outlived
3080
+ * the user's next action and replaced whatever they had opened (review finding), for a window too
3081
+ * short to be worth any state. With the mode off, a miss only closes, as it always did.
3082
+ */
3083
+ function pickAt(clientX, clientY){
3084
+ const hit = hoverOn ? probeAt(clientX, clientY) : null;
3085
+ // hitPending too: probeAt just stored this CLICK as a hover to re-read when the grid lands.
3086
+ if(hit === HIT_PENDING){ hitPending = null; closeEye(); return; }
3087
+ if(hit) openEyedropper(clientX, clientY, hit.el);
3088
+ else if(hoverOn && identifyAvailable()) openIdentify(clientX, clientY);
3089
+ else closeEye();
3090
+ }
3091
+
3092
+ // Where the popover was opened, so apply() can redraw it IN PLACE when the selection moves under it.
3093
+ let eyeAt = { x: 0, y: 0 };
3094
+ function openEyedropper(clientX, clientY, el, opts = {}){
3095
+ // A new pick supersedes any pending original-drawing read (#1528). A REDRAW of the same pick
3096
+ // (apply() after a facet toggle) keeps it: that is still the line the stepper is on.
3097
+ if(opts.rescroll !== false) identifyCancel();
1918
3098
  eyeEl = el;
3099
+ focusFilterFacet('layer', String(el.layer || 'this drawing element'));
3100
+ // Recorded on a fresh pick only: a redraw in place keeps how the pick was made.
3101
+ const off = !matchesActive(el, mode, sel);
3102
+ if(opts.rescroll !== false) eyeOff = off;
3103
+ eyeAt = { x: clientX, y: clientY };
1919
3104
  const body = document.getElementById('eyeBody');
1920
3105
  const rows = [];
1921
3106
  // A picked element whose value is not a value for its dimension cannot be added — `eyedropperAdd`
@@ -1925,16 +3110,41 @@ function openEyedropper(clientX, clientY, el){
1925
3110
  const dropped = ['layer', 'thickness', 'color'].filter(dim => eyeOffers(el, dim) && !addable(dim));
1926
3111
  const whyBlocked = (dim) => facetKey(dim, el[FACET_DIMS[dim].elementKey]) === undefined
1927
3112
  ? NO_VALUE_REASON(FACET_CONTROL_OF[dim]) : NO_ROW_REASON(FACET_CONTROL_OF[dim]);
1928
- rows.push(eyeRow('Layer', el.layer, 'layer', `<span class="sw" style="background:${safeColor(layerColor[el.layer])}"></span>`, addable('layer'), whyBlocked('layer')));
3113
+ // A value that is ALREADY ticked gets − Remove instead of + Add, never both. For a line the filter is
3114
+ // SHOWING, the value on the dimension being matched on is always ticked already, and + Add was a no-op
3115
+ // for exactly the value the user picked the line to get rid of. For a SWITCHED-OFF pick (#1527) it is
3116
+ // the other way round: at least one matched value is unticked, and its + Add is what brings it back.
3117
+ const selected = (dim) => eyedropperHas(sel, el, dim);
3118
+ rows.push(eyeRow('Layer', el.layer, 'layer', `<span class="sw" style="background:${safeColor(layerColor[el.layer])}"></span>`, addable('layer'), whyBlocked('layer'), selected('layer')));
1929
3119
  // Offered when applicable, refused when unusable — the same two-step as layer and colour.
1930
- if(eyeOffers(el, 'thickness')) rows.push(eyeRow('Thickness', thicknessLabel(el.w), 'thickness', '', addable('thickness'), whyBlocked('thickness')));
1931
- rows.push(eyeRow('Color', el.color, 'color', `<span class="sw" style="background:${safeColor(el.color)}"></span>`, addable('color'), whyBlocked('color')));
3120
+ if(eyeOffers(el, 'thickness')) rows.push(eyeRow('Thickness', thicknessLabel(el.w), 'thickness', '', addable('thickness'), whyBlocked('thickness'), selected('thickness')));
3121
+ rows.push(eyeRow('Color', el.color, 'color', `<span class="sw" style="background:${safeColor(el.color)}"></span>`, addable('color'), whyBlocked('color'), selected('color')));
3122
+ if(off) rows.unshift(`<div class="eoff">${esc(OFF_NOTE)}</div>`);
1932
3123
  body.innerHTML = rows.join('');
1933
- body.querySelectorAll('button[data-add]:not([aria-disabled])').forEach(b => b.onclick = () => { eyedropperAdd(sel, el, b.dataset.add); syncFacetChecks(); markDirty(); apply(); closeEye(); });
3124
+ body.querySelectorAll('button[data-add]:not([aria-disabled])').forEach(b => b.onclick = () => {
3125
+ eyedropperAdd(sel, el, b.dataset.add); syncFacetChecks(); markDirty(); apply(); closeEyeUnlessStillOff(el);
3126
+ });
3127
+ // A Remove always changes the selection — the button exists only for a ticked value, and the check
3128
+ // below proves it at the moment of the click — so it marks dirty unconditionally, the same as the
3129
+ // per-row checkbox handler. apply() then closes the popover
3130
+ // on its own when the pick stops matching; closeEye() covers the dimension that is not being matched
3131
+ // on, where the line stays on the drawing.
3132
+ // Checked, not assumed: "the button only exists for a ticked value" holds when the popover is DRAWN.
3133
+ // apply() redraws it whenever the selection moves, so this should never fire — but if it ever does, a
3134
+ // Remove that silently removed nothing and still raised "Unsaved ●" is the report this surface keeps
3135
+ // having to answer, so the popover is redrawn to show the truth instead.
3136
+ body.querySelectorAll('button[data-remove]').forEach(b => b.onclick = () => {
3137
+ if(!eyedropperHas(sel, el, b.dataset.remove)){ openEyedropper(eyeAt.x, eyeAt.y, el, { rescroll: false }); return; }
3138
+ eyedropperRemove(sel, el, b.dataset.remove); syncFacetChecks(); markDirty(); apply(); closeEye();
3139
+ });
1934
3140
  // The Add-all control tells the truth about what it is about to do — including refusing outright
1935
3141
  // when the pick offers nothing this filter can express.
1936
3142
  const addAll = document.getElementById('eyeAddAll');
1937
3143
  const addableCount = eyeAddableDims(el).length;
3144
+ // Hidden, not disabled, once every usable value is already ticked: there is nothing left for it to
3145
+ // add, and this page hides a dead control rather than showing it inert. The label is still computed
3146
+ // below, so a later pick that DOES leave something to add finds it correct.
3147
+ addAll.hidden = addableCount > 0 && eyeAddableDims(el).every(dim => selected(dim));
1938
3148
  addAll.textContent = addableCount === 0 ? 'Add all to filter'
1939
3149
  : dropped.length ? 'Add the ' + addableCount + ' usable value' + (addableCount === 1 ? '' : 's')
1940
3150
  : 'Add all to filter';
@@ -1948,12 +3158,48 @@ function openEyedropper(clientX, clientY, el){
1948
3158
  if(dropped.length) addAll.setAttribute('data-tip', whyBlocked(dropped[0]));
1949
3159
  else addAll.removeAttribute('data-tip');
1950
3160
  }
3161
+ // Light the element's own rows (hover does that too) and — on the click only, never on hover — SCROLL
3162
+ // THEM INTO VIEW. Reading a long layer name off a popover and then hunting it by eye down a list of
3163
+ // hundreds of rows is the trial and error this slice exists to remove; but a list that jumps under the
3164
+ // cursor on every sweep is worse than the problem, so the scroll is owed to a deliberate gesture. A
3165
+ // redraw in place (apply() below, `rescroll:false`) does not scroll: the user may be working in that list.
3166
+ // `block:'nearest'` so an already-visible row does not move at all.
3167
+ const lit = markHotRows(el);
3168
+ // The POPOVER owns the halo while it is open: it marks the line this popover is about. Painted here,
3169
+ // not left to the last hover, because a second click on another line while the popover is open never
3170
+ // produced a hover (the popover freezes it) — so the halo stayed on the FIRST line while the popover
3171
+ // and its − Remove described the second (review finding). Only with Hover info on: the halo is that
3172
+ // mode's, and a user who left it off asked for a quieter drawing.
3173
+ hot.replaceChildren();
3174
+ if(hoverOn){
3175
+ // The same halo the pick had under the pointer, ghost included when it is switched off.
3176
+ paintHot(el, off);
3177
+ hoverEl = el;
3178
+ }
3179
+ // The chip goes: the popover now says everything it did, beside the pointer where it was.
3180
+ hoverbar.hidden = true;
3181
+ if(opts.rescroll !== false){
3182
+ for(const dim of MODE_ORDER){
3183
+ const row = lit[dim][0];
3184
+ if(row && typeof row.scrollIntoView === 'function') row.scrollIntoView({ block: 'nearest' });
3185
+ }
3186
+ }
3187
+ placeEye(clientX, clientY, opts.rescroll === false);
3188
+ }
3189
+ // Show #eye beside a click, clamped to stay on screen. Shared by the pick and the original-drawing read.
3190
+ // A REDRAW keeps the popover where it is, clamped only to stay on screen. Re-deriving from the click
3191
+ // moved it whenever the redraw changed its height (Add all appearing or going) — under the pointer of a
3192
+ // user who is working in the panel, not in the popover (Codex review).
3193
+ function placeEye(clientX, clientY, redraw){
1951
3194
  eye.classList.add('show');
1952
3195
  const w = eye.offsetWidth || 220, h = eye.offsetHeight || 160;
1953
- eye.style.left = Math.min(clientX + 8, window.innerWidth - w - 8) + 'px';
1954
- eye.style.top = Math.min(clientY + 8, window.innerHeight - h - 8) + 'px';
3196
+ const keep = redraw && eye.style.left && eye.style.top;
3197
+ const x = keep ? parseFloat(eye.style.left) : clientX + 8;
3198
+ const y = keep ? parseFloat(eye.style.top) : clientY + 8;
3199
+ eye.style.left = Math.max(8, Math.min(x, window.innerWidth - w - 8)) + 'px';
3200
+ eye.style.top = Math.max(8, Math.min(y, window.innerHeight - h - 8)) + 'px';
1955
3201
  }
1956
- function eyeRow(k, v, which, swatch, addable, reason){
3202
+ function eyeRow(k, v, which, swatch, addable, reason, selected){
1957
3203
  // data-tip, never title=: .v ellipsizes, so this row NEEDS a tooltip to show a long layer name in
1958
3204
  // full — and a native title= would draw it as the light OS bubble, the one browser default this
1959
3205
  // surface still leaked. The themed #tooltip handler at the foot of this file renders it.
@@ -1963,9 +3209,32 @@ function eyeRow(k, v, which, swatch, addable, reason){
1963
3209
  // explanation on any modality. The click handler is simply not bound to it.
1964
3210
  const why = reason || NO_VALUE_REASON(FACET_CONTROL_OF[which]);
1965
3211
  const blocked = addable ? '' : ` aria-disabled="true" data-blocked-reason="${esc(why)}" data-tip="${esc(why)}"`;
1966
- return `<div class="erow"><span class="k">${k}</span>${swatch}<span class="v" data-tip="${esc(v)}">${esc(v)}</span><button data-add="${which}" data-command-id="filter.eyedropper-add"${blocked}>+ Add</button></div>`;
3212
+ // `data-dim` on BOTH buttons, so anything asking "which dimension is this control for" does not
3213
+ // have to know which of the two a ticked value turned it into.
3214
+ if(selected){
3215
+ return `<div class="erow"><span class="k">${k}</span>${swatch}<span class="v" data-tip="${esc(v)}">${esc(v)}</span><button data-remove="${which}" data-dim="${which}" data-command-id="filter.eyedropper-remove" data-tip="${esc(removeTip(which))}">− Remove</button></div>`;
3216
+ }
3217
+ return `<div class="erow"><span class="k">${k}</span>${swatch}<span class="v" data-tip="${esc(v)}">${esc(v)}</span><button data-add="${which}" data-dim="${which}" data-command-id="filter.eyedropper-add"${blocked}>+ Add</button></div>`;
3218
+ }
3219
+ /**
3220
+ * What − Remove will do, said BEFORE it is pressed — and it differs by whether the dimension is being
3221
+ * matched on. Unticking a matched layer takes every line on it off the drawing; unticking a colour
3222
+ * while only Layer is ticked under Match on changes the selection and nothing you can see, and a
3223
+ * button that silently "did nothing" is the report this surface keeps having to answer.
3224
+ */
3225
+ function removeTip(dim){
3226
+ const noun = FACET_NOUN[FACET_CONTROL_OF[dim]];
3227
+ const matchOn = { layer: 'Layer', thickness: 'Thickness', color: 'Color' }[dim];
3228
+ return modeDims(mode).includes(dim)
3229
+ ? 'Untick this ' + noun + ' in the filter. Every line with it stops being selected and drops back into the background drawing; nothing is saved until you press Save filter.'
3230
+ : 'Untick this ' + noun + ' in the filter. “' + matchOn + '” isn’t ticked under Match on, so the drawing won’t change until it is.';
1967
3231
  }
1968
- function closeEye(){ eye.classList.remove('show'); eyeEl = null; }
3232
+ // Clears the halo and the lit rows along with the popover. While #eye is open they stay on the pick (the
3233
+ // chip itself is hidden); by close time the pointer has crossed other lines to reach + Add / − Remove and
3234
+ // nothing re-fires until it moves again, so this clears rather than re-reads.
3235
+ // UNCONDITIONAL, not `if(hoverEl)`: the popover lights the pick's rows even with Hover info off, when
3236
+ // `hoverEl` is null, and the guarded version left them lit for good (Codex review).
3237
+ function closeEye(){ eye.classList.remove('show'); eyeEl = null; eyeOff = false; identifyCancel(); hoverClear(); }
1969
3238
  document.getElementById('eyeClose').onclick = closeEye;
1970
3239
  // "Add all" is the THIRD surface this refusal has to be honest on, and it was the one left dishonest:
1971
3240
  // the per-dimension + Add buttons refuse visibly while this one stayed enabled and quietly added two
@@ -1975,27 +3244,206 @@ document.getElementById('eyeClose').onclick = closeEye;
1975
3244
  // So it is gated on whether ANY offered dimension is addable, it says which one it is dropping when it
1976
3245
  // cannot take them all, and it marks dirty only when it actually added something.
1977
3246
  document.getElementById('eyeAddAll').onclick = () => {
3247
+ const pick = eyeEl; // apply() below may redraw the popover; the stay-open rule is about THIS pick
1978
3248
  if(eyeEl && eyeAddableDims(eyeEl).length){
3249
+ const beforeSelection=filterAiUndo ? filterAiSelectionCopy() : null;
1979
3250
  // Per DIMENSION, never `'all'`. `eyedropperAdd`'s own `'all'` adds every value with a canonical
1980
3251
  // key, and it cannot know which of them this filter lists a row for — so it would add exactly the
1981
3252
  // unsaveable value the button has just said it is dropping. Adding what was advertised, and only
1982
3253
  // that, is what makes the label true.
1983
3254
  for(const dim of eyeAddableDims(eyeEl)) eyedropperAdd(sel, eyeEl, dim);
3255
+ const selectionChanged=retireFilterAiUndoOnSelectionChange(beforeSelection);
1984
3256
  // The SAME question setAllFacet asks, for the same reason: adding a value that is already ticked
1985
3257
  // changes nothing, and a pick with nothing addable changes nothing at all — neither is an edit.
1986
- syncFacetChecks(); if(['layers','thicknesses','colors'].some(facetOnWouldChange)) markDirty(); apply();
3258
+ syncFacetChecks(); if(['layers','thicknesses','colors'].some(facetOnWouldChange)) markDirty(selectionChanged); apply();
1987
3259
  }
1988
3260
  // KNOWING EQUIVALENT MUTANT: dropping the `eyeAddableDims(...).length` guard turns no test red,
1989
3261
  // because `eyedropperAdd` skips every unusable value anyway and `saveWouldChange` then reports no
1990
3262
  // edit — the call is a provable no-op. It is kept as defence in depth and to state the intent, and
1991
3263
  // recorded here so the next person reading a sweep can tell it from an untested branch. The gate
1992
3264
  // that a user can actually observe is the `aria-disabled` + reason set in `openEyedropper`.
1993
- closeEye();
3265
+ closeEyeUnlessStillOff(pick);
1994
3266
  };
1995
3267
 
3268
+ /* -- What the ORIGINAL drawing has at an empty spot (#1528) -----------------------------------------
3269
+ WHY. The background is a flat image, so a pixel carries no layer, and some lines are on the drawing
3270
+ but in no vector FloLess drew: layers it reads as annotation (withheld on purpose, see #990) and
3271
+ anything else it did not read. With hundreds of layers, trial and error was the only way to name one.
3272
+
3273
+ WHAT. With Hover info on, a click on an empty spot asks the server what the source PDF has there. The
3274
+ server answers from the drawing's own geometry (the nearest line, the fill under the point, or a
3275
+ label), never by reasoning. Nothing here decides anything: it renders the answer.
3276
+ - inFilter: the hit IS an element FloLess read, so its own popover opens (it owns + Add / − Remove).
3277
+ - withheld / sourceOnly: a read-only card in the same popover, with one plain sentence saying what
3278
+ FloLess did with it. No Add button: there is no filter row that could bring it back.
3279
+ The layer's row in the Filters panel is lit when one exists (withheld layers are still listed there).
3280
+
3281
+ STALE ANSWERS. The first read of a sheet takes seconds, so every read carries a generation and the
3282
+ sheet identity it was asked for. Any newer click, a pick, closing the popover or switching sheet bumps
3283
+ the generation (and aborts the request), and an answer renders only if nothing has moved since. */
3284
+ const eyeTitle = document.getElementById('eyeTitle');
3285
+ const eyeStep = document.getElementById('eyeStep');
3286
+ const eyeStepLabel = document.getElementById('eyeStepLabel');
3287
+ const eyePrev = document.getElementById('eyePrev'), eyeNext = document.getElementById('eyeNext');
3288
+ /** How far from the click a line still counts, in screen pixels, converted at the current zoom. */
3289
+ const IDENTIFY_RADIUS_PX = 6;
3290
+ const IDENTIFY_COPY = {
3291
+ loading: 'Reading the original drawing. The first time on a sheet this can take a few seconds.',
3292
+ empty: 'No line or text FloLess can identify at this spot. Scanned or pictured parts of a drawing can’t be identified.',
3293
+ failed: 'Couldn’t read the original drawing right now. Try again in a moment.',
3294
+ withheld: 'FloLess didn’t read this layer’s lines. Its name marks it as annotation — text, dimensions or a title block.',
3295
+ sourceOnly: 'This is on the original drawing, but it isn’t among the lines FloLess read on this sheet.',
3296
+ inFilter: 'FloLess read this line on this sheet. Reload the page to pick it in the filter.',
3297
+ };
3298
+ let identifyGen = 0, identifyAbort = null, identifyShown = null;
3299
+
3300
+ /** Only where there is a source to read: a project sheet with its drawing image behind it. */
3301
+ function identifyAvailable(){
3302
+ const sh = sheets[active];
3303
+ return !!PROJECT && !!sh && typeof sh.sheet === 'string' && /^[0-9a-f]{64}$/i.test(String(sh.sourceHash || '')) && hasRasterContext();
3304
+ }
3305
+
3306
+ /** Forget any pending or shown original-drawing read and put the popover back in its pick shape. */
3307
+ function identifyCancel(){
3308
+ identifyGen++;
3309
+ if(identifyAbort){ try{ identifyAbort.abort(); }catch{ /* already settled */ } identifyAbort = null; }
3310
+ identifyShown = null;
3311
+ eye.classList.remove('identify');
3312
+ eyeStep.hidden = true;
3313
+ eyeTitle.textContent = 'Picked element';
3314
+ }
3315
+
3316
+ /**
3317
+ * The click in SHEET coordinates, and the search radius in the same units. Through the inverse screen
3318
+ * matrix, never by scaling across the element's box: the canvas is letterboxed (`xMidYMid meet`), so a
3319
+ * plain proportion is off by the letterbox whenever the stage's shape differs from the sheet's.
3320
+ */
3321
+ function sheetPointAt(clientX, clientY){
3322
+ const m = typeof svg.getScreenCTM === 'function' ? svg.getScreenCTM() : null;
3323
+ if(!m) return null;
3324
+ const inv = m.inverse();
3325
+ const at = new DOMPoint(clientX, clientY).matrixTransform(inv);
3326
+ const off = new DOMPoint(clientX + IDENTIFY_RADIUS_PX, clientY).matrixTransform(inv);
3327
+ return { x: at.x, y: at.y, r: Math.hypot(off.x - at.x, off.y - at.y) };
3328
+ }
3329
+
3330
+ function identifyMessage(text){
3331
+ document.getElementById('eyeBody').innerHTML = `<p class="enote">${esc(text)}</p>`;
3332
+ document.getElementById('eyeAddAll').hidden = true;
3333
+ }
3334
+
3335
+ async function openIdentify(clientX, clientY){
3336
+ const sh = sheets[active];
3337
+ const p = sheetPointAt(clientX, clientY);
3338
+ closeEye();
3339
+ if(!p || !sh) return;
3340
+ const gen = ++identifyGen;
3341
+ const ctl = typeof AbortController === 'function' ? new AbortController() : null;
3342
+ identifyAbort = ctl;
3343
+ hoverbar.hidden = true;
3344
+ eye.classList.add('identify');
3345
+ eyeTitle.textContent = 'From the original drawing';
3346
+ identifyMessage(IDENTIFY_COPY.loading);
3347
+ placeEye(clientX, clientY, false);
3348
+ const asked = { sheet: sh.sheet, sourceHash: String(sh.sourceHash).toLowerCase() };
3349
+ const current = () => gen === identifyGen && eye.classList.contains('show') && !!sheets[active]
3350
+ && sheets[active].sheet === asked.sheet && String(sheets[active].sourceHash).toLowerCase() === asked.sourceHash;
3351
+ let body = null, ok = false, res403 = false;
3352
+ try {
3353
+ const qs = new URLSearchParams({ sheet: asked.sheet, sourceHash: asked.sourceHash, x: p.x.toFixed(2), y: p.y.toFixed(2), r: p.r.toFixed(2) });
3354
+ const res = await fetch('/api/projects/' + encodeURIComponent(PROJECT) + '/drawing-identify?' + qs, ctl ? { signal: ctl.signal } : {});
3355
+ res403 = res.status === 403;
3356
+ body = await res.json().catch(() => null);
3357
+ ok = res.ok && !!body && body.ok === true;
3358
+ } catch(err) {
3359
+ ok = false;
3360
+ if(!err || err.name !== 'AbortError') console.warn('steel-filter: original-drawing lookup failed', err && err.name);
3361
+ }
3362
+ if(!current()) return; // a newer click, a pick, a close or another sheet got there first
3363
+ identifyAbort = null;
3364
+ // Only the route's OWN refusals are shown as written — they are sentences for this reader, marked by an
3365
+ // identify-* code (or the module policy's 403). Anything else — a framework 500, a proxy page, an older
3366
+ // server without the route — gets the generic sentence, never its raw text.
3367
+ const own = !!body && body.ok === false && typeof body.error === 'string' && body.error
3368
+ && typeof body.code === 'string' && (body.code.startsWith('identify-') || res403);
3369
+ if(!ok){
3370
+ if(body && body.ok !== true) console.warn('steel-filter: original-drawing lookup refused', body.code || '(no code)');
3371
+ identifyMessage(own ? body.error : IDENTIFY_COPY.failed); placeEye(clientX, clientY, true); return;
3372
+ }
3373
+ const hits = Array.isArray(body.hits) ? body.hits.filter(h => h && typeof h === 'object') : [];
3374
+ if(!hits.length){ identifyMessage(IDENTIFY_COPY.empty); placeEye(clientX, clientY, true); return; }
3375
+ identifyShown = { hits, i: 0, at: { x: clientX, y: clientY } };
3376
+ identifyRender(true);
3377
+ }
3378
+
3379
+ function identifyRow(k, v, swatch = ''){
3380
+ return `<div class="erow"><span class="k">${k}</span>${swatch}<span class="v" data-tip="${esc(v)}">${esc(v)}</span></div>`;
3381
+ }
3382
+
3383
+ /** Render hit `identifyShown.i`. `first` places it at the click and scrolls its panel row into view. */
3384
+ function identifyRender(first){
3385
+ const shown = identifyShown;
3386
+ if(!shown) return;
3387
+ const hit = shown.hits[shown.i];
3388
+ if(hit.status === 'inFilter' && typeof hit.elementId === 'string'){
3389
+ const el = (((sheets[active] || {}).elements) || []).find(e => e && e.elementId === hit.elementId);
3390
+ if(el){
3391
+ // Back in the pick's own shape: a step (first=false) redraws in place, which on its own would
3392
+ // leave the read-only card's title and width behind.
3393
+ eye.classList.remove('identify');
3394
+ eyeTitle.textContent = 'Picked element';
3395
+ // A STEP redraws in place, and a redraw does not record whether the pick is switched off -- so
3396
+ // stepping onto a switched-off line FloLess read kept the previous hit's answer, and the next panel
3397
+ // change closed its popover under the user (review finding, #1527 × #1528). Recorded here.
3398
+ eyeOff = !matchesActive(el, mode, sel);
3399
+ openEyedropper(shown.at.x, shown.at.y, el, first ? {} : { rescroll: false });
3400
+ // openEyedropper reset the popover to its pick shape; keep the way back to the other lines here.
3401
+ if(shown.hits.length > 1){ identifyShown = shown; identifyStep(); }
3402
+ return;
3403
+ }
3404
+ }
3405
+ eyeEl = null;
3406
+ eye.classList.add('identify');
3407
+ eyeTitle.textContent = 'From the original drawing';
3408
+ const colour = hit.kind === 'fill' && hit.fillColor ? hit.fillColor : hit.color;
3409
+ const sw = (c) => `<span class="sw" style="background:${safeColor(c)}"></span>`;
3410
+ const rows = [identifyRow('Layer', String(hit.layer || '') + (hit.dashed ? ' (dashed)' : ''), layerColor[hit.layer] ? sw(layerColor[hit.layer]) : '')];
3411
+ if(hit.kind === 'text'){
3412
+ rows.push(identifyRow('Text', String(hit.text || '')));
3413
+ if(hit.sourceLayer && hit.sourceLayer !== hit.layer) rows.push(identifyRow('Source layer', String(hit.sourceLayer)));
3414
+ } else {
3415
+ rows.push(identifyRow('Thickness', typeof hit.width === 'number' ? thicknessLabel(hit.width) : '—'));
3416
+ }
3417
+ rows.push(identifyRow('Color', String(colour || '—'), sw(colour)));
3418
+ if(hit.kind === 'line' && hit.fillColor && hit.fillColor !== hit.color) rows.push(identifyRow('Fill', String(hit.fillColor), sw(hit.fillColor)));
3419
+ // An inFilter hit lands here only when this page's copy of the sheet lacks that element (the filter
3420
+ // was re-read since it loaded): say so, never "FloLess didn't read it".
3421
+ const note = hit.status === 'withheld' ? IDENTIFY_COPY.withheld : hit.status === 'inFilter' ? IDENTIFY_COPY.inFilter : IDENTIFY_COPY.sourceOnly;
3422
+ document.getElementById('eyeBody').innerHTML = rows.join('') + `<p class="enote">${esc(note)}</p>`;
3423
+ document.getElementById('eyeAddAll').hidden = true;
3424
+ // The LAYER row only: a withheld layer is still listed, and naming its row is the point. Its colour
3425
+ // or thickness rows would light values that do nothing for this line.
3426
+ const lit = markHotRows({ kind: hit.kind === 'text' ? 'text' : 'line', layer: hit.layer });
3427
+ if(first && lit.layer[0] && typeof lit.layer[0].scrollIntoView === 'function') lit.layer[0].scrollIntoView({ block: 'nearest' });
3428
+ identifyStep();
3429
+ placeEye(shown.at.x, shown.at.y, !first);
3430
+ }
3431
+
3432
+ function identifyStep(){
3433
+ const shown = identifyShown;
3434
+ eyeStep.hidden = !shown || shown.hits.length < 2;
3435
+ if(eyeStep.hidden) return;
3436
+ eyeStepLabel.textContent = (shown.i + 1) + ' of ' + shown.hits.length;
3437
+ eyePrev.disabled = shown.i === 0;
3438
+ eyeNext.disabled = shown.i === shown.hits.length - 1;
3439
+ }
3440
+ eyePrev.onclick = () => { if(identifyShown && identifyShown.i > 0){ identifyShown.i--; identifyRender(false); } };
3441
+ eyeNext.onclick = () => { if(identifyShown && identifyShown.i < identifyShown.hits.length - 1){ identifyShown.i++; identifyRender(false); } };
3442
+
1996
3443
  // --- pan/zoom via viewBox; a click (no drag) on an element opens the eyedropper ---
1997
3444
  let base = { x:0, y:0, w:1000, h:1000 }, vb = { ...base }, drag = null;
1998
- function setVB(){ svg.setAttribute('viewBox', `${vb.x} ${vb.y} ${vb.w} ${vb.h}`); }
3445
+ // BOTH svgs, always together: #under (raster + halo) must register 1:1 with the linework on #canvas.
3446
+ function setVB(){ const v = `${vb.x} ${vb.y} ${vb.w} ${vb.h}`; svg.setAttribute('viewBox', v); under.setAttribute('viewBox', v); }
1999
3447
  svg.addEventListener('wheel', e => {
2000
3448
  e.preventDefault();
2001
3449
  const r = svg.getBoundingClientRect();
@@ -2022,7 +3470,9 @@ svg.addEventListener('pointermove', e => {
2022
3470
  svg.addEventListener('pointerup', e => {
2023
3471
  svg.classList.remove('dragging');
2024
3472
  if(drag && !drag.moved && drag.target && drag.target.__el) openEyedropper(e.clientX, e.clientY, drag.target.__el);
2025
- else if(drag && !drag.moved) closeEye();
3473
+ // Everything else is `pickAt` (see it): probed again at the click itself, never taken from the last
3474
+ // frame's readout, which may be a frame stale.
3475
+ else if(drag && !drag.moved) pickAt(e.clientX, e.clientY);
2026
3476
  drag = null;
2027
3477
  });
2028
3478
  function fit(){ vb = { ...base }; setVB(); }
@@ -2030,6 +3480,66 @@ function zoomSteel(){ const b = sheets[active] && sheets[active].steelBbox; if(!
2030
3480
  document.getElementById('fit2').onclick = fit;
2031
3481
  document.getElementById('zoomsteel2').onclick = zoomSteel;
2032
3482
 
3483
+ /* Hover info's listeners live down here rather than with its definitions above, and the reason is the
3484
+ two names in them: `svg`, whose pointer events these are, and `drag`, which pan/zoom declares just
3485
+ above. Everything the popover and the overlay rebuild have to be able to call -- hoverClear,
3486
+ markHotRows -- is defined up with the eyedropper's own state instead, so that the page's facet
3487
+ region stays self-contained: it is what the linkedom harnesses slice out and run. */
3488
+ {
3489
+ // Start the grid as soon as it can be wanted -- the mode switched on, the pointer entering the stage --
3490
+ // so it is usually ready before the pointer first reaches a switched-off line.
3491
+ const warmHitIndex = () => { if(hoverOn) hitIndexFor(sheets[active]); };
3492
+ hoverBtn.addEventListener('click', () => { setHoverInfo(!hoverOn); warmHitIndex(); });
3493
+ svg.addEventListener('pointerenter', warmHitIndex);
3494
+ // A press voids any read still waiting on the grid: after a pan the stored screen point sits over a
3495
+ // different part of the drawing, and reading it would name a line the pointer is not on (review).
3496
+ svg.addEventListener('pointerdown', () => { hitPending = null; });
3497
+ // At most ONE probe per frame, at the pointer's latest position: pointermove can fire several times a
3498
+ // frame on a high-rate mouse, and every one but the last would be work nobody sees.
3499
+ let probeRaf = 0, probeXY = null;
3500
+ const cancelProbe = () => { if(probeRaf) cancelAnimationFrame(probeRaf); probeRaf = 0; probeXY = null; hitPending = null; };
3501
+ // ONE listener on the svg, never one per node. Once the sheet's grid is built the linework takes no
3502
+ // pointer input (see `#canvas.hoverinfo.hit-ready #overlay .el`), so a shown line, a switched-off one and
3503
+ // empty stage are all answered the same way, by the hit test over the drawing data (#1527), which
3504
+ // clears the readout itself when nothing is within reach. Before that, a MOUNTED line under the
3505
+ // pointer is read straight from the DOM, as it always was.
3506
+ svg.addEventListener('pointermove', e => {
3507
+ if(!hoverOn || eye.classList.contains('show')) return; // the popover owns the halo while open
3508
+ // ANY press, not only a moving one: a pan is not a read, and a plain click is the pick, whose own
3509
+ // probe runs at pointerup.
3510
+ if(drag) return;
3511
+ if(e.target && e.target.__el){ cancelProbe(); hoverShow(e.target.__el, e.clientX, e.clientY, false); return; }
3512
+ probeXY = { x: e.clientX, y: e.clientY };
3513
+ if(probeRaf) return;
3514
+ probeRaf = requestAnimationFrame(() => {
3515
+ const at = probeXY; probeRaf = 0; probeXY = null;
3516
+ if(at && hoverOn && !drag && !eye.classList.contains('show')) hoverAt(at.x, at.y);
3517
+ });
3518
+ });
3519
+ // Not while the popover is open: reaching its buttons means leaving the svg, and clearing then took
3520
+ // the halo off the very line the popover is about (Codex review). closeEye() clears it instead.
3521
+ svg.addEventListener('pointerleave', () => { cancelProbe(); if(hoverEl && !eye.classList.contains('show')) hoverClear(); });
3522
+ // A PAN ends with the pointer somewhere new and NOTHING re-fires until it moves again -- pointer
3523
+ // capture retargeted every boundary event to the svg for the whole drag. Without this the readout
3524
+ // keeps describing the line the drag started on, and if the pointer settled back on that same line
3525
+ // the `el === hoverEl` guard would swallow the next genuine read too.
3526
+ // ONLY a pan. A plain click is the pick, and clearing on it wiped the halo off the very line the
3527
+ // popover had just opened for -- caught in the real browser pass, where the popover sat over a
3528
+ // drawing that no longer showed which line it was about. Capture phase, because pan/zoom's own
3529
+ // pointerup (registered earlier, on the same node) nulls `drag`, and by the bubble phase there is
3530
+ // no longer any way to tell a pan from a click.
3531
+ svg.addEventListener('pointerup', () => { if(hoverOn && hoverEl && drag && drag.moved) hoverClear(); }, true);
3532
+ // A wheel zoom moves the drawing under a chip that is placed only when the ELEMENT changes, leaving it
3533
+ // floating over whatever is there now. Cleared; the next line the pointer meets re-reads it.
3534
+ svg.addEventListener('wheel', () => { cancelProbe(); if(hoverEl && !eye.classList.contains('show')) hoverClear(); }, { passive: true });
3535
+ const wanted = () => { try{ return localStorage.getItem(HOVER_LS) === '1'; }catch{ return false; /* private mode */ } };
3536
+ if(wanted()) setHoverInfo(true, false);
3537
+ // The device changed, not the user's mind: follow it both ways without rewriting the stored choice.
3538
+ if(HOVER_MQ && typeof HOVER_MQ.addEventListener === 'function'){
3539
+ HOVER_MQ.addEventListener('change', () => setHoverInfo(canHover() && wanted(), false));
3540
+ }
3541
+ }
3542
+
2033
3543
  // --- save: write the selection + mode onto C.filter and PUT the contract ---
2034
3544
  saveBtn.onclick = () => { void beginSave(); };
2035
3545
  // Serialize THIS tab's writes, as the steel editor does. Without it the page conflicts with ITSELF:
@@ -2043,7 +3553,8 @@ let writeQueue = Promise.resolve();
2043
3553
  const queueWrite = (fn) => (writeQueue = writeQueue.then(fn, fn));
2044
3554
  function save(){ return queueWrite(saveNow); }
2045
3555
  function blockRequiredCheckpointSave(message){
2046
- checkpointSaveBlocked = true;
3556
+ retireFilterAiUndo('This required save needs a reload, so Undo is no longer available.');
3557
+ checkpointSaveBlocked = true; notifyFilterAi();
2047
3558
  setSaved('err');
2048
3559
  setRequiredSaveCue(false, false);
2049
3560
  saveBtn.disabled = true;
@@ -2074,6 +3585,7 @@ const signoffList = document.getElementById('signoffList');
2074
3585
  const signoffTotal = document.getElementById('signoffTotal');
2075
3586
  const signoffCaption = document.getElementById('signoffCaption');
2076
3587
  const signoffNotice = document.getElementById('signoffNotice');
3588
+ const signoffSaveStatus = document.getElementById('signoffSaveStatus');
2077
3589
  const signoffCancel = document.getElementById('signoffCancel');
2078
3590
  const signoffApprove = document.getElementById('signoffApprove');
2079
3591
  const signoffCloseBtn = document.getElementById('signoffClose');
@@ -2243,6 +3755,9 @@ function setSignoffMode(problem){
2243
3755
 
2244
3756
  let signoffCoveredSurfaces = [];
2245
3757
  function coverSignoffBackground(){
3758
+ // The dismissal confirmation blocks Apply/Undo from AI Chat while it is open (queued, so it sees the
3759
+ // overlay state the caller sets next).
3760
+ notifyFilterAi();
2246
3761
  if(signoffCoveredSurfaces.length) return;
2247
3762
  signoffCoveredSurfaces = ['app', 'eye'].map((id) => document.getElementById(id)).filter(Boolean).map((element) => ({
2248
3763
  element,
@@ -2255,6 +3770,7 @@ function coverSignoffBackground(){
2255
3770
  }
2256
3771
  }
2257
3772
  function restoreSignoffBackground(){
3773
+ notifyFilterAi();
2258
3774
  for(const { element, hadInert, ariaHidden } of signoffCoveredSurfaces){
2259
3775
  // The Save transaction may still own this lock when polling retires the dialog's checkpoint.
2260
3776
  // Release only the dialog's share; saveNow.finally performs the last unlock after both writes.
@@ -2546,7 +4062,19 @@ function retireSignOffForCheckpointChange(){
2546
4062
  function setSignoffBusy(busy){
2547
4063
  signoffBusy = busy;
2548
4064
  signoffCancel.disabled = busy; signoffApprove.disabled = busy;
2549
- signoffApprove.textContent = busy ? 'Saving…' : SIGNOFF_APPROVE_LABEL;
4065
+ // The button is disabled during the write, so its changed label may not be announced. Keep a
4066
+ // separate live status on the dialog without disturbing the count/status above the list.
4067
+ signoffSaveStatus.textContent = busy ? 'Saving filter…' : '';
4068
+ if(busy) signoffApprove.setAttribute('aria-busy', 'true');
4069
+ else signoffApprove.removeAttribute('aria-busy');
4070
+ signoffApprove.replaceChildren();
4071
+ if(busy){
4072
+ // Reuse the ring shown while the dismissal count is calculated, so the same dialog has one
4073
+ // consistent working signal through preview and the potentially slower save transaction.
4074
+ const spinner = document.createElement('span');
4075
+ spinner.className = 'signoff-spinner'; spinner.setAttribute('aria-hidden', 'true');
4076
+ signoffApprove.append(spinner, document.createTextNode('Saving…'));
4077
+ } else signoffApprove.textContent = SIGNOFF_APPROVE_LABEL;
2550
4078
  }
2551
4079
 
2552
4080
  async function approveSignOff(){
@@ -2629,6 +4157,7 @@ async function saveNow(){
2629
4157
  // A second click while already conflicted must NOT silently re-fire a request we know will fail —
2630
4158
  // just re-surface the explanation.
2631
4159
  if(conflicted){ showChangedBanner(); return; }
4160
+ retireFilterAiUndo('Save filter was pressed, so Undo is no longer available.');
2632
4161
  saveInFlight = true;
2633
4162
  setFilterEditingLocked(true);
2634
4163
  setRequiredSaveCue(false, false);
@@ -2670,7 +4199,7 @@ async function saveNow(){
2670
4199
  if(res.status === 412){
2671
4200
  releaseMutation(mid);
2672
4201
  if(checkpointRequest && revisionRequest !== checkpointRequest){ setSaved(dirty ? 'dirty' : ''); return; }
2673
- conflicted = true;
4202
+ conflicted = true; notifyFilterAi();
2674
4203
  if(checkpointRequest){
2675
4204
  blockRequiredCheckpointSave('This Drawing Filter changed before the required save could finish. Reload the Drawing Filter, review the selections, and press Save filter again.');
2676
4205
  } else {
@@ -2738,7 +4267,7 @@ async function saveNow(){
2738
4267
  if(revisionRequest === checkpointRequest){
2739
4268
  signoffOutcome = code;
2740
4269
  dirty = false;
2741
- checkpointSaveBlocked = true;
4270
+ checkpointSaveBlocked = true; notifyFilterAi();
2742
4271
  setRequiredSaveCue(false, false);
2743
4272
  saveBtn.disabled = true;
2744
4273
  setSaved('signoff-blocked');
@@ -2833,6 +4362,22 @@ window.__filterTest = {
2833
4362
  sheetTriggerText: () => sheetTriggerLabel.textContent,
2834
4363
  sheetOptionTexts: () => sheetOptions().map(o => o.textContent),
2835
4364
  pick: (i) => { const el = nodes[i].el; openEyedropper(Math.round(window.innerWidth / 2), 200, el); return el; },
4365
+ // Hover info. The HOVER itself stays a real pointer event in the browser pass -- these read the
4366
+ // outcome, they do not drive it. `hotPathD` is the halo's own geometry rather than "a halo exists",
4367
+ // so a probe can prove it traces the element the readout is describing.
4368
+ hoverInfoOn: () => hoverBtn.getAttribute('aria-pressed') === 'true',
4369
+ hoverbarShown: () => !hoverbar.hidden,
4370
+ hoverReadout: () => ({
4371
+ layer: hbLayerPre.textContent + hbLayer.textContent,
4372
+ thickness: hbThick.textContent,
4373
+ color: hbColor.textContent,
4374
+ layerSwatch: hbLayerSw.style.background,
4375
+ colorSwatch: hbColorSw.style.background,
4376
+ }),
4377
+ hotPathD: () => { const n = hot.firstElementChild; return n ? n.getAttribute('d') : null; },
4378
+ hotTag: () => { const n = hot.firstElementChild; return n ? n.tagName : null; },
4379
+ hotRows: () => [...document.querySelectorAll('#panel .opts label.hot-row')].map(r => r.textContent.trim()),
4380
+ setHoverInfo: (on) => setHoverInfo(on),
2836
4381
  addAll: () => document.getElementById('eyeAddAll').click(),
2837
4382
  // Exclusion sign-off state, so a real browser pass can assert the control and the {dim, value} list
2838
4383
  // it SUBMITS, not only that a modal appeared. `signoffValues` is the submitted list itself — names