@floless/app 0.117.1 → 0.118.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.
@@ -12,8 +12,16 @@ Usage:
12
12
 
13
13
  python vision_to_contract.py vision-out.json sketch.png --out contract.json
14
14
  python vision_to_contract.py vision-out2.json page2.png --merge-into contract.json
15
+ python vision_to_contract.py vision-out.json scan.png --geometry cv.json --out contract.json
15
16
 
16
17
  --merge-into appends the extraction as the next sheet of an existing contract (multi-image sets).
18
+
19
+ --geometry takes the sheet's GEOMETRY from classify_and_trace.py instead of from the model, and
20
+ keeps only the model's TEXT. That is the measured split: on a real framing plan the model placed
21
+ geometry at centerline F1 0.008 against the sheet's own CAD data while the CV tracer scored 0.73,
22
+ and the model read the labels correctly where the CV tracer produces none at all. They fail in
23
+ opposite directions, so each keeps what it is good at. Without the flag this behaves exactly as
24
+ before.
17
25
  Requires PyMuPDF (used only to read the image/PDF pixel size).
18
26
  """
19
27
 
@@ -40,7 +48,52 @@ def unwrap(payload):
40
48
  return result["elements"], model
41
49
 
42
50
 
43
- def to_sheet(elements, image_path):
51
+ def load_cv_geometry(path, expect_w=None, expect_h=None):
52
+ """Geometry elements from classify_and_trace.py, already in the image's pixel frame.
53
+
54
+ The CV tracer measures the ink, so unlike the model it needs no 0..1000 remap. Text is
55
+ dropped if present -- this path exists precisely because the model owns text.
56
+ """
57
+ with open(path, encoding="utf-8") as f:
58
+ doc = json.load(f)
59
+ els = doc.get("elements")
60
+ if els is None and isinstance(doc.get("sheets"), list) and doc["sheets"]:
61
+ els = doc["sheets"][0].get("elements")
62
+ if not isinstance(els, list):
63
+ sys.exit(f"{path}: no elements[] — is this classify_and_trace.py output?")
64
+ # The tracer records the image it measured. If that is not the image being converted, the
65
+ # geometry lands in a different frame from the text and the page box, silently — trace a
66
+ # downsampled copy and hand over the original and everything still "works".
67
+ img = doc.get("image") or {}
68
+ if expect_w and img.get("w") and (int(img["w"]) != int(expect_w) or int(img["h"]) != int(expect_h)):
69
+ sys.exit(f"{path} was traced from a {img.get('w')}x{img.get('h')} image but the image "
70
+ f"given here is {expect_w}x{expect_h} — geometry and text would be in "
71
+ f"different frames. Trace and convert the SAME image.")
72
+ if doc.get("output_frame") not in (None, "original"):
73
+ sys.exit(f"{path}: output_frame is {doc['output_frame']!r}, not 'original' — the editor "
74
+ f"and the raster backdrop both use the original frame.")
75
+ out = []
76
+ for el in els:
77
+ if el.get("kind") == "text":
78
+ continue
79
+ e = {"kind": el["kind"]}
80
+ if el.get("d"):
81
+ e["d"] = el["d"]
82
+ elif el.get("pts"):
83
+ e["pts"] = [[round(float(p[0]), 1), round(float(p[1]), 1)] for p in el["pts"]]
84
+ else:
85
+ continue
86
+ out.append(e)
87
+ if not out:
88
+ # An empty trace with --geometry would emit a text-only contract still CLAIMING measured
89
+ # geometry, and the editor would tell the user the linework was measured from the ink
90
+ # over a drawing with no linework in it.
91
+ sys.exit(f"{path} contains no geometry — the trace found nothing. Re-run the tracer "
92
+ f"(try --ink-method otsu), or drop --geometry to use the vision-only path.")
93
+ return out, doc.get("method", "opencv/centerline")
94
+
95
+
96
+ def to_sheet(elements, image_path, geometry=None):
44
97
  # Images only: a multi-page PDF has no single 0..1000 frame, so the caller rasterizes each
45
98
  # PDF page to its own image first (SKILL.md step 3b) and runs one extraction per image.
46
99
  if image_path.lower().endswith(".pdf"):
@@ -50,10 +103,14 @@ def to_sheet(elements, image_path):
50
103
  w, h = float(pix.width), float(pix.height)
51
104
  sx, sy = w / 1000.0, h / 1000.0
52
105
 
53
- out = []
106
+ out = list(geometry or [])
54
107
  for el in elements:
55
108
  kind = el.get("kind")
56
109
  conf = el.get("confidence")
110
+ # With CV geometry in hand the model contributes TEXT ONLY. Letting its lines through
111
+ # as well would put two conflicting sets of coordinates in one contract.
112
+ if geometry is not None and kind != "text":
113
+ continue
57
114
  if kind == "text":
58
115
  bbox = el.get("bbox")
59
116
  if not el.get("text") or not bbox or len(bbox) != 4:
@@ -88,6 +145,73 @@ def to_sheet(elements, image_path):
88
145
  return {"page": {"w": round(w, 2), "h": round(h, 2)}, "elements": out}
89
146
 
90
147
 
148
+ def selftest():
149
+ """Pin the --geometry contract. Every case here is one a review found or asked for."""
150
+ import tempfile
151
+ tmp = tempfile.mkdtemp(prefix="v2c_")
152
+ fails = []
153
+
154
+ def check(name, cond, detail=""):
155
+ print(f" {'ok ' if cond else 'FAIL'} {name}" + ("" if cond else f" -> {detail}"))
156
+ if not cond:
157
+ fails.append(name)
158
+
159
+ # a 200x100 white PNG, written with PyMuPDF so no extra dependency is needed
160
+ img = os.path.join(tmp, "img.png")
161
+ pm = fitz.Pixmap(fitz.csRGB, fitz.IRect(0, 0, 200, 100), False)
162
+ pm.clear_with(255)
163
+ pm.save(img)
164
+
165
+ def write(name, obj):
166
+ q = os.path.join(tmp, name)
167
+ with open(q, "w", encoding="utf-8") as f:
168
+ json.dump(obj, f)
169
+ return q
170
+
171
+ cv_ok = write("cv.json", {"method": "opencv/centerline", "output_frame": "original",
172
+ "image": {"w": 200, "h": 100},
173
+ "elements": [{"kind": "line", "pts": [[0, 0], [100, 0]]},
174
+ {"kind": "arc", "d": "M0 0 A5 5 0 1 1 10 0"}]})
175
+ vis = write("vis.json", {"result": {"elements": [
176
+ {"kind": "text", "text": "BEAM", "bbox": [100, 100, 300, 200], "confidence": 0.9},
177
+ {"kind": "line", "pts": [[0, 0], [900, 900]]}]}, "model": "m1"})
178
+
179
+ geom, method = load_cv_geometry(cv_ok, 200, 100)
180
+ check("geometry loads from tracer output", len(geom) == 2 and method == "opencv/centerline",
181
+ (len(geom), method))
182
+ sheet = to_sheet([{"kind": "text", "text": "BEAM", "bbox": [100, 100, 300, 200]},
183
+ {"kind": "line", "pts": [[0, 0], [900, 900]]}], img, geom)
184
+ kinds = [e["kind"] for e in sheet["elements"]]
185
+ check("model GEOMETRY is dropped when --geometry is given",
186
+ kinds.count("line") == 1 and kinds.count("text") == 1, kinds)
187
+ check("ids are unique across the combined set",
188
+ len({e["id"] for e in sheet["elements"]}) == len(sheet["elements"]))
189
+ check("CV geometry is NOT rescaled (it is already in pixels)",
190
+ sheet["elements"][0]["pts"] == [[0.0, 0.0], [100.0, 0.0]], sheet["elements"][0])
191
+ check("model text IS rescaled from the 0..1000 frame",
192
+ sheet["elements"][2]["bbox"][0] == 20.0, sheet["elements"][2]["bbox"])
193
+
194
+ # a trace of a DIFFERENT image must be refused, not silently combined
195
+ bad_frame = write("bad.json", {"method": "opencv/centerline", "image": {"w": 400, "h": 200},
196
+ "elements": [{"kind": "line", "pts": [[0, 0], [1, 1]]}]})
197
+ try:
198
+ load_cv_geometry(bad_frame, 200, 100)
199
+ check("a trace of a different-sized image is refused", False, "no exit")
200
+ except SystemExit:
201
+ check("a trace of a different-sized image is refused", True)
202
+
203
+ empty = write("empty.json", {"method": "opencv/centerline", "image": {"w": 200, "h": 100},
204
+ "elements": []})
205
+ try:
206
+ load_cv_geometry(empty, 200, 100)
207
+ check("an EMPTY trace is refused, not shipped as text-only", False, "no exit")
208
+ except SystemExit:
209
+ check("an EMPTY trace is refused, not shipped as text-only", True)
210
+
211
+ print(f"\nselftest: {len(fails)} failure(s)")
212
+ return 1 if fails else 0
213
+
214
+
91
215
  def main():
92
216
  for stream in (sys.stdout, sys.stderr):
93
217
  try:
@@ -95,17 +219,40 @@ def main():
95
219
  except AttributeError:
96
220
  pass
97
221
  ap = argparse.ArgumentParser(description=__doc__)
98
- ap.add_argument("vision_json", help="output of `aware agent invoke vision extract --json`")
99
- ap.add_argument("image", help="the raster image the extraction ran on (rasterize PDF pages first)")
222
+ ap.add_argument("vision_json", nargs="?",
223
+ help="output of `aware agent invoke vision extract --json`; may be "
224
+ "OMITTED when --geometry is given, which emits measured geometry "
225
+ "with no text at all")
226
+ ap.add_argument("image", nargs="?",
227
+ help="the raster image the extraction ran on (rasterize PDF pages first)")
100
228
  ap.add_argument("--out", help="write a NEW one-sheet contract here")
101
229
  ap.add_argument("--merge-into", help="append as the next sheet of this existing contract")
230
+ ap.add_argument("--selftest", action="store_true")
231
+ ap.add_argument("--geometry", help="classify_and_trace.py output: take GEOMETRY from the "
232
+ "CV tracer and keep only the model's TEXT")
102
233
  args = ap.parse_args()
234
+ if args.selftest:
235
+ sys.exit(selftest())
236
+ if not args.image:
237
+ sys.exit("an image is required")
103
238
  if bool(args.out) == bool(args.merge_into):
104
239
  sys.exit("pass exactly one of --out / --merge-into")
105
240
 
106
- with open(args.vision_json, encoding="utf-8") as f:
107
- elements, model = unwrap(json.load(f))
108
- sheet = to_sheet(elements, args.image)
241
+ if not args.vision_json and not args.geometry:
242
+ sys.exit("pass a vision output, or --geometry for a measured-geometry-only contract")
243
+ if args.vision_json:
244
+ with open(args.vision_json, encoding="utf-8") as f:
245
+ elements, model = unwrap(json.load(f))
246
+ else:
247
+ # The geometry-only fallback: the tracer ran, the vision CLI/credential did not. The
248
+ # contract carries measured linework and NO text, and says so in `extractor` so the
249
+ # editor cannot imply a model was involved.
250
+ elements, model = [], None
251
+ geometry, cv_method = (None, None)
252
+ if args.geometry:
253
+ pix0 = fitz.Pixmap(args.image)
254
+ geometry, cv_method = load_cv_geometry(args.geometry, pix0.width, pix0.height)
255
+ sheet = to_sheet(elements, args.image, geometry)
109
256
  stem = os.path.splitext(os.path.basename(args.image))[0]
110
257
 
111
258
  if args.merge_into:
@@ -135,7 +282,13 @@ def main():
135
282
  "kind": "image",
136
283
  "sha256": digest,
137
284
  "read_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
138
- "extractor": f"vision.extract@{model}",
285
+ # The extractor string IS the provenance the editor reads to word its
286
+ # confidence note, so a hybrid must say so: geometry measured from the ink,
287
+ # text read by the model. Claiming either alone would be a false statement
288
+ # about how the drawing was read.
289
+ "extractor": (
290
+ (f"{cv_method}+vision.text@{model}" if model else f"{cv_method}")
291
+ if geometry is not None else f"vision.extract@{model}"),
139
292
  },
140
293
  "sheets": [sheet],
141
294
  }
@@ -144,7 +297,21 @@ def main():
144
297
  with open(path, "w", encoding="utf-8") as f:
145
298
  json.dump(contract, f, ensure_ascii=False)
146
299
  weak = sum(1 for e in sheet["elements"] if (e.get("confidence") or 1) < 0.5)
147
- print(f"{path}: sheet {sheet['id']} ({stem}), {len(sheet['elements'])} element(s), {weak} weak", file=sys.stderr)
300
+ # Geometry and text are counted SEPARATELY: one undifferentiated total let a contract with
301
+ # zero linework and a handful of labels read as a healthy result.
302
+ n_text = sum(1 for e in sheet["elements"] if e.get("kind") == "text")
303
+ n_geom = len(sheet["elements"]) - n_text
304
+ print(f"{path}: sheet {sheet['id']} ({stem}), {n_geom} geometry + {n_text} text "
305
+ f"element(s), {weak} weak", file=sys.stderr)
306
+ if args.merge_into and contract.get("source", {}).get("extractor") and geometry is not None:
307
+ # Provenance is top-level, so a multi-sheet job that used different paths per sheet can
308
+ # only carry one claim. Say so rather than let the first sheet speak for all of them.
309
+ prev = contract["source"]["extractor"]
310
+ now = (f"{cv_method}+vision.text@{model}" if model else cv_method)
311
+ if prev != now:
312
+ print(f" ! this sheet was read as {now!r} but the contract says {prev!r}; provenance "
313
+ f"is per-CONTRACT, so the editor will show one claim for every sheet.",
314
+ file=sys.stderr)
148
315
 
149
316
 
150
317
  if __name__ == "__main__":
@@ -2,7 +2,7 @@
2
2
  name: reading-structural-drawings
3
3
  description: This skill should be used BEFORE modelling anything from a structural/architectural drawing SET (PDF). Use it whenever turning drawings into a 3D frame, takeoff, IFC, or Tekla model — it is the prerequisite reading discipline for the `floless-app-steel-takeoff` reader (and the `floless-app-steel-model` guide that orchestrates the full flow). Triggers on "read this drawing set", "model this structure from the PDF", "take off this steel", "build a model from these drawings", or any pure-PDF → structure task. It encodes the method that stops the classic failures (missing that a set is TWO buildings, missing a curved/sloped roof, conflating grids across sheets, tracing dimension lines as members) — establish MASSING + COORDINATE FRAME first (from the index + elevations + sections), members LAST; deterministic geometry feeds the reasoning; cross-validate every view; verify before presenting.
4
4
  metadata:
5
- version: 0.2.1
5
+ version: 0.3.0
6
6
  ---
7
7
 
8
8
  # Reading a structural drawing set — the discipline (do this BEFORE you model anything)
@@ -255,8 +255,40 @@ any external count.
255
255
  A 2-point fit gives `real = A·pixel + b`. Check the grid is orthogonal / skewed / radial — don't
256
256
  assume 90°. **Each sheet may have its own origin/orientation — re-anchor per sheet; never carry one
257
257
  sheet's grid onto another** (this conflation is a top failure).
258
- - **Levels:** OCR the level/T.O.STEEL tags from an elevation/section into a datum table
259
- (L1 +0'-0", L2 +16'-6", Roof …). Members snap to these.
258
+ - **Levels — hunt down the T.O.S. callouts BEFORE assuming any level is flat.** Sweep everywhere they
259
+ hide: the framing plans themselves, the frame elevations, and **every section view** — a section is
260
+ often the only place a level is ever stated, so always open them if the set has any. OCR them into a
261
+ datum table (L1 +0'-0", L2 +16'-6", Roof …) and let members snap to it **only where the level really
262
+ is flat** — establish that, don't assume it.
263
+ - **A level reading `VARIES`/`SLOPES`, or carrying several different T.O.S. values, has NO single
264
+ elevation, and no default may be substituted for one.** Those callouts are **WORKING POINTS**: each
265
+ fixes top-of-steel at a known location, so every member framing at that point sits there, and the
266
+ level lies on the surface the points define. Derive it from the points:
267
+ 1. **Trace every leader to its real endpoint.** A T.O.S. leader commonly lands on a **column point**,
268
+ not on a beam — and a column is shared by two to four beams. Where those beams belong to one
269
+ continuous surface the callout fixes them all at once, which is what makes it powerful. It is not
270
+ a licence to propagate blindly: stepped framing, a dropped bay, secondary steel or two roof facets
271
+ meeting can put different elevations at one plan point. Propagate only to members shown to share
272
+ the surface, and stop at anything the drawing separates.
273
+ 2. **Let the points tell you the surface — never assume its shape.** Tabulate `(location → value)` and
274
+ test the candidates: flat; a function of ONE axis (a one-way slope, so callouts sharing that
275
+ coordinate must agree); a general plane varying in both (`z = ax + by + c`); several independent
276
+ surfaces (separate structures, or facets meeting at a ridge/valley); or stepped/warped/cambered,
277
+ which no single fit describes. **Quote the residuals** — a tight fit is evidence, a poor one means
278
+ your surface model is wrong, not that the drawing is.
279
+ 3. **Read every other member off that surface, and be honest about how.** Interpolating between two
280
+ callouts that bracket the member is sound. **Extrapolating past the outermost callout is not**:
281
+ allow it only within the same continuous facet, only for a short reach against the callout spacing
282
+ you fitted (a fraction of a bay, never a new one), and only when nothing suggests the surface
283
+ changes out there. Past that, the elevation is unresolved — **RFI it** rather than stretching the
284
+ plane. Record which values were derived rather than measured; a model format may not carry that
285
+ distinction for you, so the read log is usually the only place it survives.
286
+ 4. **A member running across the fall has a DIFFERENT elevation at each end.** Record both. Never
287
+ collapse a sloping member to one number, and never average it.
288
+
289
+ If the points do not determine the surface, say so and **RFI it** — inventing a level is exactly the
290
+ failure this pass exists to prevent. Expect the slope to be stated ONLY by these point elevations:
291
+ there is often no slope arrow, no `SLOPE` text and no note anywhere in the set.
260
292
 
261
293
  ### Pass 3 — MEMBERS (now, and only now), per building, per level
262
294
  - Tile big sheets: **always include a low-DPI full-sheet overview alongside overlapping high-DPI
@@ -2,7 +2,7 @@
2
2
  name: steel-drawing-abbreviations
3
3
  description: Default legend of standard US (AISC, imperial) structural-steel drawing abbreviations, note conventions, and shape designations — the fallback meaning when a drawing set omits or only partially supplies its own abbreviations/legend sheet. This skill should be used while reading a structural steel drawing whenever an abbreviation, note code, or profile designation needs expanding (TYP, TOS, UON, EQ, (E)/(N), SIM, HSS, WT, and so on), or when the steel reader (floless-app-steel-takeoff / floless-app-steel-model) meets a note or label whose meaning is not defined on the supplied sheets. The project's own legend always overrides these defaults.
4
4
  metadata:
5
- version: "0.2.1"
5
+ version: "0.3.0"
6
6
  ---
7
7
 
8
8
  # Steel drawing abbreviations — default legend
@@ -270,7 +270,11 @@ When reading the General Notes and plan notes, these drive member geometry/metad
270
270
  - **`TYP`** — a value/detail shown once applies to all like conditions. A "TYP" profile or spacing in
271
271
  the notes is the **default** for unlabeled members of that kind.
272
272
  - **`TOS` / `TOC` / `TOF` / `BOS`** — top/bottom-of-steel/concrete/footing elevations. A plan default
273
- TOS ("ALL STEEL T.O.S. = 16'-6" UON") sets every member's elevation unless a local callout overrides.
273
+ TOS ("ALL STEEL T.O.S. = 16'-6" UON") sets every member's elevation unless a local callout overrides —
274
+ **but that order only holds for a level that is genuinely FLAT.** Where the level varies (`VARIES`,
275
+ `SLOPES`, or simply several different T.O.S. values on the sheet), the individual callouts are not
276
+ exceptions to the note: they are **working points** that define the surface. Collect them ALL and fit
277
+ the surface FIRST, before reaching for any default — see `reading-structural-drawings`.
274
278
  - **`UON` / `UNO`** — the stated value holds everywhere *unless* a local note says otherwise. Treat a
275
279
  "TYP … UON" note as the fallback and watch for the exceptions.
276
280
  - **`EQ`** — equally-spaced members between two references (no explicit dimension).
package/dist/web/app.css CHANGED
@@ -161,6 +161,12 @@
161
161
  background-repeat: no-repeat;
162
162
  background-position: right 10px center;
163
163
  }
164
+ /* A <select> upgraded by themeSelect() (app.js) is no longer a rendered control — it is the
165
+ value model behind a .sel-combo, and it is hidden because the styling above can only reach
166
+ its CLOSED state. Its OPEN option list is drawn by the OS and cannot be themed at all, which
167
+ is the whole reason the combobox exists (same call steel-editor.html and steel-filter.html
168
+ already made). Leaving it visible would show two controls for one value. */
169
+ select.sel-native { display: none; }
164
170
  select:hover, button:hover { border-color: var(--accent-dim); }
165
171
  /* Keyboard focus ring (the global outline:none above kills it for mouse users;
166
172
  restore it for keyboard nav across every control, incl. JS-built buttons). */
@@ -2074,14 +2080,20 @@
2074
2080
 
2075
2081
  /* Add/edit form */
2076
2082
  .modal.routine-edit { width: 540px; max-width: 92vw; max-height: 90vh; overflow-y: auto; }
2077
- #rtn-workflow, .rtn-kind-select { min-width: 0; width: 100%; }
2078
2083
  .rtn-days { display: flex; flex-wrap: wrap; gap: 5px; }
2079
2084
  .rtn-day { text-transform: capitalize; }
2080
- /* Time picker: two app-styled selects (replaces the native time input so it
2081
- matches the dark baseline instead of the OS picker). */
2082
- .rtn-time { display: flex; align-items: center; gap: 8px; }
2083
- .rtn-time select { min-width: 0; width: auto; flex: 0 0 auto; }
2084
- .rtn-time-sep { color: var(--text-dim); font-family: var(--mono); }
2085
+ /* Time picker: two themed comboboxes, sized to their content (00–23 / 00–59) rather than
2086
+ stretched across the field like the full-width ones above. Replaces the native time input,
2087
+ which draws the OS picker. */
2088
+ .rtn-time { display: flex; align-items: flex-start; gap: 8px; }
2089
+ .rtn-time .sel-combo { width: auto; flex: 0 0 auto; }
2090
+ .rtn-time .sel-combo .wf-trigger { width: auto; min-width: 74px; }
2091
+ /* The hour/minute popovers sit side by side; keep each one over its own trigger rather than
2092
+ letting the in-line flow push the second one down a row. */
2093
+ .rtn-time .sel-combo .fm-select-popover { min-width: 100%; }
2094
+ /* flex-start above (an open popover flows in-line and makes its column tall); the padding
2095
+ keeps the ":" on the triggers' text line instead of riding the top edge. */
2096
+ .rtn-time-sep { color: var(--text-dim); font-family: var(--mono); padding: 8px 0; }
2085
2097
  #rtn-cron { font-family: var(--mono); letter-spacing: 0.02em; }
2086
2098
  .rtn-cron-hint { margin-top: 7px; font-size: 10.5px; color: var(--text-dim); line-height: 1.55; }
2087
2099
  .rtn-cron-hint code { font-family: var(--mono); color: var(--text-muted); background: var(--surface-2); padding: 0 3px; border-radius: 3px; }
package/dist/web/app.js CHANGED
@@ -1597,6 +1597,249 @@ document.addEventListener('keydown', (e) => {
1597
1597
  }
1598
1598
  });
1599
1599
 
1600
+ /* ============= THEMED SELECT ============= */
1601
+ // CLAUDE.md, "Style EVERY control, including the secondary/native ones": `<select>`
1602
+ // dropdowns must be the themed combobox, never the native control. The `select { appearance:
1603
+ // none }` rule in app.css de-nativizes the CLOSED state only — the OPEN option list is drawn
1604
+ // by the OS and comes back white against the dark baseline, which is exactly why
1605
+ // steel-editor.html (plan switcher) and steel-filter.html (sheet switcher) each dropped their
1606
+ // <select> for a hand-rolled combobox. The Routines editor was the straggler: six native
1607
+ // selects (workflow, schedule kind, every-N-minutes, every-N-hours, hour, minute), every one
1608
+ // of them opening a light OS popup on a dark modal.
1609
+ //
1610
+ // This is the same move, done as an in-place UPGRADE rather than a rewrite. The <select> stays
1611
+ // in the DOM and stays the single source of truth: `.value` reads/writes, `.innerHTML` option
1612
+ // rebuilds, `.disabled` toggles, `data-tip` and `change` listeners all keep working untouched
1613
+ // (aware.js does all six of those to these controls). It is only made invisible, with a
1614
+ // .wf-combo trigger + popover — the SAME markup and classes the workflow picker and the
1615
+ // form-modal pickers already render — drawn in its place and kept in sync.
1616
+ //
1617
+ // Sync is not left to a call site remembering to ask for it: the option list and the
1618
+ // disabled/data-tip attributes are observed, and the instance's `value` setter is wrapped, so
1619
+ // there is no way to change the select and leave the combo showing something stale.
1620
+ const SELECT_COMBO_SEARCH_MIN = 12; // a search box earns its place only once the list outgrows a scan
1621
+ function themeSelect(sel) {
1622
+ if (!sel || sel.dataset.combo) return;
1623
+ sel.dataset.combo = '1';
1624
+
1625
+ const box = document.createElement('div');
1626
+ // fm-select: the modal-field variant, whose popover flows IN-LINE (position:static). The
1627
+ // routines modal is itself a scroll container (.modal.routine-edit is overflow-y:auto), and
1628
+ // an absolutely-positioned popover inside one gets clipped — the reason fm-select exists.
1629
+ box.className = 'wf-combo fm-select sel-combo';
1630
+ const trigger = document.createElement('button');
1631
+ trigger.type = 'button';
1632
+ trigger.className = 'wf-trigger fm-select-trigger';
1633
+ trigger.id = (sel.id || 'sel') + '-combo-trigger';
1634
+ trigger.setAttribute('aria-haspopup', 'listbox');
1635
+ trigger.setAttribute('aria-expanded', 'false');
1636
+ const label = document.createElement('span');
1637
+ label.className = 'wf-trigger-label fm-select-label';
1638
+ trigger.appendChild(label);
1639
+ trigger.insertAdjacentHTML('beforeend',
1640
+ '<svg class="wf-caret" width="10" height="6" viewBox="0 0 10 6" aria-hidden="true"><path fill="currentColor" d="M0 0l5 6 5-6z"/></svg>');
1641
+ const popover = document.createElement('div');
1642
+ popover.className = 'wf-popover fm-select-popover';
1643
+ popover.setAttribute('role', 'listbox');
1644
+ popover.hidden = true;
1645
+ const searchWrap = document.createElement('div');
1646
+ searchWrap.className = 'wf-search-wrap';
1647
+ searchWrap.hidden = true;
1648
+ const search = document.createElement('input');
1649
+ search.type = 'text';
1650
+ search.className = 'wf-search fm-select-search';
1651
+ search.placeholder = 'Search…';
1652
+ search.autocomplete = 'off';
1653
+ search.setAttribute('aria-label', 'Search');
1654
+ searchWrap.appendChild(search);
1655
+ const list = document.createElement('div');
1656
+ list.className = 'wf-list fm-select-list';
1657
+ const empty = document.createElement('div');
1658
+ empty.className = 'wf-empty-search';
1659
+ empty.textContent = 'No matches';
1660
+ empty.hidden = true;
1661
+ popover.append(searchWrap, list, empty);
1662
+ box.append(trigger, popover);
1663
+ sel.classList.add('sel-native'); // display:none — the value model, not a rendered control
1664
+ sel.setAttribute('aria-hidden', 'true');
1665
+ sel.tabIndex = -1;
1666
+ sel.after(box);
1667
+
1668
+ // Accessible name. The field's own <label for=…> now points at a hidden element, so it is
1669
+ // re-pointed at the trigger and read together WITH the trigger's text (which is the current
1670
+ // value) — the pairing a native select gives for free. A select carrying its own aria-label
1671
+ // (the hour/minute pair) hands that over instead.
1672
+ const field = document.querySelector(`label[for="${CSS.escape(sel.id || '')}"]`);
1673
+ const ownLabel = sel.getAttribute('aria-label');
1674
+ if (ownLabel) {
1675
+ trigger.setAttribute('aria-label', ownLabel);
1676
+ popover.setAttribute('aria-label', ownLabel);
1677
+ } else if (field) {
1678
+ if (!field.id) field.id = (sel.id || 'sel') + '-combo-label';
1679
+ trigger.setAttribute('aria-labelledby', `${field.id} ${trigger.id}`);
1680
+ popover.setAttribute('aria-label', field.textContent.trim());
1681
+ // A label whose `for` target is display:none is inert on click; keep the click target.
1682
+ field.addEventListener('click', (e) => { e.preventDefault(); trigger.focus(); });
1683
+ }
1684
+
1685
+ let hi = -1;
1686
+ const rows = () => [...list.children];
1687
+ const visible = () => rows().filter((r) => !r.hidden);
1688
+ const clearHi = () => { rows().forEach((r) => r.classList.remove('highlighted')); hi = -1; };
1689
+
1690
+ function render() {
1691
+ const opts = [...sel.options];
1692
+ const at = sel.selectedIndex;
1693
+ label.textContent = at >= 0 ? opts[at].textContent : (sel.dataset.placeholder || 'Select…');
1694
+ label.toggleAttribute('data-empty', at < 0);
1695
+ list.replaceChildren(...opts.map((o, i) => {
1696
+ const row = document.createElement('div');
1697
+ row.className = 'wf-option' + (i === at ? ' selected' : '');
1698
+ row.setAttribute('role', 'option');
1699
+ row.setAttribute('aria-selected', i === at ? 'true' : 'false');
1700
+ row.dataset.index = String(i);
1701
+ row.dataset.search = o.textContent.toLowerCase();
1702
+ row.tabIndex = -1;
1703
+ if (o.disabled) row.setAttribute('aria-disabled', 'true');
1704
+ const name = document.createElement('span');
1705
+ name.className = 'wf-option-name';
1706
+ name.textContent = o.textContent; // textContent, not innerHTML — option text is server data
1707
+ row.appendChild(name);
1708
+ return row;
1709
+ }));
1710
+ searchWrap.hidden = opts.length <= SELECT_COMBO_SEARCH_MIN;
1711
+ empty.hidden = true;
1712
+ trigger.disabled = sel.disabled;
1713
+ // data-tip lives on the select in the markup/callers; the hidden element can never be
1714
+ // hovered, so the tip has to ride the control the user actually points at.
1715
+ const tip = sel.getAttribute('data-tip');
1716
+ if (tip) trigger.setAttribute('data-tip', tip); else trigger.removeAttribute('data-tip');
1717
+ clearHi();
1718
+ }
1719
+
1720
+ const filter = (q) => {
1721
+ q = (q || '').toLowerCase().trim();
1722
+ let any = false;
1723
+ rows().forEach((r) => { const m = !q || r.dataset.search.includes(q); r.hidden = !m; if (m) any = true; });
1724
+ empty.hidden = any;
1725
+ clearHi();
1726
+ };
1727
+ const open = () => {
1728
+ if (trigger.disabled) return;
1729
+ closeOtherCombos(box);
1730
+ popover.hidden = false;
1731
+ trigger.classList.add('open');
1732
+ trigger.setAttribute('aria-expanded', 'true');
1733
+ // The highlight belongs to ONE open session and must not survive into the next. close() clears
1734
+ // it, but closeOtherCombos() only hides the DOM — so a combo dismissed by an outside click kept
1735
+ // `hi` pointing at whatever the arrows had reached. Reopening then armed it: the trigger's
1736
+ // keydown opened the popover and the SAME Enter bubbled on to select that stale row, so one
1737
+ // keypress on a closed control silently changed the schedule from Every day to Specific days.
1738
+ // Reproduced in Chromium before this line existed. Clearing on open() fixes it wherever the
1739
+ // close came from, which is why it is here and not in closeOtherCombos().
1740
+ clearHi();
1741
+ if (!searchWrap.hidden) { search.value = ''; filter(''); setTimeout(() => search.focus(), 0); }
1742
+ const sel0 = list.querySelector('.wf-option.selected');
1743
+ if (sel0) sel0.scrollIntoView({ block: 'nearest' });
1744
+ };
1745
+ const close = (focusTrigger) => {
1746
+ popover.hidden = true;
1747
+ trigger.classList.remove('open');
1748
+ trigger.setAttribute('aria-expanded', 'false');
1749
+ clearHi();
1750
+ if (focusTrigger) trigger.focus();
1751
+ };
1752
+ const move = (d) => {
1753
+ const vis = visible();
1754
+ if (!vis.length) return;
1755
+ hi = hi < 0 ? (d > 0 ? 0 : vis.length - 1) : Math.max(0, Math.min(vis.length - 1, hi + d));
1756
+ vis.forEach((r, i) => r.classList.toggle('highlighted', i === hi));
1757
+ vis[hi].scrollIntoView({ block: 'nearest' });
1758
+ };
1759
+ const choose = (row) => {
1760
+ const i = Number(row.dataset.index);
1761
+ const changed = i !== sel.selectedIndex;
1762
+ if (changed) {
1763
+ sel.selectedIndex = i;
1764
+ render();
1765
+ // bubbles: the routines wiring uses .onchange, and a caller may yet delegate.
1766
+ sel.dispatchEvent(new Event('change', { bubbles: true }));
1767
+ }
1768
+ close(true);
1769
+ };
1770
+
1771
+ trigger.addEventListener('click', (e) => { e.stopPropagation(); popover.hidden ? open() : close(false); });
1772
+ trigger.addEventListener('keydown', (e) => {
1773
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(); }
1774
+ });
1775
+ list.addEventListener('click', (e) => {
1776
+ const row = e.target.closest('.wf-option');
1777
+ if (row && !row.hasAttribute('aria-disabled')) { e.stopPropagation(); choose(row); }
1778
+ });
1779
+ search.addEventListener('input', () => filter(search.value));
1780
+ // Keep combo keys inside the combo. Escape especially: the document-level Escape handler
1781
+ // closes the whole routines modal, which would throw away the form to dismiss a dropdown.
1782
+ box.addEventListener('keydown', (e) => {
1783
+ if (popover.hidden) return;
1784
+ if (e.key === 'ArrowDown') { e.preventDefault(); e.stopPropagation(); move(1); }
1785
+ else if (e.key === 'ArrowUp') { e.preventDefault(); e.stopPropagation(); move(-1); }
1786
+ else if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); const vis = visible(); if (hi >= 0 && vis[hi]) choose(vis[hi]); }
1787
+ else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(true); }
1788
+ });
1789
+
1790
+ // Option-list rebuilds (`$wf.innerHTML = …`, fillTimeSelects) and disabled/data-tip flips
1791
+ // reach the DOM, so they are observed rather than announced.
1792
+ new MutationObserver(render).observe(sel, {
1793
+ childList: true, subtree: true, attributes: true, attributeFilter: ['disabled', 'data-tip'],
1794
+ });
1795
+ // `select.value = x` sets an IDL property and produces no mutation record, so the setter is
1796
+ // wrapped on this instance. Without it, openRoutineEdit()'s five value writes would leave
1797
+ // every trigger reading whatever the previous routine said.
1798
+ const native = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value');
1799
+ Object.defineProperty(sel, 'value', {
1800
+ configurable: true,
1801
+ get() { return native.get.call(this); },
1802
+ set(v) { native.set.call(this, v); render(); },
1803
+ });
1804
+ // Backstop for the selection writes neither of the two above can see: `selectedIndex = i`,
1805
+ // `option.selected = true` and `form.reset()` set IDL state that emits no mutation record and does
1806
+ // not pass through the `value` setter. No call site in web/ does any of those today — the only
1807
+ // `selectedIndex =` in the tree is choose()'s own, which renders explicitly — so this closes a
1808
+ // latent gap rather than a live bug, and it is one line instead of routing every mutation through
1809
+ // a new API. It catches anything that follows the conventional mutate-then-dispatch pattern;
1810
+ // a mutation with NO change event still would not repaint, which is stated rather than implied.
1811
+ // render() is idempotent, so the extra pass after choose()'s explicit one costs nothing.
1812
+ sel.addEventListener('change', render);
1813
+
1814
+ render();
1815
+ }
1816
+ // Only one popover open at a time, and a click OUTSIDE every combo dismisses them all.
1817
+ // `keep` is the one combo left alone — the one being opened, or the one a click landed inside.
1818
+ function closeOtherCombos(keep) {
1819
+ document.querySelectorAll('.sel-combo').forEach((other) => {
1820
+ if (other === keep) return;
1821
+ const pop = other.querySelector('.fm-select-popover');
1822
+ if (!pop || pop.hidden) return;
1823
+ pop.hidden = true;
1824
+ const t = other.querySelector('.fm-select-trigger');
1825
+ if (t) { t.classList.remove('open'); t.setAttribute('aria-expanded', 'false'); }
1826
+ });
1827
+ }
1828
+ function initThemedSelects() {
1829
+ document.querySelectorAll('select:not([hidden])').forEach(themeSelect);
1830
+ // Resolve the combo the click landed IN and keep that one open. The earlier
1831
+ // `closeOtherCombos(null)` relied on every in-combo click calling stopPropagation — which the
1832
+ // trigger and the option rows do, but the SEARCH BOX does not. So clicking into the search
1833
+ // field of the hour/minute pickers (the only lists past SELECT_COMBO_SEARCH_MIN, hence the only
1834
+ // ones that have a search box) closed the very popover being clicked into and dropped focus to
1835
+ // <body>: the field was unreachable by mouse. Asking the event where it landed fixes that
1836
+ // without weakening "click outside dismisses", and no longer depends on every inner control
1837
+ // remembering to stop the event.
1838
+ document.addEventListener('click', (e) => {
1839
+ closeOtherCombos(e.target instanceof Element ? e.target.closest('.sel-combo') : null);
1840
+ });
1841
+ }
1842
+
1600
1843
  /* ============= TOOLTIPS ============= */
1601
1844
  // App-styled tooltips for any [data-tip] element — one reused box, event-delegated
1602
1845
  // (so JS-generated cards/chips/buttons get them for free), shown on hover AND
@@ -1670,6 +1913,7 @@ document.addEventListener('keydown', (e) => {
1670
1913
  /* ============= INIT ============= */
1671
1914
  loadState();
1672
1915
  initTheme();
1916
+ initThemedSelects();
1673
1917
  loadWidths();
1674
1918
  applyCollapse();
1675
1919
  setupResize();
@@ -335,9 +335,9 @@ export function snapPoint(dragged, candidates, toScreen, tolPx) {
335
335
  }
336
336
 
337
337
  /** An intersection is worth this many px of aim against a line when choosing BETWEEN grid levels. */
338
- export const GRID_INT_HEADSTART_PX = 3;
338
+ const GRID_INT_HEADSTART_PX = 3;
339
339
  /** Scores this close are "the same pixel" — the levels are stacked, so distance can't choose. */
340
- export const GRID_LEVEL_TIE_PX = 0.5;
340
+ const GRID_LEVEL_TIE_PX = 0.5;
341
341
 
342
342
  /**
343
343
  * Choose which grid LEVEL a snap lands on. A structural grid is drawn at every visible Z datum, so the
@@ -555,7 +555,7 @@ export function offsetsFor(v, st, vA) {
555
555
 
556
556
  // UCS Stage 5 — one shared unit-direction rule for a frame-aware dim's world axisDir.
557
557
  // Below EPS a vector is degenerate (no direction); above UNIT_TOL from 1 it's non-unit and gets re-normalized.
558
- export const AXDIR_EPS = 1e-9, AXDIR_UNIT_TOL = 1e-6;
558
+ const AXDIR_EPS = 1e-9, AXDIR_UNIT_TOL = 1e-6;
559
559
  /**
560
560
  * Normalize a candidate world direction, or return null when it carries no usable direction.
561
561
  * null unless v is [finite, finite, finite] with a FINITE magnitude > AXDIR_EPS. Math.hypot can