constructelligence commited on
Commit
98410e9
·
verified ·
1 Parent(s): 176941f

Data Centre Nameplates — static demo

Browse files
Files changed (8) hide show
  1. README.md +38 -4
  2. index.html +208 -17
  3. nameplate-model.js +399 -0
  4. nameplates-app.js +672 -0
  5. og-nameplates.png +0 -0
  6. progress-project.js +535 -0
  7. schedule-import.js +195 -0
  8. style.css +1864 -18
README.md CHANGED
@@ -1,10 +1,44 @@
1
  ---
2
  title: Data Centre Nameplates
3
- emoji: 🐢
4
- colorFrom: pink
5
- colorTo: blue
6
  sdk: static
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Data Centre Nameplates
3
+ emoji: 🔌
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: static
7
  pinned: false
8
+ license: apache-2.0
9
+ short_description: Nameplate OCR checked against the equipment schedule
10
  ---
11
 
12
+ # Data Centre Nameplates
13
+
14
+ **Read an equipment nameplate and know if it is the unit the schedule asked for.**
15
+
16
+ Photograph the nameplate of a UPS, PDU, switchgear, generator, transformer, busway, battery, CRAH or chiller. This
17
+ runs OCR in your browser, pulls out the plate's fields — manufacturer, model, serial, voltage, phase, Hz, kVA, kW,
18
+ amps, MCA, MOCP, refrigerant, manufacture date — and **checks each one against the equipment schedule**, flagging
19
+ a mismatch instead of a silent pass. It builds an asset register and exports it to CSV.
20
+
21
+ Nothing is uploaded: the photo and the schedule stay on your device.
22
+
23
+ ## Try it
24
+
25
+ 1. Drop an equipment schedule as CSV (or click **Use sample schedule**).
26
+ 2. Drop a nameplate photo (or click **Try a sample nameplate**).
27
+ 3. Click **Read nameplate** and check the verdict, field by field, against the plate.
28
+
29
+ ## How it works
30
+
31
+ - **OCR** — `tesseract.js@5` (English LSTM), loaded from a CDN, plus an error model for the way OCR misreads plate
32
+ lettering (serifed `V`→`Vv`, `K`→`X` in `KVA`, `HZ`→`Hw`, codes split after their punctuation).
33
+ - **Extraction** — labelled-field parsing of `MODEL`, `S/N`, `MVA`, `MCA`, `MOCP`, `FLA`, `VOLTS`, `REFRIGERANT`,
34
+ `MFG DATE`, with voltages read as `480Y/277`, `13.8 kV` or `208/120`.
35
+ - **Matching** — model and serial codes compared with `O/0`, `I/L/1`, `S/5`, `B/8`, `Z/2` folded, so a misread is
36
+ not a false mismatch while a genuine voltage variant still fails.
37
+
38
+ ## Links
39
+
40
+ - **Model card and code** — [constructelligence/data-centre-nameplates](https://huggingface.co/constructelligence/data-centre-nameplates)
41
+ - **Constructelligence** — [huggingface.co/constructelligence](https://huggingface.co/constructelligence) · [constructelligence.co](https://constructelligence.co)
42
+
43
+ > A prompt to look, not a finding. Not safety-rated, not a compliance decision, and not a substitute for
44
+ > inspection by a competent person.
index.html CHANGED
@@ -1,19 +1,210 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Data Centre Nameplates — read &amp; verify equipment nameplates</title>
7
+ <meta name="description" content="Photograph an equipment nameplate and read it in your browser: model, serial, voltage and rating checked against your equipment schedule, with an asset register CSV. Nothing is uploaded." />
8
+ <meta name="robots" content="index, follow" />
9
+ <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22><rect width=%2224%22 height=%2224%22 rx=%225%22 fill=%22%230f2547%22/><rect x=%225%22 y=%227%22 width=%2214%22 height=%2210%22 rx=%221.5%22 fill=%22none%22 stroke=%22white%22 stroke-width=%221.8%22/><path d=%22M8 11h8M8 14h5%22 stroke=%22white%22 stroke-width=%221.6%22/></svg>" />
10
+ <meta name="theme-color" content="#0f2547" />
11
+ <meta name="author" content="Constructelligence" />
12
+ <meta name="keywords" content="nameplate OCR, equipment nameplate reader, data centre nameplate, data center commissioning, UPS nameplate, PDU nameplate, switchgear, generator nameplate, transformer nameplate, equipment schedule verification, asset register, CRAH, chiller, MEP commissioning, browser OCR, BuildVision" />
13
+
14
+ <meta property="og:type" content="website" />
15
+ <meta property="og:site_name" content="BuildVision" />
16
+ <meta property="og:title" content="Nameplates — read &amp; verify equipment nameplates in the browser" />
17
+ <meta property="og:description" content="Photograph a data centre equipment nameplate and read it in your browser: model, serial, voltage and rating checked against your equipment schedule, with an asset register CSV. Nothing is uploaded." />
18
+ <meta property="og:image" content="og-nameplates.png" />
19
+ <meta property="og:image:width" content="1200" />
20
+ <meta property="og:image:height" content="630" />
21
+ <meta property="og:image:alt" content="BuildVision Nameplates — read and verify data centre equipment nameplates against the equipment schedule" />
22
+ <meta name="twitter:card" content="summary_large_image" />
23
+ <meta name="twitter:title" content="Nameplates — read &amp; verify equipment nameplates in the browser" />
24
+ <meta name="twitter:description" content="Photograph a UPS, PDU, switchgear or chiller nameplate and check model, serial, voltage and rating against the equipment schedule. Runs in your browser; nothing is uploaded." />
25
+ <meta name="twitter:image" content="og-nameplates.png" />
26
+ <meta name="twitter:image:alt" content="BuildVision Nameplates — equipment-nameplate OCR checked against the equipment schedule" />
27
+
28
+ <script type="application/ld+json">
29
+ {
30
+ "@context": "https://schema.org",
31
+ "@type": "WebApplication",
32
+ "name": "BuildVision Nameplates",
33
+ "description": "Browser tool that reads an equipment nameplate (UPS, PDU, switchgear, generator, transformer, battery, CRAH, chiller) with in-browser OCR and checks model, serial, voltage, phase, Hz, kVA, kW, amps, MCA, MOCP and refrigerant against the equipment schedule, then exports an asset register CSV. Photos never leave the device.",
34
+ "applicationCategory": "BusinessApplication",
35
+ "operatingSystem": "Any (runs in a modern web browser)",
36
+ "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },
37
+ "featureList": [
38
+ "On-device nameplate OCR (nothing uploaded)",
39
+ "13 equipment types: UPS, generator, ATS, switchgear, transformer, PDU, panelboard, busway, battery, CDU, chiller, CRAH/CRAC, pump",
40
+ "Field-by-field check against the equipment schedule",
41
+ "Flags wrong voltage, rating or model instead of a silent pass",
42
+ "Asset register with duplicate-serial and missing-tag detection, exported as CSV"
43
+ ]
44
+ }
45
+ </script>
46
+ <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
47
+ <link rel="stylesheet" href="style.css" />
48
+ <style>
49
+ body { min-height: 100%; }
50
+ .np-wrap { display: grid; grid-template-columns: 320px minmax(0, 1fr); flex: 1; min-height: 0; }
51
+ .np-side { border-right: 1px solid var(--border); padding: 18px 18px 28px; display: flex; flex-direction: column; gap: 18px; background: var(--bg-panel-2); overflow-y: auto; }
52
+ .np-side h2, .np-main h2 { font-size: 0.78rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--text-dim); margin: 0 0 8px; }
53
+ .np-side p, .np-note { font-size: 0.82rem; color: var(--text-dim); line-height: 1.45; margin: 0; }
54
+ .np-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
55
+ .np-btn { border: 1px solid var(--border); background: var(--bg); color: var(--text); padding: 8px 12px; border-radius: var(--radius-sm); font-weight: 600; font-size: 0.84rem; cursor: pointer; }
56
+ .np-btn:hover { border-color: var(--accent); }
57
+ .np-btn.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
58
+ .np-btn.primary:hover { background: var(--accent-hover); }
59
+ .np-btn:disabled { opacity: 0.5; cursor: default; }
60
+ .np-btn.link { border: none; background: none; padding: 4px 6px; color: var(--text-dim); font-weight: 500; }
61
+ .np-drop { display: block; border: 1.5px dashed var(--border); border-radius: var(--radius); padding: 16px; text-align: center; font-size: 0.84rem; color: var(--text-dim); background: var(--bg); cursor: pointer; }
62
+ .np-drop.over { border-color: var(--accent); background: var(--accent-soft); }
63
+ .np-status { font-size: 0.82rem; min-height: 1.2em; color: var(--text-dim); }
64
+ .np-status.err { color: var(--danger); }
65
+ .np-bar { height: 4px; background: var(--border); border-radius: 2px; overflow: hidden; }
66
+ .np-bar > i { display: block; height: 100%; width: 0; background: var(--accent); transition: width 0.15s; }
67
+ .np-main { display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow-y: auto; }
68
+ .np-top { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(300px, 1fr); border-bottom: 1px solid var(--border); }
69
+ .np-stage { position: relative; min-height: 340px; background: var(--bg-subtle); display: grid; place-items: center; padding: 12px; }
70
+ .np-stage canvas { max-width: 100%; max-height: 62vh; height: auto; display: block; border-radius: var(--radius-sm); }
71
+ .np-empty { text-align: center; color: var(--text-dim); font-size: 0.9rem; padding: 24px; }
72
+ .np-reading { padding: 16px 18px 20px; border-left: 1px solid var(--border); display: flex; flex-direction: column; gap: 12px; }
73
+ .np-fields { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 6px 10px; align-items: center; font-size: 0.84rem; }
74
+ .np-fields label { color: var(--text-dim); font-weight: 600; white-space: nowrap; display: flex; align-items: center; gap: 6px; }
75
+ .np-fields input, .np-fields select, .np-tag select { width: 100%; padding: 6px 8px; border: 1px solid var(--border); border-radius: var(--radius-sm); font-size: 16px; background: var(--bg); color: var(--text); min-width: 0; }
76
+ .np-fields input.low { border-color: var(--warning, #c98a00); background: color-mix(in srgb, var(--warning, #c98a00) 8%, var(--bg)); }
77
+ .np-key { display: inline-block; width: 9px; height: 9px; border-radius: 2px; flex: none; }
78
+ .np-tag { display: flex; flex-direction: column; gap: 6px; font-size: 0.84rem; font-weight: 600; }
79
+ .np-checks { list-style: none; margin: 0; padding: 0; font-size: 0.84rem; display: flex; flex-direction: column; gap: 4px; }
80
+ .np-checks li { display: flex; gap: 8px; align-items: baseline; }
81
+ .np-checks .ok { color: var(--success, #1f8a4c); }
82
+ .np-checks .mismatch { color: var(--danger); font-weight: 600; }
83
+ .np-checks .unread { color: var(--text-dim); }
84
+ .np-verdict { padding: 8px 10px; border-radius: var(--radius-sm); font-size: 0.86rem; font-weight: 600; }
85
+ .np-verdict.verified { background: color-mix(in srgb, var(--success, #1f8a4c) 12%, transparent); color: var(--success, #1f8a4c); }
86
+ .np-verdict.mismatch { background: color-mix(in srgb, var(--danger) 12%, transparent); color: var(--danger); }
87
+ .np-verdict.partial, .np-verdict.unmatched { background: var(--bg-subtle); color: var(--text); }
88
+ .np-register { padding: 14px 18px 24px; }
89
+ .np-summary { display: flex; gap: 18px; flex-wrap: wrap; margin-bottom: 10px; font-size: 0.86rem; }
90
+ .np-summary b { font-size: 1.05rem; }
91
+ table.np-table { border-collapse: collapse; width: 100%; font-size: 0.82rem; }
92
+ .np-table th, .np-table td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--border); vertical-align: top; }
93
+ .np-table th { color: var(--text-dim); font-weight: 600; font-size: 0.74rem; text-transform: uppercase; letter-spacing: 0.04em; }
94
+ .np-table tr[data-id] { cursor: pointer; }
95
+ .np-table tr[data-id]:hover td { background: var(--bg-subtle); }
96
+ .np-table tr.sel td { background: var(--accent-soft); }
97
+ .np-table img { width: 56px; height: 40px; object-fit: cover; border-radius: 3px; display: block; }
98
+ .np-chip { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 0.74rem; font-weight: 600; white-space: nowrap; background: var(--bg-subtle); }
99
+ .np-chip.verified { background: color-mix(in srgb, var(--success, #1f8a4c) 14%, transparent); color: var(--success, #1f8a4c); }
100
+ .np-chip.mismatch { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
101
+ .np-missing { font-size: 0.82rem; color: var(--text-dim); margin-top: 10px; }
102
+ @media (max-width: 980px) {
103
+ .np-top { grid-template-columns: 1fr; }
104
+ .np-reading { border-left: none; border-top: 1px solid var(--border); }
105
+ }
106
+ @media (max-width: 820px) {
107
+ /* One column that scrolls as a page, not panels that each scroll (they overlapped the photo). */
108
+ html, body { height: auto; }
109
+ .np-wrap { display: block; }
110
+ .np-side, .np-main { overflow: visible; }
111
+ .np-side { border-right: none; border-bottom: 1px solid var(--border); padding: 16px; }
112
+ .np-stage { min-height: 220px; }
113
+ .np-reading, .np-register { padding: 14px 16px; }
114
+ .np-table .np-hide-sm { display: none; }
115
+ }
116
+ </style>
117
+ </head>
118
+ <body>
119
+ <header class="app-header">
120
+ <div class="brand">
121
+ <a class="brand-home" href="https://huggingface.co/constructelligence/data-centre-nameplates" title="Model card on Hugging Face" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:8px">
122
+ <h1 class="brand-name">BuildVision</h1>
123
+ </a>
124
+ </div>
125
+ <nav class="mode-switch" aria-label="Page">
126
+ <a class="mode-link" href="https://huggingface.co/constructelligence/data-centre-nameplates" target="_blank" rel="noopener">Model card</a>
127
+ <a class="mode-link" href="https://constructelligence.co" target="_blank" rel="noopener">constructelligence.co</a>
128
+ <span class="mode-link active" aria-current="page">Nameplates</span>
129
+ </nav>
130
+ <div class="header-status"><span id="npModel" class="status-pill model-status">OCR idle</span></div>
131
+ </header>
132
+
133
+ <main class="np-wrap">
134
+ <aside class="np-side">
135
+ <section>
136
+ <h2>1. Equipment schedule</h2>
137
+ <label id="npSchedDrop" class="np-drop" tabindex="0">
138
+ <input id="npSchedFile" type="file" accept=".csv,.tsv,.txt,text/csv" hidden />
139
+ <span>Drop the equipment schedule as CSV, or click to choose</span>
140
+ </label>
141
+ <div class="np-row" style="margin-top:8px">
142
+ <button id="npSchedSample" class="np-btn" type="button">Use sample schedule</button>
143
+ <button id="npSchedClear" class="np-btn link" type="button" hidden>Remove</button>
144
+ </div>
145
+ <p id="npSchedStatus" class="np-status" style="margin-top:8px" aria-live="polite"></p>
146
+ <p style="margin-top:6px">Optional. Needs a Tag or Model column; Manufacturer, Voltage, Phase, kVA, kW, Amps, Refrigerant, Serial and Location are checked when present.</p>
147
+ </section>
148
+ <section>
149
+ <h2>2. Nameplate photo</h2>
150
+ <label id="npDrop" class="np-drop" tabindex="0">
151
+ <input id="npFile" type="file" accept="image/*" multiple hidden />
152
+ <span>Take or drop a nameplate photo, or a batch from a walk</span>
153
+ </label>
154
+ <div class="np-row" style="margin-top:8px">
155
+ <button id="npSample" class="np-btn" type="button">Try a sample nameplate</button>
156
+ <button id="npRotate" class="np-btn" type="button" disabled title="Rotate the photo 90°">Rotate</button>
157
+ </div>
158
+ <p style="margin-top:8px">Fill the frame with the plate, without glare across the text. Tilted shots are straightened automatically. Pick several photos at once to read a whole walk into the register, then click a row to review it.</p>
159
+ </section>
160
+ <section>
161
+ <button id="npRun" class="np-btn primary" type="button" disabled>Read nameplate</button>
162
+ <div class="np-bar" style="margin-top:10px"><i id="npProg"></i></div>
163
+ <div id="npStatus" class="np-status" role="status" aria-live="polite"></div>
164
+ </section>
165
+ <section>
166
+ <p class="np-note">Runs in your browser: photos never leave this device. The first read downloads the OCR engine and English text model (about 11 MB) from a public CDN. OCR misreads happen, so fields with low confidence are highlighted for you to check against the plate.</p>
167
+ </section>
168
+ </aside>
169
+
170
+ <section class="np-main">
171
+ <div class="np-top">
172
+ <div class="np-stage">
173
+ <canvas id="npCanvas" width="0" height="0" hidden></canvas>
174
+ <div id="npEmpty" class="np-empty">Load a nameplate photo to begin.</div>
175
+ </div>
176
+ <div id="npReading" class="np-reading" hidden>
177
+ <h2>Reading</h2>
178
+ <div id="npVerdict" class="np-verdict" aria-live="polite"></div>
179
+ <div class="np-fields" id="npFields"></div>
180
+ <div class="np-tag">
181
+ <span>Schedule tag</span>
182
+ <select id="npTag"></select>
183
+ <span id="npTagNote" class="np-note" style="font-weight:400"></span>
184
+ </div>
185
+ <ul id="npChecks" class="np-checks" aria-label="Checks against the schedule"></ul>
186
+ <div class="np-row">
187
+ <button id="npAdd" class="np-btn primary" type="button">Add to register</button>
188
+ <details style="font-size:0.8rem;color:var(--text-dim)"><summary>OCR text</summary><pre id="npText" style="white-space:pre-wrap;font-size:0.78rem;margin:6px 0 0"></pre></details>
189
+ </div>
190
+ </div>
191
+ </div>
192
+ <div class="np-register">
193
+ <h2>Asset register</h2>
194
+ <div id="npSummary" class="np-summary"></div>
195
+ <div class="np-row" style="margin-bottom:10px">
196
+ <button id="npCsv" class="np-btn" type="button" disabled>Download register CSV</button>
197
+ <button id="npClearReg" class="np-btn link" type="button" disabled>Clear register</button>
198
+ </div>
199
+ <table class="np-table">
200
+ <thead><tr><th class="np-hide-sm">Photo</th><th>Tag</th><th>Status</th><th>Model</th><th class="np-hide-sm">Serial</th><th class="np-hide-sm">Voltage</th><th>Issues</th><th></th></tr></thead>
201
+ <tbody id="npRows"></tbody>
202
+ </table>
203
+ <p id="npEmptyReg" class="np-note" style="margin-top:10px">Nothing scanned yet. Each plate you add appears here with its check result.</p>
204
+ <p id="npMissing" class="np-missing"></p>
205
+ </div>
206
+ </section>
207
+ </main>
208
+ <script type="module" src="nameplates-app.js"></script>
209
+ </body>
210
  </html>
nameplate-model.js ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Nameplates: equipment nameplate OCR checked against the equipment schedule.
2
+ // On a data centre job the gear is the job (UPS, PDUs, switchgear, gensets,
3
+ // CRAHs, chillers), and the costly mistakes are a unit delivered at the wrong
4
+ // voltage or rating, or one that never gets onto the asset register. This
5
+ // module turns OCR text into nameplate fields, matches a reading to the
6
+ // schedule, checks each field, and builds the register CSV.
7
+ //
8
+ // OCR is Tesseract.js (pretrained, loaded from the CDN like the other models),
9
+ // so nothing here is trained: it is parsing and matching.
10
+ // Pure functions (tests/nameplate-model.test.mjs).
11
+ import { parseCsv } from './schedule-import.js';
12
+
13
+ export const FIELDS = [
14
+ ['manufacturer', 'Manufacturer'], ['model', 'Model'], ['serial', 'Serial'], ['voltage', 'Voltage'],
15
+ ['phase', 'Phase'], ['hz', 'Hz'], ['kva', 'kVA'], ['kw', 'kW'], ['amps', 'Amps'], ['mca', 'MCA'], ['mocp', 'MOCP'],
16
+ ['refrigerant', 'Refrigerant'], ['mfgDate', 'Mfg date'],
17
+ ];
18
+
19
+ export const EQUIPMENT_TYPES = [
20
+ ['ups', 'UPS', /\bUPS\b|UNINTERRUPTIBLE/],
21
+ ['generator', 'Generator', /GENERATOR|GENSET|\bEKW\b|STANDBY POWER|PRIME POWER/],
22
+ ['ats', 'Transfer switch', /TRANSFER SWITCH|\bATS\b|\bSTS\b/],
23
+ ['switchgear', 'Switchgear / switchboard', /SWITCHGEAR|SWITCHBOARD/],
24
+ ['transformer', 'Transformer', /TRANSFORMER|\bXFMR\b|PRIMARY.*SECONDARY/],
25
+ ['pdu', 'PDU / RPP', /POWER DISTRIBUTION UNIT|\bPDU\b|\bRPP\b|REMOTE POWER PANEL/],
26
+ ['panelboard', 'Panelboard', /PANELBOARD/],
27
+ ['busway', 'Busway', /BUSWAY|BUS PLUG|BUS DUCT/],
28
+ ['battery', 'Battery cabinet', /BATTERY|\bVRLA\b|LITHIUM/],
29
+ ['cdu', 'Coolant distribution unit', /COOLANT DISTRIBUTION|\bCDU\b/],
30
+ ['chiller', 'Chiller', /CHILLER/],
31
+ ['crah', 'CRAH / CRAC', /\bCRAH\b|\bCRAC\b|COMPUTER ROOM AIR|AIR HANDL/],
32
+ ['pump', 'Pump', /\bPUMP\b/],
33
+ ];
34
+
35
+ // Makers common on data centre electrical and cooling packages. Matched as
36
+ // whole words; anything else falls back to a line that reads like a company.
37
+ const MAKERS = [
38
+ 'Schneider Electric', 'Square D', 'APC', 'Eaton', 'ABB', 'Siemens', 'Vertiv', 'Liebert', 'Caterpillar', 'Cummins',
39
+ 'Kohler', 'Rolls-Royce', 'MTU', 'Generac', 'Trane', 'Carrier', 'Daikin', 'York', 'Johnson Controls', 'Stulz',
40
+ 'Munters', 'nVent', 'Legrand', 'Mitsubishi Electric', 'Toshiba', 'General Electric', 'Hubbell', 'Socomec', 'Piller',
41
+ 'Starline', 'Raritan', 'Server Technology', 'Emerson', 'Russelectric', 'ASCO', 'Hitachi', 'Riello',
42
+ 'Rittal', 'Motivair', 'CoolIT', 'Hitec', 'EnerSys', 'Leclanché', 'Samsung SDI',
43
+ ];
44
+ const COMPANY_LINE = /\b(INC|CORP|CORPORATION|LTD|LLC|GMBH|CO\.|COMPANY|SYSTEMS|ELECTRIC|POWER|TECHNOLOGIES|INDUSTRIES)\b/;
45
+
46
+ const NUM = '(\\d{1,5}(?:[.,]\\d+)?)';
47
+ // "1,002" is a thousands separator on a US plate; "2,5" is a European decimal.
48
+ const num = s => (s == null ? null : parseFloat(/^\d{1,3},\d{3}$/.test(String(s)) ? String(s).replace(',', '') : String(s).replace(',', '.')));
49
+
50
+ /**
51
+ * Nameplate fields from OCR output: a string, or lines as [{ text, confidence }]
52
+ * (Tesseract's data.lines). Each field is { value, conf } (conf 0–100, the OCR
53
+ * confidence of the line it came from; 100 for plain text).
54
+ */
55
+ export function parseNameplate(input) {
56
+ const lines = (typeof input === 'string' ? input.split(/\r?\n/).map(text => ({ text, confidence: 100 })) : input)
57
+ .map(l => ({ text: ocrFix(String(l.text || '').replace(/\s+/g, ' ').trim()), conf: Math.round(l.confidence ?? 100), bbox: l.bbox || null }))
58
+ // Lines Tesseract itself scores near zero are texture read as text (brushed metal, a busy background).
59
+ .filter(l => l.text && l.conf >= 20);
60
+ const fields = {};
61
+ // line: index of the OCR line the value came from, so the page can outline it on the photo.
62
+ const set = (key, value, conf, line) => { if (fields[key] == null && value != null && value !== '') fields[key] = { value, conf, line }; };
63
+ // Each rule runs over every line in order, so the first line that has the field wins.
64
+ const scan = (key, re, map = m => m[1]) => {
65
+ for (const [i, l] of lines.entries()) {
66
+ const m = up(l.text).match(re);
67
+ if (m) { const v = map(m); if (v != null && v !== '') { set(key, v, l.conf, i); return; } }
68
+ }
69
+ };
70
+
71
+ const CODE = '([A-Z0-9][A-Z0-9\\-\\/\\.]{2,})';
72
+ scan('model', new RegExp(`(?:\\bMODEL\\b|\\bMOD\\.|\\bM\\/N\\b|\\bCAT(?:ALOG)?\\.?\\s*(?:NO\\b\\.?|#|NUMBER)|\\bP\\/N\\b|\\bPART\\s*(?:NO\\b\\.?|#|NUMBER))\\s*(?:NO\\b\\.?|NUMBER\\b|#)?\\s*[:#.]?\\s*${CODE}`), m => cleanCode(m[1]));
73
+ scan('serial', new RegExp(`(?:\\bSERIAL\\b|\\bSER\\.|\\bS\\/N\\b|\\b5\\/N\\b|\\bSN\\b)\\s*(?:NO\\b\\.?|NUMBER\\b|#)?\\s*[:#.]?\\s*([A-Z0-9][A-Z0-9\\-]{3,})`), m => cleanCode(m[1]));
74
+ scan('refrigerant', /\bR[-\s]?(410A|134A|1234ZE|1234YF|513A|514A|1233ZD|454B|407C|32|22)\b/, m => `R-${m[1]}`);
75
+ scan('hz', /\b(50|60)\s*HZ\b|\bHZ\s*[:]?\s*(50|60)\b|\bFREQ(?:UENCY)?\.?\s*[:]?\s*(50|60)\b/, m => +(m[1] || m[2] || m[3]));
76
+ scan('phase', /\b([13])\s*-?\s*(?:PH|PHASE|Ø|Φ)\b|\bPH(?:ASE)?\s*[:]?\s*([13])\b/, m => +(m[1] || m[2]));
77
+ scan('kva', new RegExp(`${NUM}\\s*KVA\\b|\\bKVA\\s*[:]?\\s*${NUM}`), m => num(m[1] || m[2]));
78
+ scan('kw', new RegExp(`${NUM}\\s*E?KW\\b|\\bE?KW\\s*[:]?\\s*${NUM}`), m => num(m[1] || m[2]));
79
+ scan('mfgDate', /\b(?:MFG\.?|MANUFACTURED|MFD\.?|BUILD|PROD(?:UCTION)?\.?)\s*(?:DATE)?\s*[:]?\s*(\d{1,2}[/-]\d{2,4}|\d{4}[/-]\d{1,2}(?:[/-]\d{1,2})?|\d{1,2}[/-]\d{1,2}[/-]\d{2,4})/, m => m[1]);
80
+
81
+ // Voltage: every voltage on the plate (a transformer or UPS carries more than one).
82
+ const volts = [];
83
+ let voltLine = null;
84
+ for (const [i, l] of lines.entries()) {
85
+ const found = voltagesIn(up(l.text));
86
+ if (found.values.length) {
87
+ for (const v of found.values) if (!volts.includes(v)) volts.push(v);
88
+ if (!voltLine) voltLine = { text: found.display, conf: l.conf, line: i };
89
+ }
90
+ }
91
+ if (volts.length) fields.voltage = { value: voltLine.text, conf: voltLine.conf, line: voltLine.line, values: volts };
92
+
93
+ // Amps: a labelled rated current first, then any bare "1002 A". Refrigerants (R-410A) are not amps.
94
+ scan('amps', new RegExp(`(?:\\bFLA\\b|\\bRLA\\b|\\bCURRENT\\b|\\bAMPS?\\b|\\bAMPERES\\b)\\s*[:]?\\s*${NUM}`), m => num(m[1]));
95
+ if (!fields.amps) scan('amps', new RegExp(`(?<![-\\d.R])${NUM}\\s*(?:A|AMPS?)\\b`), m => num(m[1]));
96
+ scan('mca', new RegExp(`\\bMCA\\b\\s*[:]?\\s*${NUM}`), m => num(m[1]));
97
+ scan('mocp', new RegExp(`(?:\\bMOCP\\b|\\bMAX\\.?\\s*(?:FUSE|BREAKER|OCP))\\s*(?:SIZE)?\\s*[:]?\\s*${NUM}`), m => num(m[1]));
98
+
99
+ // Manufacturer: a known maker anywhere, else a line that reads like a company name.
100
+ for (const [i, l] of lines.entries()) {
101
+ // "New York" on a supplier's address is not York the maker.
102
+ const t = up(l.text).replace(/NEW YORK/g, '');
103
+ const maker = MAKERS.find(mk => new RegExp(`\\b${escapeRe(up(mk))}\\b`).test(t));
104
+ if (maker) { set('manufacturer', maker, l.conf, i); break; }
105
+ }
106
+ if (!fields.manufacturer) {
107
+ const i = lines.findIndex(x => COMPANY_LINE.test(up(x.text)) && !/\d{3}/.test(x.text) && x.text.length <= 48);
108
+ if (i >= 0) set('manufacturer', titleCase(lines[i].text.replace(/[^A-Za-z0-9&.,\- ]/g, '').trim()), lines[i].conf, i);
109
+ }
110
+
111
+ const all = up(lines.map(l => l.text).join('\n'));
112
+ const type = (EQUIPMENT_TYPES.find(([, , re]) => re.test(all)) || [null])[0];
113
+ const conf = lines.length ? Math.round(lines.reduce((s, l) => s + l.conf, 0) / lines.length) : 0;
114
+ return { fields, type, conf, text: lines.map(l => l.text).join('\n'), lines: lines.map(l => ({ text: l.text, conf: l.conf, bbox: l.bbox })) };
115
+ }
116
+
117
+ /**
118
+ * Undo the misreads Tesseract makes on plate lettering (seen in tests/nameplates-bench.mjs):
119
+ * a serifed "V" read as "Vv", "Y" as "¥", codes and decimals split after their punctuation
120
+ * ("NPX- 750- 480", "38. 5"), "HZ" as "Hw"/"H2", "KVA" as "XVA".
121
+ */
122
+ export function ocrFix(t) {
123
+ return t
124
+ .replace(/[¥]/g, 'Y')
125
+ .replace(/[‘’`]/g, "'")
126
+ .replace(/(\d)\s*V[vV]\b/g, '$1 V')
127
+ .replace(/([A-Za-z0-9])-\s+(?=[A-Za-z0-9])/g, '$1-')
128
+ .replace(/(\d)\.\s+(?=\d)/g, '$1.')
129
+ .replace(/\b(50|60)\s*H[wW2]\b/g, '$1 HZ')
130
+ // K read as X in KVA / KW / EKW.
131
+ .replace(/(\d\s*)XVA\b/g, '$1KVA')
132
+ .replace(/(\d\s*)E[KX][WN]\b/g, '$1EKW')
133
+ .replace(/(\d\s*)XW\b/g, '$1KW');
134
+ }
135
+
136
+ /** Voltages written on one line: 480Y/277V, 208/120 VAC, VOLTS: 480, 13.8 kV. */
137
+ export function voltagesIn(s) {
138
+ s = s.replace(/(\d),(\d{3})\b/g, '$1$2'); // 13,800 V
139
+ const values = [];
140
+ let display = null;
141
+ const add = (v, shown) => {
142
+ if (!(v >= 100 && v <= 40000)) return;
143
+ if (!values.includes(v)) values.push(v);
144
+ if (!display) display = shown;
145
+ };
146
+ const pair = /\b(\d{3,5})\s*(Y)?\s*\/\s*(\d{3,5})\s*(?:V|VAC|VOLTS?)?\b/g;
147
+ let m;
148
+ const isLabelled = /VOLT|\bV\b|\bVAC\b|\dV\b/.test(s);
149
+ while ((m = pair.exec(s))) {
150
+ // "480/277" with no V anywhere on the line could be anything; require a voltage word or unit.
151
+ if (!isLabelled && !/\d\s*(?:V|VAC|VOLTS?)\b/.test(m[0])) continue;
152
+ add(+m[1], `${m[1]}${m[2] ? 'Y' : ''}/${m[3]} V`);
153
+ add(+m[3], null);
154
+ }
155
+ const single = /\b(\d{3,5})\s*(?:V|VAC|VDC|VOLTS?)\b/g;
156
+ while ((m = single.exec(s))) add(+m[1], `${m[1]} V`);
157
+ const labelled = /\bVOLT(?:S|AGE)?\b[^0-9]{0,12}(\d{3,5})\b/g;
158
+ while ((m = labelled.exec(s))) add(+m[1], `${m[1]} V`);
159
+ const kv = /\b(\d{1,2}(?:\.\d{1,2})?)\s*KV\b/g;
160
+ while ((m = kv.exec(s))) add(Math.round(parseFloat(m[1]) * 1000), `${m[1]} kV`);
161
+ return { values, display };
162
+ }
163
+
164
+ // ------------------------------------------------------------------ schedule
165
+
166
+ const HEADERS = {
167
+ tag: /^(tag|mark|equipment tag|equip(ment)? (id|no\.?|number|tag)|asset( tag| id)?|id|unit tag)$/i,
168
+ type: /^(type|equipment|equipment type|description|desc|item|system)$/i,
169
+ manufacturer: /^(manufacturer|mfr\.?|mfg\.?|make|brand|vendor|basis of design)$/i,
170
+ model: /^(model|model no\.?|model number|model #|cat(alog)? no\.?|catalog number|part (no\.?|number))$/i,
171
+ serial: /^(serial|serial no\.?|serial number|s\/n)$/i,
172
+ voltage: /^(voltage|volts|v|input voltage|volts\/phase|electrical)$/i,
173
+ phase: /^(phase|ph|phases)$/i,
174
+ kva: /^(kva|rating \(kva\)|kva rating|capacity \(kva\))$/i,
175
+ kw: /^(kw|ekw|rating \(kw\)|kw rating|capacity \(kw\))$/i,
176
+ amps: /^(amps|a|amperage|fla|rated current|current)$/i,
177
+ mca: /^(mca|min\.? circuit amp(s|acity)?|minimum circuit ampacity)$/i,
178
+ mocp: /^(mocp|max\.? (fuse|breaker|ocp)( size)?|maximum overcurrent protection)$/i,
179
+ refrigerant: /^(refrigerant|ref\.?)$/i,
180
+ location: /^(location|room|area|level|space|served from|zone)$/i,
181
+ };
182
+
183
+ /** Equipment schedule from a CSV export: the header row is the first that names a tag or model column plus one more. */
184
+ export function parseEquipmentSchedule(text) {
185
+ const rows = parseCsv(String(text || ''));
186
+ const known = r => Object.values(HEADERS).filter(re => r.some(c => re.test(c.trim()))).length;
187
+ const headerIdx = rows.findIndex(r => (r.some(c => HEADERS.tag.test(c.trim())) || r.some(c => HEADERS.model.test(c.trim()))) && known(r) >= 2);
188
+ if (headerIdx < 0) return { items: [], problems: ['No header row with a Tag or Model column was found.'] };
189
+ const header = rows[headerIdx].map(c => c.trim());
190
+ const cols = Object.fromEntries(Object.keys(HEADERS).map(k => [k, header.findIndex(h => HEADERS[k].test(h))]));
191
+ const items = [], problems = [];
192
+ rows.slice(headerIdx + 1).forEach((r, i) => {
193
+ const get = k => (cols[k] >= 0 ? String(r[cols[k]] ?? '').trim() : '');
194
+ const tag = get('tag') || (get('model') ? `Row ${headerIdx + i + 2}` : '');
195
+ if (!tag) return;
196
+ if (items.some(x => x.tag === tag)) problems.push(`Tag ${tag} appears more than once; the first row is used.`);
197
+ else items.push({
198
+ tag, type: get('type'), manufacturer: get('manufacturer'), model: get('model'), serial: get('serial'),
199
+ voltage: get('voltage'), phase: num(get('phase').match(/[13]/)?.[0]), kva: num(get('kva')) || null, kw: num(get('kw')) || null,
200
+ amps: num(get('amps')) || null, mca: num(get('mca')) || null, mocp: num(get('mocp')) || null, refrigerant: get('refrigerant'), location: get('location'),
201
+ });
202
+ });
203
+ if (!items.length) problems.push('The header was found but no equipment rows under it.');
204
+ return { items, problems };
205
+ }
206
+
207
+ /** Voltages a schedule cell asks for: "480Y/277", "480V 3PH", "13.8kV". */
208
+ export function scheduleVoltages(cell) {
209
+ const s = up(cell);
210
+ const r = voltagesIn(s);
211
+ if (r.values.length) return r.values;
212
+ return [...s.matchAll(/(?<![\d.])(\d{3,5})(?![\d.])/g)].map(m => +m[1]).filter(v => v >= 100 && v <= 40000);
213
+ }
214
+
215
+ // ------------------------------------------------------------------ matching
216
+
217
+ /** Model/serial codes compared the way OCR gets them wrong: O/0, I/L/1, S/5, B/8, Z/2, punctuation and case ignored. */
218
+ export function foldCode(s) {
219
+ return up(s).replace(/[^A-Z0-9]/g, '').replace(/O/g, '0').replace(/[IL]/g, '1').replace(/S/g, '5').replace(/B/g, '8').replace(/Z/g, '2');
220
+ }
221
+
222
+ export function codeSimilarity(a, b) {
223
+ const x = foldCode(a), y = foldCode(b);
224
+ if (!x || !y) return 0;
225
+ if (x === y) return 1;
226
+ // Plate models often carry option suffixes the schedule leaves off (9395P-750 vs 9395P-750-N-480).
227
+ const [short, long] = x.length <= y.length ? [x, y] : [y, x];
228
+ if (short.length >= 5 && long.startsWith(short)) return 0.92;
229
+ return 1 - levenshtein(x, y) / Math.max(x.length, y.length);
230
+ }
231
+
232
+ const sameMaker = (a, b) => {
233
+ const x = up(a).replace(/[^A-Z0-9]/g, ''), y = up(b).replace(/[^A-Z0-9]/g, '');
234
+ return !!x && !!y && (x.includes(y) || y.includes(x));
235
+ };
236
+
237
+ /**
238
+ * Schedule rows this reading could be, best first: [{ item, score, registered }].
239
+ * Data halls repeat, so several tags often share one model (UPS-1A, UPS-1B…):
240
+ * among equal scores, tags not on the register yet come first.
241
+ */
242
+ export function candidatesFor(reading, items, register = []) {
243
+ const f = reading.fields || {};
244
+ const taken = new Set(register.map(r => r.tag).filter(Boolean));
245
+ const out = [];
246
+ for (const item of items) {
247
+ let score;
248
+ if (item.serial && f.serial?.value && foldCode(item.serial) === foldCode(f.serial.value)) score = 1.5;
249
+ else {
250
+ const m = item.model && f.model?.value ? codeSimilarity(item.model, f.model.value) : 0;
251
+ const mk = item.manufacturer && f.manufacturer?.value ? (sameMaker(item.manufacturer, f.manufacturer.value) ? 1 : 0) : 0.5;
252
+ const ty = reading.type && item.type ? (typeOf(item.type) === reading.type ? 1 : 0) : 0.5;
253
+ score = 0.7 * m + 0.15 * mk + 0.15 * ty;
254
+ }
255
+ if (score >= 0.5) out.push({ item, score: Math.round(score * 100) / 100, registered: taken.has(item.tag) });
256
+ }
257
+ return out.sort((a, b) => (b.score - a.score) || (a.registered - b.registered));
258
+ }
259
+
260
+ /** Equipment type key for free text such as a schedule's description column. */
261
+ export function typeOf(text) {
262
+ const s = up(text);
263
+ return (EQUIPMENT_TYPES.find(([, , re]) => re.test(s)) || [null])[0];
264
+ }
265
+
266
+ /**
267
+ * Field-by-field check of a reading against one schedule row:
268
+ * [{ key, label, status: 'ok' | 'mismatch' | 'unread', expected, found }].
269
+ * Fields the schedule leaves blank are not checked.
270
+ */
271
+ export function checkAgainst(reading, item) {
272
+ const f = reading.fields || {};
273
+ const out = [];
274
+ const push = (key, expected, found, ok) => out.push({
275
+ key, label: FIELDS.find(x => x[0] === key)?.[1] || key, expected: String(expected), found: found == null ? '' : String(found),
276
+ status: found == null || found === '' ? 'unread' : ok ? 'ok' : 'mismatch',
277
+ });
278
+ if (item.manufacturer) push('manufacturer', item.manufacturer, f.manufacturer?.value, sameMaker(item.manufacturer, f.manufacturer?.value));
279
+ if (item.model) push('model', item.model, f.model?.value, codeSimilarity(item.model, f.model?.value) >= 0.85);
280
+ if (item.serial) push('serial', item.serial, f.serial?.value, foldCode(item.serial) === foldCode(f.serial?.value));
281
+ if (item.voltage) {
282
+ const want = scheduleVoltages(item.voltage);
283
+ const have = f.voltage?.values || (f.voltage?.value ? scheduleVoltages(f.voltage.value) : []);
284
+ push('voltage', item.voltage, f.voltage?.value, want.length > 0 && want.every(v => have.includes(v)));
285
+ }
286
+ if (item.phase) push('phase', item.phase, f.phase?.value, +item.phase === +f.phase?.value);
287
+ for (const k of ['kva', 'kw', 'amps', 'mca', 'mocp']) {
288
+ if (item[k]) push(k, item[k], f[k]?.value, Math.abs(+f[k]?.value - item[k]) <= Math.max(0.5, item[k] * 0.01));
289
+ }
290
+ if (item.refrigerant) push('refrigerant', item.refrigerant, f.refrigerant?.value, up(item.refrigerant).replace(/[^A-Z0-9]/g, '') === up(f.refrigerant?.value).replace(/[^A-Z0-9]/g, ''));
291
+ return out;
292
+ }
293
+
294
+ /** Overall status of a register entry: matched and clean, matched with a problem, or not on the schedule. */
295
+ export function statusOf(checks, tag) {
296
+ if (!tag) return 'unmatched';
297
+ if (checks.some(c => c.status === 'mismatch')) return 'mismatch';
298
+ if (checks.some(c => c.status === 'unread')) return 'partial';
299
+ return 'verified';
300
+ }
301
+
302
+ export const STATUS_LABELS = { verified: 'Verified', partial: 'Matched, fields unread', mismatch: 'Does not match schedule', unmatched: 'Not on schedule', missing: 'Not scanned yet' };
303
+
304
+ /** Register entries that share a serial (the same plate scanned twice, or a copied serial). */
305
+ export function duplicateSerials(register) {
306
+ const seen = new Map();
307
+ for (const r of register) {
308
+ const s = foldCode(r.fields?.serial?.value);
309
+ if (!s) continue;
310
+ seen.set(s, [...(seen.get(s) || []), r.id]);
311
+ }
312
+ return [...seen.values()].filter(ids => ids.length > 1);
313
+ }
314
+
315
+ /** Progress against the schedule: scanned, verified, flagged, not scanned. */
316
+ export function registerSummary(register, items = []) {
317
+ const tags = new Set(register.map(r => r.tag).filter(Boolean));
318
+ return {
319
+ scanned: register.length,
320
+ scheduled: items.length,
321
+ scannedOfSchedule: items.filter(i => tags.has(i.tag)).length,
322
+ verified: register.filter(r => r.status === 'verified').length,
323
+ flagged: register.filter(r => r.status === 'mismatch').length,
324
+ unmatched: register.filter(r => r.status === 'unmatched').length,
325
+ duplicates: duplicateSerials(register).length,
326
+ missing: items.filter(i => !tags.has(i.tag)).map(i => i.tag),
327
+ };
328
+ }
329
+
330
+ /** Asset register CSV: one row per scanned plate, then every scheduled tag not scanned yet. */
331
+ export function registerCsv(register, items = []) {
332
+ const head = ['Tag', 'Status', 'Type', 'Location', 'Manufacturer', 'Model', 'Serial', 'Voltage', 'Phase', 'Hz', 'kVA', 'kW', 'Amps', 'MCA', 'MOCP', 'Refrigerant', 'Mfg date', 'Issues', 'Scanned'];
333
+ const byTag = new Map(items.map(i => [i.tag, i]));
334
+ const typeLabel = k => (EQUIPMENT_TYPES.find(t => t[0] === k) || [])[1] || '';
335
+ const dups = new Set(duplicateSerials(register).flat());
336
+ const rows = register.map(r => {
337
+ const f = r.fields || {};
338
+ const v = k => f[k]?.value ?? '';
339
+ const issues = (r.checks || []).filter(c => c.status === 'mismatch').map(c => `${c.label}: schedule ${c.expected}, plate ${c.found}`);
340
+ if (dups.has(r.id)) issues.push('Serial also on another scanned plate');
341
+ return [r.tag || '', STATUS_LABELS[r.status] || r.status, typeLabel(r.type), byTag.get(r.tag)?.location || '',
342
+ v('manufacturer'), v('model'), v('serial'), v('voltage'), v('phase'), v('hz'), v('kva'), v('kw'), v('amps'),
343
+ v('mca'), v('mocp'), v('refrigerant'), v('mfgDate'), issues.join('; '), r.scannedAt ? new Date(r.scannedAt).toISOString().slice(0, 16).replace('T', ' ') : ''];
344
+ });
345
+ const tags = new Set(register.map(r => r.tag));
346
+ for (const i of items) {
347
+ if (tags.has(i.tag)) continue;
348
+ rows.push([i.tag, STATUS_LABELS.missing, i.type, i.location, i.manufacturer, i.model, i.serial, i.voltage, i.phase ?? '', '',
349
+ i.kva ?? '', i.kw ?? '', i.amps ?? '', i.mca ?? '', i.mocp ?? '', i.refrigerant, '', '', '']);
350
+ }
351
+ return [head, ...rows].map(r => r.map(csvCell).join(',')).join('\n') + '\n';
352
+ }
353
+
354
+ // ------------------------------------------------------------------ sample data
355
+
356
+ // Fictional maker and models: the sample shows the workflow without implying
357
+ // any real product's ratings.
358
+ export const SAMPLE_SCHEDULE = `Tag,Description,Manufacturer,Model,Voltage,Phase,kVA,kW,MCA,MOCP,Refrigerant,Location
359
+ UPS-1A,Static UPS module,Northline Power Systems,NPX-750-480,480Y/277,3,750,675,,,,Electrical Room 1A
360
+ UPS-1B,Static UPS module,Northline Power Systems,NPX-750-480,480Y/277,3,750,675,,,,Electrical Room 1B
361
+ UPS-2A,Static UPS module,Northline Power Systems,NPX-750-480,480Y/277,3,750,675,,,,Electrical Room 2A
362
+ UPS-2B,Static UPS module,Northline Power Systems,NPX-750-480,480Y/277,3,750,675,,,,Electrical Room 2B
363
+ PDU-1-01,Power distribution unit,Northline Power Systems,NPD-300-415,480 / 415Y/240,3,300,,,,,Data Hall 1
364
+ PDU-1-02,Power distribution unit,Northline Power Systems,NPD-300-415,480 / 415Y/240,3,300,,,,,Data Hall 1
365
+ GEN-01,Diesel generator,Harbor Engine Works,HG-3000,13800,3,3750,3000,,,,Generator Yard
366
+ GEN-02,Diesel generator,Harbor Engine Works,HG-3000,13800,3,3750,3000,,,,Generator Yard
367
+ CRAH-1-01,Computer room air handler,Coldline Systems,CW-150-480,480,3,,,45,60,,Data Hall 1
368
+ CH-01,Air-cooled chiller,Coldline Systems,AC-1200,460,3,,,612,800,R-513A,Roof
369
+ `;
370
+
371
+ /** Text of the two sample plates: one that matches UPS-1A, one delivered at the wrong voltage. */
372
+ export const SAMPLE_PLATES = [
373
+ ['NORTHLINE POWER SYSTEMS', 'UNINTERRUPTIBLE POWER SUPPLY', 'MODEL NO: NPX-750-480', 'SERIAL NO: NL26A01937',
374
+ 'INPUT: 480Y/277 VAC 3 PH 60 HZ', 'RATING: 750 KVA / 675 KW', 'INPUT CURRENT: 1002 A', 'MFG DATE: 03/2026'],
375
+ ['NORTHLINE POWER SYSTEMS', 'UNINTERRUPTIBLE POWER SUPPLY', 'MODEL NO: NPX-750-415', 'SERIAL NO: NL26A02210',
376
+ 'INPUT: 415Y/240 VAC 3 PH 50 HZ', 'RATING: 750 KVA / 675 KW', 'INPUT CURRENT: 1160 A', 'MFG DATE: 04/2026'],
377
+ ];
378
+
379
+ // ------------------------------------------------------------------ helpers
380
+
381
+ function up(s) { return String(s ?? '').toUpperCase(); }
382
+ function escapeRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
383
+ function cleanCode(s) { return s.replace(/[.\-/]+$/, ''); }
384
+ function titleCase(s) { return s.toLowerCase().replace(/\b[a-z]/g, c => c.toUpperCase()); }
385
+ function csvCell(v) { const s = String(v ?? ''); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; }
386
+
387
+ export function levenshtein(a, b) {
388
+ const prev = Array.from({ length: b.length + 1 }, (_, i) => i);
389
+ for (let i = 1; i <= a.length; i++) {
390
+ let diag = prev[0];
391
+ prev[0] = i;
392
+ for (let j = 1; j <= b.length; j++) {
393
+ const tmp = prev[j];
394
+ prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
395
+ diag = tmp;
396
+ }
397
+ }
398
+ return prev[b.length];
399
+ }
nameplates-app.js ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Nameplates page controller: load an equipment schedule, photograph a plate,
2
+ // OCR it (Tesseract.js, in the browser), parse and check the fields against the
3
+ // schedule, and keep an asset register that exports to CSV.
4
+ import {
5
+ FIELDS, EQUIPMENT_TYPES, STATUS_LABELS, SAMPLE_SCHEDULE, SAMPLE_PLATES,
6
+ parseNameplate, parseEquipmentSchedule, candidatesFor, checkAgainst, statusOf,
7
+ registerSummary, registerCsv, duplicateSerials, voltagesIn,
8
+ } from './nameplate-model.js';
9
+
10
+ const TESSERACT = 'https://cdn.jsdelivr.net/npm/tesseract.js@5.1.1/dist/tesseract.min.js';
11
+ const STORE = 'buildvision.nameplates.v1';
12
+ const LOW_CONF = 70;
13
+ const NUMERIC = new Set(['phase', 'hz', 'kva', 'kw', 'amps', 'mca', 'mocp']);
14
+ // Dark enough for white label text on the photo overlay.
15
+ const COLORS = {
16
+ manufacturer: '#0f2547', model: '#1b5fa8', serial: '#7340a8', voltage: '#c0262d', phase: '#b04f00', hz: '#7a4a35',
17
+ kva: '#1f7a32', kw: '#0b7285', amps: '#a8327a', mca: '#5c6b00', mocp: '#8a5a00', refrigerant: '#4d6b1f', mfgDate: '#555b63',
18
+ };
19
+
20
+ const $ = id => document.getElementById(id);
21
+ const els = Object.fromEntries([
22
+ 'npSchedDrop', 'npSchedFile', 'npSchedSample', 'npSchedClear', 'npSchedStatus', 'npDrop', 'npFile', 'npSample', 'npRotate',
23
+ 'npRun', 'npProg', 'npStatus', 'npModel', 'npCanvas', 'npEmpty', 'npReading', 'npVerdict', 'npFields', 'npTag', 'npTagNote',
24
+ 'npChecks', 'npAdd', 'npText', 'npSummary', 'npCsv', 'npClearReg', 'npRows', 'npEmptyReg', 'npMissing',
25
+ ].map(id => [id.slice(2, 3).toLowerCase() + id.slice(3), $(id)]));
26
+
27
+ const state = {
28
+ schedule: null, // { name, items }
29
+ register: [], // [{ id, tag, type, fields, checks, status, thumb, scannedAt }]
30
+ image: null, // canvas holding the photo as loaded (after rotation)
31
+ reading: null, // parseNameplate() result, with edits applied
32
+ candidates: [],
33
+ tag: '',
34
+ sample: 0,
35
+ editing: null, // register id being reviewed (Add then updates it)
36
+ photos: new Map(), // register id -> { image, reading } for this session (photos are not stored)
37
+ };
38
+ window.BuildVisionNameplates = state;
39
+
40
+ // ------------------------------------------------------------------ storage
41
+ function load() {
42
+ try {
43
+ const s = JSON.parse(localStorage.getItem(STORE) || 'null');
44
+ if (s) { state.schedule = s.schedule || null; state.register = s.register || []; }
45
+ } catch { /* private window or cleared storage: start empty */ }
46
+ }
47
+ function save() {
48
+ try { localStorage.setItem(STORE, JSON.stringify({ schedule: state.schedule, register: state.register })); }
49
+ catch { setStatus('Could not save the register in this browser. Download the CSV to keep it.', true); }
50
+ }
51
+
52
+ function setStatus(msg, err = false) { els.status.textContent = msg; els.status.classList.toggle('err', err); }
53
+ function setProgress(p) { els.prog.style.width = `${Math.round(p * 100)}%`; }
54
+ const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
55
+ // "Model" -> "model" in a sentence, but MOCP and kVA keep their case.
56
+ const inSentence = label => (label.slice(1) === label.slice(1).toLowerCase() ? label.toLowerCase() : label);
57
+ const typeLabel = k => (EQUIPMENT_TYPES.find(t => t[0] === k) || [])[1] || '';
58
+
59
+ // ------------------------------------------------------------------ schedule
60
+ function setSchedule(text, name) {
61
+ const { items, problems } = parseEquipmentSchedule(text);
62
+ if (!items.length) {
63
+ els.schedStatus.textContent = problems[0] || 'No equipment rows found.';
64
+ els.schedStatus.classList.add('err');
65
+ return;
66
+ }
67
+ state.schedule = { name, items };
68
+ els.schedStatus.classList.remove('err');
69
+ save();
70
+ renderSchedule(problems);
71
+ if (state.reading) rematch();
72
+ renderRegister();
73
+ }
74
+ function renderSchedule(problems = []) {
75
+ els.schedClear.hidden = !state.schedule;
76
+ if (!state.schedule) { els.schedStatus.textContent = 'No schedule loaded: plates are read but not checked.'; return; }
77
+ const n = state.schedule.items.length;
78
+ els.schedStatus.textContent = `${state.schedule.name}: ${n} item${n === 1 ? '' : 's'}.${problems.length ? ` ${problems.join(' ')}` : ''}`;
79
+ }
80
+
81
+ // ------------------------------------------------------------------ photo
82
+ async function decodeFile(file) {
83
+ const url = URL.createObjectURL(file);
84
+ try {
85
+ const img = new Image();
86
+ img.src = url;
87
+ await img.decode();
88
+ return img;
89
+ } finally { URL.revokeObjectURL(url); }
90
+ }
91
+
92
+ async function loadImageFile(file) {
93
+ try {
94
+ const img = await decodeFile(file);
95
+ setImage(img, img.naturalWidth, img.naturalHeight);
96
+ setStatus(`Loaded ${file.name}. Read it when ready.`);
97
+ } catch {
98
+ setStatus('That file could not be opened as an image.', true);
99
+ }
100
+ }
101
+
102
+ /**
103
+ * A walk's worth of photos: read each, match it to its likeliest tag and put it on the register.
104
+ * Flagged and low-confidence plates are then reviewed by clicking their row.
105
+ */
106
+ async function readBatch(files) {
107
+ const busy = [els.run, els.sample, els.rotate, els.add];
108
+ busy.forEach(b => { b.disabled = true; });
109
+ let done = 0, failed = 0;
110
+ try {
111
+ for (const [i, file] of files.entries()) {
112
+ setProgress(i / files.length);
113
+ setStatus(`Reading ${i + 1} of ${files.length}: ${file.name}…`);
114
+ let img;
115
+ try { img = await decodeFile(file); } catch { failed++; continue; }
116
+ setImage(img, img.naturalWidth, img.naturalHeight);
117
+ state.reading = await ocrImage(state.image);
118
+ state.reading.source = file.name;
119
+ rematch(true);
120
+ addToRegister({ quiet: true });
121
+ done++;
122
+ }
123
+ setProgress(1);
124
+ const added = state.register.slice(-done);
125
+ const flagged = added.filter(r => r.status === 'mismatch').length;
126
+ const review = added.filter(r => r.status !== 'verified').length;
127
+ setStatus(`Read ${done} plate${done === 1 ? '' : 's'}${failed ? ` (${failed} file${failed === 1 ? '' : 's'} could not be opened)` : ''}: ` +
128
+ `${done - review} verified, ${flagged} flagged${review - flagged ? `, ${review - flagged} to review` : ''}. Click a row to review it.`, failed > 0 && !done);
129
+ } catch (e) {
130
+ setStatus(`OCR failed: ${e.message}. It needs a network connection the first time.`, true);
131
+ } finally {
132
+ busy.forEach(b => { b.disabled = false; });
133
+ els.add.disabled = false;
134
+ }
135
+ }
136
+
137
+ /** Keep phone photos to a size OCR handles quickly; upscale small crops so text has enough pixels. */
138
+ function fitForOcr(src, w, h) {
139
+ const scale = Math.min(2400 / Math.max(w, h), Math.max(1, 1400 / Math.max(w, h)));
140
+ const c = document.createElement('canvas');
141
+ c.width = Math.round(w * scale); c.height = Math.round(h * scale);
142
+ c.getContext('2d').drawImage(src, 0, 0, c.width, c.height);
143
+ return c;
144
+ }
145
+
146
+ function setImage(src, w, h) {
147
+ state.image = fitForOcr(src, w, h);
148
+ state.reading = null;
149
+ state.editing = null;
150
+ getWorker().catch(() => {}); // start the 11 MB download and engine start-up now, not on Read
151
+ els.reading.hidden = true;
152
+ els.run.disabled = false;
153
+ els.rotate.disabled = false;
154
+ draw();
155
+ }
156
+
157
+ function rotate() {
158
+ const s = state.image;
159
+ const c = document.createElement('canvas');
160
+ c.width = s.height; c.height = s.width;
161
+ const g = c.getContext('2d');
162
+ g.translate(c.width, 0); g.rotate(Math.PI / 2); g.drawImage(s, 0, 0);
163
+ state.image = c;
164
+ state.reading = null;
165
+ els.reading.hidden = true;
166
+ draw();
167
+ }
168
+
169
+ /** A synthetic stamped-metal plate (fictional maker), drawn here so the sample needs no image file. */
170
+ function samplePlate(lines) {
171
+ const c = document.createElement('canvas');
172
+ c.width = 1400; c.height = 960;
173
+ const g = c.getContext('2d');
174
+ const bg = g.createLinearGradient(0, 0, c.width, c.height);
175
+ bg.addColorStop(0, '#d9dcdf'); bg.addColorStop(0.5, '#c4c8cc'); bg.addColorStop(1, '#d2d5d8');
176
+ g.fillStyle = '#5b6067'; g.fillRect(0, 0, c.width, c.height);
177
+ g.fillStyle = bg; roundRect(g, 40, 40, c.width - 80, c.height - 80, 26); g.fill();
178
+ for (let y = 60; y < c.height - 60; y += 3) { g.fillStyle = `rgba(255,255,255,${0.05 + 0.05 * Math.sin(y * 0.7)})`; g.fillRect(60, y, c.width - 120, 1); }
179
+ for (const [x, y] of [[80, 80], [c.width - 80, 80], [80, c.height - 80], [c.width - 80, c.height - 80]]) {
180
+ g.fillStyle = '#8b9096'; g.beginPath(); g.arc(x, y, 14, 0, Math.PI * 2); g.fill();
181
+ }
182
+ g.fillStyle = '#1b1e22';
183
+ g.textBaseline = 'alphabetic';
184
+ g.font = 'bold 54px Arial, Helvetica, sans-serif';
185
+ g.fillText(lines[0], 120, 175);
186
+ g.fillRect(120, 200, c.width - 240, 4);
187
+ g.font = 'bold 38px Arial, Helvetica, sans-serif';
188
+ g.fillText(lines[1], 120, 270);
189
+ g.font = 'bold 44px "Courier New", Courier, monospace';
190
+ lines.slice(2).forEach((t, i) => g.fillText(t, 120, 360 + i * 84));
191
+ return c;
192
+ }
193
+ function roundRect(g, x, y, w, h, r) {
194
+ g.beginPath(); g.moveTo(x + r, y); g.arcTo(x + w, y, x + w, y + h, r); g.arcTo(x + w, y + h, x, y + h, r);
195
+ g.arcTo(x, y + h, x, y, r); g.arcTo(x, y, x + w, y, r); g.closePath();
196
+ }
197
+
198
+ // ------------------------------------------------------------------ OCR
199
+ let workerPromise = null;
200
+ function loadScript(src) {
201
+ return new Promise((resolve, reject) => {
202
+ const s = document.createElement('script');
203
+ s.src = src; s.async = true; s.onload = resolve; s.onerror = () => reject(new Error(`Could not load ${src}`));
204
+ document.head.appendChild(s);
205
+ });
206
+ }
207
+ let onOcrProgress = () => {};
208
+ function getWorker() {
209
+ if (!workerPromise) {
210
+ workerPromise = (async () => {
211
+ els.model.textContent = 'Loading OCR…';
212
+ if (!window.Tesseract) await loadScript(TESSERACT);
213
+ const w = await window.Tesseract.createWorker('eng', 1, { logger: m => onOcrProgress(m) });
214
+ // Plates are blocks of short lines; keep spacing so "480Y/277 VAC 3 PH" stays on one line.
215
+ await w.setParameters({ preserve_interword_spaces: '1' });
216
+ els.model.textContent = 'OCR ready';
217
+ return w;
218
+ })().catch(e => { workerPromise = null; els.model.textContent = 'OCR unavailable'; throw e; });
219
+ }
220
+ return workerPromise;
221
+ }
222
+
223
+ /**
224
+ * Plate photo -> clean grayscale for OCR:
225
+ * 1. grayscale;
226
+ * 2. denoise, only when the photo is noisy (median neighbour difference), since blur costs sharp text;
227
+ * 3. flatten lighting: divide by a heavily blurred copy, which removes glare, shadows and the gradient
228
+ * across brushed metal and keeps text polarity (dark-on-light and light-on-dark plates both work);
229
+ * 4. stretch contrast (2nd–98th percentile).
230
+ * Each step was kept because it raised field accuracy in tests/nameplates-bench.mjs.
231
+ */
232
+ export function preprocess(src) {
233
+ const w = src.width, h = src.height, n = w * h;
234
+ const c = document.createElement('canvas');
235
+ c.width = w; c.height = h;
236
+ const g = c.getContext('2d', { willReadFrequently: true });
237
+ g.drawImage(src, 0, 0);
238
+ const im = g.getImageData(0, 0, w, h);
239
+ const d = im.data;
240
+ let gray = new Float32Array(n);
241
+ for (let i = 0, j = 0; j < n; i += 4, j++) gray[j] = d[i] * 0.299 + d[i + 1] * 0.587 + d[i + 2] * 0.114;
242
+
243
+ const noise = noiseLevel(gray, w, h);
244
+ if (noise > 4) gray = boxBlur(boxBlur(gray, w, h, noise > 12 ? 2 : 1), w, h, 1);
245
+
246
+ // Lighting estimate: a wide blur. Computing it at half or quarter resolution was tried and cost
247
+ // accuracy on the hardest photos (tests/nameplates-bench.mjs "phone": 98% -> 93%).
248
+ const R = Math.max(8, Math.round(Math.max(w, h) / 30));
249
+ const bg = boxBlur(boxBlur(gray, w, h, R), w, h, R);
250
+ const flat = new Float32Array(n);
251
+ for (let j = 0; j < n; j++) flat[j] = Math.min(255, (gray[j] / (bg[j] + 4)) * 128);
252
+
253
+ const hist = new Uint32Array(256);
254
+ for (let j = 0; j < n; j++) hist[flat[j] | 0]++;
255
+ let lo = 0, hi = 255, acc = 0;
256
+ for (; lo < 255 && (acc += hist[lo]) < n * 0.02; lo++);
257
+ acc = 0;
258
+ for (; hi > 0 && (acc += hist[hi]) < n * 0.02; hi--);
259
+ const span = Math.max(1, hi - lo);
260
+ for (let i = 0, j = 0; j < n; i += 4, j++) {
261
+ const v = Math.max(0, Math.min(255, ((flat[j] - lo) * 255) / span));
262
+ d[i] = d[i + 1] = d[i + 2] = v;
263
+ }
264
+ g.putImageData(im, 0, 0);
265
+ return deskew(c, d, w, h);
266
+ }
267
+
268
+ /**
269
+ * Straighten a plate shot at an angle: the text-line angle is the one whose row projection of
270
+ * text pixels is most peaked (lines of text in sharp rows, gaps between). Searched ±20° on a
271
+ * downsampled copy; Tesseract's own rotateAuto handles 90°/180° turns but not this.
272
+ */
273
+ function deskew(c, d, w, h) {
274
+ const hist = new Uint32Array(256);
275
+ for (let i = 0; i < d.length; i += 4) hist[d[i]]++;
276
+ let mode = 0;
277
+ for (let v = 1; v < 256; v++) if (hist[v] > hist[mode]) mode = v;
278
+ const step = Math.max(1, Math.round(Math.max(w, h) / 500));
279
+ const pts = [];
280
+ for (let y = 0; y < h; y += step) for (let x = 0; x < w; x += step) if (Math.abs(d[(y * w + x) * 4] - mode) > 90) pts.push(x, y);
281
+ if (pts.length < 200) return c;
282
+ const bins = Math.ceil((w + h) / step) + 2;
283
+ const peakiness = deg => {
284
+ const t = (deg * Math.PI) / 180, sin = Math.sin(t), cos = Math.cos(t), rows = new Float64Array(bins);
285
+ for (let i = 0; i < pts.length; i += 2) rows[((pts[i + 1] * cos - pts[i] * sin) / step + w / step) | 0]++;
286
+ let sum = 0;
287
+ for (const r of rows) sum += r * r;
288
+ return sum;
289
+ };
290
+ let best = 0, bestScore = peakiness(0);
291
+ for (let deg = -20; deg <= 20; deg += 1) { const sc = peakiness(deg); if (sc > bestScore) { bestScore = sc; best = deg; } }
292
+ for (let deg = best - 0.75; deg <= best + 0.75; deg += 0.25) { const sc = peakiness(deg); if (sc > bestScore) { bestScore = sc; best = deg; } }
293
+ if (Math.abs(best) < 1) return c;
294
+ const out = document.createElement('canvas');
295
+ out.width = w; out.height = h;
296
+ const g = out.getContext('2d');
297
+ g.fillStyle = `rgb(${mode},${mode},${mode})`;
298
+ g.fillRect(0, 0, w, h);
299
+ g.translate(w / 2, h / 2);
300
+ g.rotate((-best * Math.PI) / 180);
301
+ g.drawImage(c, -w / 2, -h / 2);
302
+ out.deskewAngle = best;
303
+ return out;
304
+ }
305
+
306
+ /** Median absolute difference between horizontal neighbours on every 3rd row: ~0–2 on a clean photo, 20+ on a grainy one. */
307
+ function noiseLevel(gray, w, h) {
308
+ const hist = new Uint32Array(256);
309
+ let count = 0;
310
+ for (let y = 1; y < h; y += 3) for (let x = 0, i = y * w; x < w - 1; x++, i++) { hist[Math.min(255, Math.abs(gray[i] - gray[i + 1]) | 0)]++; count++; }
311
+ let acc = 0;
312
+ for (let v = 0; v < 256; v++) if ((acc += hist[v]) >= count / 2) return v;
313
+ return 0;
314
+ }
315
+
316
+ /** Separable box blur with running sums, O(n) in the radius. */
317
+ function boxBlur(src, w, h, r) {
318
+ const tmp = new Float32Array(src.length), out = new Float32Array(src.length);
319
+ for (let y = 0; y < h; y++) {
320
+ const row = y * w;
321
+ let sum = 0;
322
+ for (let x = -r; x <= r; x++) sum += src[row + Math.min(w - 1, Math.max(0, x))];
323
+ for (let x = 0; x < w; x++) {
324
+ tmp[row + x] = sum / (2 * r + 1);
325
+ sum += src[row + Math.min(w - 1, x + r + 1)] - src[row + Math.max(0, x - r)];
326
+ }
327
+ }
328
+ for (let x = 0; x < w; x++) {
329
+ let sum = 0;
330
+ for (let y = -r; y <= r; y++) sum += tmp[Math.min(h - 1, Math.max(0, y)) * w + x];
331
+ for (let y = 0; y < h; y++) {
332
+ out[y * w + x] = sum / (2 * r + 1);
333
+ sum += tmp[Math.min(h - 1, y + r + 1) * w + x] - tmp[Math.max(0, y - r) * w + x];
334
+ }
335
+ }
336
+ return out;
337
+ }
338
+
339
+ /**
340
+ * OCR one image into a parsed reading. Pass 1 uses Tesseract's automatic layout (PSM 3). That
341
+ * occasionally classes a whole tilted plate as a picture and returns no text, and it drops lines
342
+ * on busy photos, so when pass 1 reads few fields a sparse-text pass (PSM 11) runs and the two
343
+ * merge field by field, keeping the more confident line. Only weak reads pay for the second pass.
344
+ */
345
+ async function ocrImage(src) {
346
+ const worker = await getWorker();
347
+ const img = preprocess(src);
348
+ const pass = async psm => {
349
+ await worker.setParameters({ tessedit_pageseg_mode: psm });
350
+ const { data } = await worker.recognize(img, { rotateAuto: true });
351
+ return parseNameplate((data.lines || []).map(l => ({ text: l.text, confidence: l.confidence, bbox: l.bbox })));
352
+ };
353
+ const first = await pass('3');
354
+ const reading = Object.keys(first.fields).length >= 6 && first.conf >= 70 ? first : mergeReadings(first, await pass('11'));
355
+ reading.deskew = img.deskewAngle || 0; // OCR boxes are in the straightened frame; draw() turns them back
356
+ return reading;
357
+ }
358
+
359
+ /** Two readings of one plate -> one: per field, the value from the more confident line. */
360
+ function mergeReadings(a, b) {
361
+ const base = Object.keys(b.fields).length > Object.keys(a.fields).length ? b : a;
362
+ const other = base === a ? b : a;
363
+ const offset = base.lines.length;
364
+ const fields = { ...base.fields };
365
+ for (const [k, f] of Object.entries(other.fields)) {
366
+ if (!fields[k] || f.conf > fields[k].conf + 5) fields[k] = { ...f, line: f.line + offset };
367
+ }
368
+ return { ...base, fields, type: base.type || other.type, lines: [...base.lines, ...other.lines] };
369
+ }
370
+
371
+ // Hooks for tests/nameplates-bench.mjs: OCR an arbitrary canvas, draw a sample plate.
372
+ window.__nameplates = { ocrImage, samplePlate, getWorker, fitForOcr, preprocess };
373
+
374
+ async function read() {
375
+ if (!state.image) return;
376
+ els.run.disabled = true;
377
+ setProgress(0.02);
378
+ try {
379
+ setStatus('Loading the OCR engine (first read only)…');
380
+ onOcrProgress = m => {
381
+ if (m.status === 'recognizing text') { setProgress(0.3 + 0.7 * m.progress); setStatus('Reading the plate…'); }
382
+ else if (/load|initializ/.test(m.status)) { setProgress(0.05 + 0.25 * (m.progress || 0)); setStatus(`${m.status[0].toUpperCase()}${m.status.slice(1)}…`); }
383
+ };
384
+ state.reading = await ocrImage(state.image);
385
+ setProgress(1);
386
+ const found = Object.keys(state.reading.fields).length;
387
+ setStatus(found ? `Read ${found} field${found === 1 ? '' : 's'} at ${state.reading.conf}% average OCR confidence. Check them against the plate.` :
388
+ 'No nameplate fields were recognised. Try a closer, straighter photo, or rotate it.', !found);
389
+ rematch(true);
390
+ } catch (e) {
391
+ setStatus(`OCR failed: ${e.message}. It needs a network connection the first time.`, true);
392
+ } finally {
393
+ els.run.disabled = false;
394
+ }
395
+ }
396
+
397
+ // ------------------------------------------------------------------ reading
398
+ function rematch(pickBest = false) {
399
+ const r = state.reading;
400
+ if (!r) return;
401
+ const items = state.schedule?.items || [];
402
+ state.candidates = candidatesFor(r, items, state.register);
403
+ if (pickBest || !items.some(i => i.tag === state.tag)) state.tag = state.candidates[0]?.item.tag || '';
404
+ renderReading();
405
+ draw();
406
+ }
407
+
408
+ function currentChecks() {
409
+ const item = state.schedule?.items.find(i => i.tag === state.tag);
410
+ return item ? checkAgainst(state.reading, item) : [];
411
+ }
412
+
413
+ function renderReading() {
414
+ const r = state.reading;
415
+ els.reading.hidden = !r;
416
+ if (!r) return;
417
+ els.text.textContent = r.text || '(no text)';
418
+ // Fields: editable, low-confidence ones highlighted.
419
+ const typeOpts = ['<option value="">Unknown</option>', ...EQUIPMENT_TYPES.map(([k, label]) => `<option value="${k}"${r.type === k ? ' selected' : ''}>${esc(label)}</option>`)].join('');
420
+ els.fields.innerHTML = `<label for="npf-type">Type</label><select id="npf-type">${typeOpts}</select>` +
421
+ FIELDS.map(([k, label]) => {
422
+ const f = r.fields[k];
423
+ const low = f && !f.edited && f.conf < LOW_CONF;
424
+ return `<label for="npf-${k}"><span class="np-key" style="background:${f ? COLORS[k] : 'transparent'}"></span>${esc(label)}</label>` +
425
+ `<input id="npf-${k}" data-key="${k}" value="${esc(f?.value ?? '')}" ${low ? `class="low" title="OCR confidence ${f.conf}%: check against the plate"` : ''} autocomplete="off" spellcheck="false" />`;
426
+ }).join('');
427
+
428
+ // Tag picker: likely tags first, then the rest of the schedule.
429
+ const items = state.schedule?.items || [];
430
+ const cand = new Set(state.candidates.map(c => c.item.tag));
431
+ const opt = (i, extra = '') => `<option value="${esc(i.tag)}"${i.tag === state.tag ? ' selected' : ''}>${esc(i.tag)}${i.model ? ` · ${esc(i.model)}` : ''}${extra}</option>`;
432
+ els.tag.innerHTML = `<option value=""${state.tag ? '' : ' selected'}>Not on the schedule</option>` +
433
+ (state.candidates.length ? `<optgroup label="Likely matches">${state.candidates.map(c => opt(c.item, c.registered ? ' (already scanned)' : '')).join('')}</optgroup>` : '') +
434
+ (items.length > cand.size ? `<optgroup label="All scheduled items">${items.filter(i => !cand.has(i.tag)).map(i => opt(i)).join('')}</optgroup>` : '');
435
+ els.tag.disabled = !items.length;
436
+ const same = state.candidates.filter(c => c.score === state.candidates[0]?.score).length;
437
+ els.tagNote.textContent = !items.length ? 'Load an equipment schedule to check this plate.'
438
+ : !state.candidates.length ? 'No scheduled item looks like this plate.'
439
+ : same > 1 ? `${same} scheduled items share this model. Picked the first not yet scanned; change it to the tag on site.`
440
+ : '';
441
+ if (state.register.some(x => x.tag && x.tag === state.tag)) els.tagNote.textContent += ` ${state.tag} is already on the register; adding replaces it.`;
442
+ renderChecks();
443
+ }
444
+
445
+ function renderChecks() {
446
+ const checks = currentChecks();
447
+ const status = statusOf(checks, state.tag);
448
+ els.checks.innerHTML = checks.map(c => `<li class="${c.status}"><span>${c.status === 'ok' ? '✓' : c.status === 'mismatch' ? '✗' : '–'}</span>` +
449
+ `<span><b>${esc(c.label)}</b> ${c.status === 'ok' ? esc(c.found) : c.status === 'mismatch' ? `schedule ${esc(c.expected)}, plate ${esc(c.found)}` : `not read (schedule ${esc(c.expected)})`}</span></li>`).join('');
450
+ const bad = checks.filter(c => c.status === 'mismatch').map(c => inSentence(c.label));
451
+ els.verdict.className = `np-verdict ${status}`;
452
+ els.verdict.textContent = status === 'verified' ? `Matches ${state.tag} on every scheduled field.`
453
+ : status === 'mismatch' ? `Does not match ${state.tag}: ${bad.join(', ')}. Hold before install.`
454
+ : status === 'partial' ? `Matches ${state.tag} so far; some scheduled fields were not read.`
455
+ : state.schedule ? 'Not matched to the schedule.' : 'Read only: no schedule loaded to check against.';
456
+ }
457
+
458
+ function editField(key, raw) {
459
+ const r = state.reading;
460
+ const v = raw.trim();
461
+ if (!v) delete r.fields[key];
462
+ else if (key === 'voltage') r.fields.voltage = { value: v, conf: 100, edited: true, values: voltagesIn(v.toUpperCase()).values.length ? voltagesIn(v.toUpperCase()).values : (v.match(/\d{3,5}/g) || []).map(Number) };
463
+ else r.fields[key] = { value: NUMERIC.has(key) ? (parseFloat(v.replace(',', '')) || v) : v, conf: 100, edited: true, line: r.fields[key]?.line };
464
+ $(`npf-${key}`)?.classList.remove('low');
465
+ if (key === 'model' || key === 'serial' || key === 'manufacturer') {
466
+ state.candidates = candidatesFor(r, state.schedule?.items || [], state.register);
467
+ }
468
+ renderChecks();
469
+ }
470
+
471
+ // ------------------------------------------------------------------ canvas
472
+ function draw() {
473
+ const c = els.canvas, s = state.image;
474
+ els.empty.hidden = !!s;
475
+ c.hidden = !s;
476
+ if (!s) return;
477
+ c.width = s.width; c.height = s.height;
478
+ const g = c.getContext('2d');
479
+ g.drawImage(s, 0, 0);
480
+ const r = state.reading;
481
+ if (!r) return;
482
+ // Outline each line a field came from, labelled with every field read off it (voltage, phase
483
+ // and Hz often share one line). Boxes are in the straightened frame OCR saw: rotate them back.
484
+ const byLine = new Map();
485
+ for (const [k, f] of Object.entries(r.fields)) {
486
+ if (f.edited || !r.lines[f.line]?.bbox) continue;
487
+ byLine.set(f.line, [...(byLine.get(f.line) || []), k]);
488
+ }
489
+ const lw = Math.max(2, s.width / 450), fs = Math.round(Math.max(14, s.width / 60)), pad = fs * 0.3;
490
+ g.save();
491
+ g.translate(s.width / 2, s.height / 2);
492
+ g.rotate(((r.deskew || 0) * Math.PI) / 180);
493
+ g.translate(-s.width / 2, -s.height / 2);
494
+ g.font = `600 ${fs}px system-ui, sans-serif`;
495
+ g.textBaseline = 'middle';
496
+ for (const [line, keys] of byLine) {
497
+ const b = r.lines[line].bbox;
498
+ g.strokeStyle = COLORS[keys[0]]; g.lineWidth = lw;
499
+ g.strokeRect(b.x0 - 4, b.y0 - 4, b.x1 - b.x0 + 8, b.y1 - b.y0 + 8);
500
+ let x = b.x0 - 4;
501
+ for (const k of keys) {
502
+ const label = FIELDS.find(f => f[0] === k)?.[1] || k;
503
+ const tw = g.measureText(label).width + pad * 2, th = fs + pad * 1.4, y = Math.max(0, b.y0 - 4 - th);
504
+ g.fillStyle = COLORS[k]; g.fillRect(x, y, tw, th);
505
+ g.fillStyle = '#fff'; g.fillText(label, x + pad, y + th / 2);
506
+ x += tw + 3;
507
+ }
508
+ }
509
+ g.restore();
510
+ }
511
+
512
+ // ------------------------------------------------------------------ register
513
+ function addToRegister({ quiet = false } = {}) {
514
+ const r = state.reading;
515
+ if (!r) return;
516
+ const checks = currentChecks();
517
+ const prev = state.editing && state.register.find(x => x.id === state.editing);
518
+ const entry = {
519
+ id: prev?.id || `np-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
520
+ tag: state.tag, type: $('npf-type')?.value ?? r.type ?? '', fields: structuredClone(r.fields),
521
+ checks, status: statusOf(checks, state.tag), thumb: prev?.thumb || thumbnail(state.image),
522
+ scannedAt: prev?.scannedAt || Date.now(), source: r.source || prev?.source || '',
523
+ // Fields OCR was unsure of and nobody has corrected: listed on the register for a second look.
524
+ lowConf: Object.entries(r.fields).filter(([, f]) => !f.edited && f.conf < LOW_CONF).map(([k, f]) => `${k}:${f.conf}`),
525
+ };
526
+ for (const f of Object.values(entry.fields)) { delete f.line; }
527
+ state.photos.set(entry.id, { image: state.image, reading: structuredClone(r) });
528
+ const at = prev ? state.register.indexOf(prev) : -1;
529
+ state.register = state.register.filter(x => x.id !== entry.id && !(entry.tag && x.tag === entry.tag));
530
+ if (at >= 0) state.register.splice(Math.min(at, state.register.length), 0, entry);
531
+ else state.register.push(entry);
532
+ save();
533
+ renderRegister();
534
+ if (!quiet) setStatus(`${entry.tag || 'Unmatched plate'} ${prev ? 'updated on' : 'added to'} the register (${STATUS_LABELS[entry.status].toLowerCase()}).`);
535
+ state.editing = null;
536
+ els.add.textContent = 'Add to register';
537
+ state.reading = null;
538
+ els.reading.hidden = true;
539
+ draw();
540
+ }
541
+
542
+ /** Open a register entry for review: its photo and reading if read this session, else its stored fields over the thumbnail. */
543
+ async function review(id) {
544
+ const entry = state.register.find(x => x.id === id);
545
+ if (!entry) return;
546
+ const photo = state.photos.get(id);
547
+ if (photo) {
548
+ state.image = photo.image;
549
+ state.reading = structuredClone(photo.reading);
550
+ state.reading.fields = structuredClone(entry.fields);
551
+ for (const [k, f] of Object.entries(state.reading.fields)) f.line = photo.reading.fields[k]?.line;
552
+ } else {
553
+ const img = new Image();
554
+ img.src = entry.thumb;
555
+ try { await img.decode(); state.image = fitForOcr(img, img.naturalWidth, img.naturalHeight); } catch { state.image = null; }
556
+ state.reading = { fields: structuredClone(entry.fields), type: entry.type, conf: 100, text: '', lines: [] };
557
+ }
558
+ state.reading.type = entry.type || state.reading.type;
559
+ state.editing = id;
560
+ state.candidates = candidatesFor(state.reading, state.schedule?.items || [], state.register.filter(x => x.id !== id));
561
+ state.tag = entry.tag;
562
+ els.add.textContent = 'Update register entry';
563
+ els.run.disabled = !state.image;
564
+ els.rotate.disabled = !state.image;
565
+ renderReading();
566
+ draw();
567
+ renderRegister();
568
+ els.reading.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
569
+ setStatus(`Reviewing ${entry.tag || 'an unmatched plate'}. Correct any field, then update the entry.`);
570
+ }
571
+
572
+ function thumbnail(src) {
573
+ const c = document.createElement('canvas');
574
+ const s = 240 / Math.max(src.width, src.height);
575
+ c.width = Math.round(src.width * s); c.height = Math.round(src.height * s);
576
+ c.getContext('2d').drawImage(src, 0, 0, c.width, c.height);
577
+ return c.toDataURL('image/jpeg', 0.7);
578
+ }
579
+
580
+ function renderRegister() {
581
+ const items = state.schedule?.items || [];
582
+ const sum = registerSummary(state.register, items);
583
+ const dups = new Set(duplicateSerials(state.register).flat());
584
+ els.summary.innerHTML = state.register.length || items.length ? [
585
+ items.length ? `<span><b>${sum.scannedOfSchedule}</b> of ${items.length} scheduled scanned</span>` : `<span><b>${sum.scanned}</b> scanned</span>`,
586
+ `<span><b>${sum.verified}</b> verified</span>`,
587
+ `<span style="color:${sum.flagged ? 'var(--danger)' : 'inherit'}"><b>${sum.flagged}</b> flagged</span>`,
588
+ sum.unmatched ? `<span><b>${sum.unmatched}</b> not on schedule</span>` : '',
589
+ sum.duplicates ? `<span style="color:var(--danger)"><b>${sum.duplicates}</b> duplicate serial${sum.duplicates === 1 ? '' : 's'}</span>` : '',
590
+ ].join('') : '';
591
+ els.rows.innerHTML = state.register.map(r => {
592
+ const issues = r.checks.filter(c => c.status === 'mismatch').map(c => `${c.label}: schedule ${c.expected}, plate ${c.found}`);
593
+ if (dups.has(r.id)) issues.push('Serial also on another scanned plate');
594
+ if (r.lowConf?.length) issues.push(`Check ${r.lowConf.map(x => { const [k, c] = x.split(':'); return `${inSentence((FIELDS.find(f => f[0] === k) || [k, k])[1])} (OCR ${c}%)`; }).join(', ')}`);
595
+ return `<tr data-id="${r.id}" class="${r.id === state.editing ? 'sel' : ''}" tabindex="0" title="Review this plate"><td class="np-hide-sm">${r.thumb ? `<img src="${r.thumb}" alt="">` : ''}</td>` +
596
+ `<td><b>${esc(r.tag || '—')}</b><br><span class="np-note">${esc(typeLabel(r.type))}</span></td>` +
597
+ `<td><span class="np-chip ${r.status}">${esc(STATUS_LABELS[r.status])}</span></td>` +
598
+ `<td>${esc(r.fields.model?.value || '')}</td><td class="np-hide-sm">${esc(r.fields.serial?.value || '')}</td>` +
599
+ `<td class="np-hide-sm">${esc(r.fields.voltage?.value || '')}</td><td>${esc(issues.join('; '))}</td>` +
600
+ `<td><button class="np-btn link" type="button" data-remove="${r.id}" aria-label="Remove ${esc(r.tag || 'entry')}">✕</button></td></tr>`;
601
+ }).join('');
602
+ els.emptyReg.hidden = state.register.length > 0;
603
+ els.csv.disabled = !state.register.length && !items.length;
604
+ els.clearReg.disabled = !state.register.length;
605
+ els.missing.textContent = items.length && sum.missing.length && state.register.length
606
+ ? `Not scanned yet (${sum.missing.length}): ${sum.missing.slice(0, 24).join(', ')}${sum.missing.length > 24 ? '…' : ''}` : '';
607
+ }
608
+
609
+ function download(name, text, type) {
610
+ const a = document.createElement('a');
611
+ a.href = URL.createObjectURL(new Blob([text], { type }));
612
+ a.download = name;
613
+ a.click();
614
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000);
615
+ }
616
+
617
+ // ------------------------------------------------------------------ wiring
618
+ function dropZone(zone, input, onFile, onFiles) {
619
+ const take = list => { const files = [...list]; if (files.length > 1 && onFiles) onFiles(files); else if (files[0]) onFile(files[0]); };
620
+ input.addEventListener('change', () => { take(input.files); input.value = ''; });
621
+ zone.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); input.click(); } });
622
+ zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('over'); });
623
+ zone.addEventListener('dragleave', () => zone.classList.remove('over'));
624
+ zone.addEventListener('drop', e => { e.preventDefault(); zone.classList.remove('over'); take(e.dataTransfer.files); });
625
+ }
626
+
627
+ dropZone(els.schedDrop, els.schedFile, async f => setSchedule(await f.text(), f.name));
628
+ dropZone(els.drop, els.file, loadImageFile, files => readBatch(files.filter(f => /^image\//.test(f.type) || /\.(jpe?g|png|webp|heic|gif|bmp)$/i.test(f.name))));
629
+ els.schedSample.addEventListener('click', () => setSchedule(SAMPLE_SCHEDULE, 'Sample schedule'));
630
+ els.schedClear.addEventListener('click', () => { state.schedule = null; save(); renderSchedule(); rematch(); renderRegister(); });
631
+ els.sample.addEventListener('click', () => {
632
+ const c = samplePlate(SAMPLE_PLATES[state.sample % SAMPLE_PLATES.length]);
633
+ state.sample++;
634
+ setImage(c, c.width, c.height);
635
+ setStatus(`Sample plate ${((state.sample - 1) % SAMPLE_PLATES.length) + 1} of ${SAMPLE_PLATES.length} loaded (a drawn plate, fictional maker). Read it when ready.`);
636
+ });
637
+ els.rotate.addEventListener('click', rotate);
638
+ els.run.addEventListener('click', read);
639
+ els.add.addEventListener('click', () => addToRegister());
640
+ els.tag.addEventListener('change', () => { state.tag = els.tag.value; renderReading(); });
641
+ els.fields.addEventListener('change', e => {
642
+ if (e.target.id === 'npf-type') { state.reading.type = e.target.value || null; state.candidates = candidatesFor(state.reading, state.schedule?.items || [], state.register); renderReading(); }
643
+ else if (e.target.dataset.key) editField(e.target.dataset.key, e.target.value);
644
+ });
645
+ els.rows.addEventListener('click', e => {
646
+ const id = e.target.closest('[data-remove]')?.dataset.remove;
647
+ if (id) {
648
+ state.register = state.register.filter(r => r.id !== id);
649
+ state.photos.delete(id);
650
+ if (state.editing === id) { state.editing = null; state.reading = null; els.reading.hidden = true; els.add.textContent = 'Add to register'; }
651
+ save();
652
+ renderRegister();
653
+ return;
654
+ }
655
+ const row = e.target.closest('tr[data-id]');
656
+ if (row) review(row.dataset.id);
657
+ });
658
+ els.rows.addEventListener('keydown', e => {
659
+ const row = e.target.closest('tr[data-id]');
660
+ if (row && (e.key === 'Enter' || e.key === ' ') && !e.target.closest('button')) { e.preventDefault(); review(row.dataset.id); }
661
+ });
662
+ els.clearReg.addEventListener('click', () => {
663
+ if (!confirm('Remove every scanned plate from the register?')) return;
664
+ state.register = [];
665
+ save();
666
+ renderRegister();
667
+ });
668
+ els.csv.addEventListener('click', () => download('asset-register.csv', registerCsv(state.register, state.schedule?.items || []), 'text/csv'));
669
+
670
+ load();
671
+ renderSchedule();
672
+ renderRegister();
og-nameplates.png ADDED
progress-project.js ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Project-level progress for Progress mode: the layer Buildots puts on top of
2
+ // per-area stage reads — where each area sits on the floor plan, whether it is
3
+ // ahead of or behind its planned dates, which areas nobody has walked lately,
4
+ // and one report across every area and trade.
5
+ //
6
+ // Progress mode already stores, per named area, a plan (what the area should
7
+ // contain) and dated captures (overall % and per-trade items, from
8
+ // rollupProgress). This module only reads that store plus three optional
9
+ // fields per area, all entered by the user — BuildVision has no BIM and no
10
+ // schedule import:
11
+ //
12
+ // area.schedule = { start, finish, trades?: { [itemKey]: { start, finish } } } (ms timestamps)
13
+ // area.floor = 'L3' (else parsed from the area name: "L3 east corridor")
14
+ // area.pin = { plan, x, y } (plan id, x/y as 0..1 of the plan image)
15
+ //
16
+ // and store.plans = { [id]: { name, image } } for the floor-plan images.
17
+ //
18
+ // Planned progress is linear between an area's start and finish — the same
19
+ // straight-line reading a Gantt bar gives, not a resource-loaded curve — and
20
+ // the UI says so. Everything here is a pure function (tests/progress-project.test.mjs).
21
+
22
+ const DAY = 86400000;
23
+ export const ON_TRACK_POINTS = 5; // |actual − planned| within this many points reads as on track
24
+ export const STALE_DAYS = 7; // an unfinished area not captured in this long is flagged
25
+ export const SLIP_TOLERANCE_DAYS = 2;
26
+
27
+ export const STATUS = {
28
+ complete: { label: 'Complete', color: '#2f9e44', rank: 0 },
29
+ ahead: { label: 'Ahead', color: '#1c7ed6', rank: 1 },
30
+ on_track: { label: 'On track', color: '#74b816', rank: 2 },
31
+ at_risk: { label: 'At risk', color: '#f59f00', rank: 4 },
32
+ behind: { label: 'Behind', color: '#e03131', rank: 5 },
33
+ not_started_late: { label: 'Should have started', color: '#c2255c', rank: 6 },
34
+ not_captured: { label: 'Not captured', color: '#868e96', rank: 3 },
35
+ unscheduled: { label: 'No schedule', color: '#868e96', rank: 3 },
36
+ };
37
+
38
+ const latestCapture = rec => {
39
+ const caps = (rec?.captures || []).filter(c => Number.isFinite(c.time));
40
+ return caps.length ? caps.reduce((a, b) => (b.time > a.time ? b : a)) : null;
41
+ };
42
+
43
+ /** Planned % complete at time t for a { start, finish } window: 0 before, 100 after, linear between. */
44
+ export function plannedPctAt(window, t) {
45
+ if (!window || !Number.isFinite(window.start) || !Number.isFinite(window.finish) || window.finish <= window.start) return null;
46
+ if (t <= window.start) return 0;
47
+ if (t >= window.finish) return 100;
48
+ return Math.round(((t - window.start) / (window.finish - window.start)) * 100);
49
+ }
50
+
51
+ /**
52
+ * Least-squares production rate (points/day) over captures; null without two captures a day apart.
53
+ * Same fit forecastCompletion uses, repeated here so this module stands alone.
54
+ */
55
+ function productionRate(captures) {
56
+ const pts = (captures || []).filter(c => c.overall != null && Number.isFinite(c.time)).map(c => [c.time / DAY, c.overall]);
57
+ if (pts.length < 2) return null;
58
+ const xs = pts.map(p => p[0]);
59
+ if (Math.max(...xs) - Math.min(...xs) < 1) return null;
60
+ const mx = xs.reduce((s, x) => s + x, 0) / pts.length, my = pts.reduce((s, p) => s + p[1], 0) / pts.length;
61
+ const sxx = pts.reduce((s, p) => s + (p[0] - mx) ** 2, 0);
62
+ return pts.reduce((s, p) => s + (p[0] - mx) * (p[1] - my), 0) / sxx;
63
+ }
64
+
65
+ /**
66
+ * Planned vs actual for one window and one actual reading taken at `at`.
67
+ * daysBehind is schedule time: how long ago the plan expected today's actual %
68
+ * (positive = behind, negative = ahead) — the number a superintendent quotes.
69
+ */
70
+ function varianceOf(window, actual, at) {
71
+ const planned = plannedPctAt(window, at);
72
+ if (planned == null || actual == null) return { planned, actual, variancePts: null, daysBehind: null };
73
+ const whenPlanned = window.start + (Math.min(100, actual) / 100) * (window.finish - window.start);
74
+ return { planned, actual, variancePts: actual - planned, daysBehind: Math.round((at - whenPlanned) / DAY) };
75
+ }
76
+
77
+ /**
78
+ * Where one area stands against its schedule, from its latest capture.
79
+ * Status precedence: complete > (no schedule) > should-have-started > behind > at risk > ahead > on track.
80
+ * "At risk" = within the on-track band today but the production rate lands
81
+ * the finish more than SLIP_TOLERANCE_DAYS after the planned finish.
82
+ */
83
+ export function areaStatus(rec, now = Date.now(), { staleDays = STALE_DAYS } = {}) {
84
+ const last = latestCapture(rec);
85
+ const schedule = rec?.schedule;
86
+ const actual = last?.overall ?? null;
87
+ const lastCaptureDays = last ? Math.floor((now - last.time) / DAY) : null;
88
+ const complete = actual != null && actual >= 100;
89
+ const stale = !complete && last != null && lastCaptureDays > staleDays;
90
+ const base = { actual, lastCapture: last?.time ?? null, lastCaptureDays, stale, captures: (rec?.captures || []).length, items: last?.items || [] };
91
+
92
+ const rate = productionRate(rec?.captures);
93
+ let projectedFinish = null;
94
+ if (complete) projectedFinish = last.time;
95
+ else if (rate > 0.05 && last) projectedFinish = Math.max(now, last.time + ((100 - actual) / rate) * DAY);
96
+ const withSchedule = Number.isFinite(schedule?.start) && Number.isFinite(schedule?.finish) && schedule.finish > schedule.start;
97
+ const plannedFinish = withSchedule ? schedule.finish : null;
98
+ const slipDays = projectedFinish != null && plannedFinish != null ? Math.round((projectedFinish - plannedFinish) / DAY) : null;
99
+ const trades = tradeStatus(rec, last);
100
+
101
+ if (complete) return { ...base, status: 'complete', planned: withSchedule ? plannedPctAt(schedule, now) : null,
102
+ variancePts: null, daysBehind: null, rate, projectedFinish, plannedFinish, slipDays, trades };
103
+ if (!withSchedule) {
104
+ return { ...base, status: last ? 'unscheduled' : 'not_captured', planned: null, variancePts: null, daysBehind: null,
105
+ rate, projectedFinish, plannedFinish: null, slipDays: null, trades };
106
+ }
107
+ if (!last) {
108
+ const planned = plannedPctAt(schedule, now);
109
+ return { ...base, status: now > schedule.start ? 'not_started_late' : 'not_captured', planned, variancePts: null,
110
+ daysBehind: now > schedule.start ? Math.round((now - schedule.start) / DAY) : null, rate, projectedFinish, plannedFinish, slipDays, trades };
111
+ }
112
+ // Judge the latest capture against the plan *at that capture's date*: a
113
+ // week-old 40% is not "behind" today's 70% plan by 30 points, it is stale.
114
+ const v = varianceOf(schedule, actual, last.time);
115
+ let status;
116
+ if (v.variancePts < -ON_TRACK_POINTS) status = 'behind';
117
+ else if (slipDays != null && slipDays > SLIP_TOLERANCE_DAYS) status = 'at_risk';
118
+ else if (rate != null && !(rate > 0.05) && plannedPctAt(schedule, now) > actual + ON_TRACK_POINTS) status = 'at_risk'; // stalled
119
+ else if (v.variancePts > ON_TRACK_POINTS) status = 'ahead';
120
+ else status = 'on_track';
121
+ return { ...base, status, ...v, rate, projectedFinish, plannedFinish, slipDays, trades };
122
+ }
123
+
124
+ /** Per-trade variance for trades that have their own planned window. */
125
+ function tradeStatus(rec, last) {
126
+ const windows = rec?.schedule?.trades || {};
127
+ return (last?.items || []).filter(i => windows[i.key]).map(i => {
128
+ const v = varianceOf(windows[i.key], i.pct ?? null, last.time);
129
+ const status = i.pct >= 100 ? 'complete' : v.variancePts == null ? 'not_captured'
130
+ : v.variancePts < -ON_TRACK_POINTS ? 'behind' : v.variancePts > ON_TRACK_POINTS ? 'ahead' : 'on_track';
131
+ return { key: i.key, trade: i.trade, status, ...v };
132
+ });
133
+ }
134
+
135
+ /** "L3", "Level 3", "Floor 03", "3F", "B1", "Basement 2" at the start of an area name → a floor key. */
136
+ export function floorOf(name, rec) {
137
+ if (rec?.floor) return String(rec.floor).trim();
138
+ const s = String(name || '').trim();
139
+ let m = s.match(/^(?:l|lvl|level|fl|floor)\s*-?\s*0*(\d+)\b/i) || s.match(/^0*(\d+)\s*(?:f|fl)\b/i);
140
+ if (m) return `L${Number(m[1])}`;
141
+ m = s.match(/^(?:b|basement)\s*-?\s*0*(\d+)\b/i);
142
+ if (m) return `B${Number(m[1])}`;
143
+ if (/^(?:roof|rf)\b/i.test(s)) return 'Roof';
144
+ if (/^(?:ground|gf|g)\b/i.test(s)) return 'L0';
145
+ return 'Unassigned';
146
+ }
147
+
148
+ const floorOrder = f => (f === 'Unassigned' ? 1e6 : f === 'Roof' ? 1e5 : f[0] === 'B' ? -Number(f.slice(1)) : Number(f.slice(1)) || 0);
149
+
150
+ /**
151
+ * Every area, rolled up: per-area status, per-floor and per-trade averages from
152
+ * each area's latest capture, and an attention list (behind / at risk / late
153
+ * starts / stale) ordered worst first. Averages count captured areas only and
154
+ * say how many they cover, so one captured room is never presented as the floor.
155
+ */
156
+ export function projectRollup(store, now = Date.now(), opts = {}) {
157
+ const areas = Object.entries(store?.areas || {}).map(([name, rec]) => ({
158
+ name, floor: floorOf(name, rec), pin: rec.pin || null, ...areaStatus(rec, now, opts),
159
+ }));
160
+ const captured = areas.filter(a => a.actual != null);
161
+ const mean = xs => (xs.length ? Math.round(xs.reduce((s, x) => s + x, 0) / xs.length) : null);
162
+
163
+ const floors = {};
164
+ for (const a of areas) {
165
+ const f = (floors[a.floor] ||= { floor: a.floor, areas: 0, captured: 0, pcts: [], behind: 0, atRisk: 0, stale: 0 });
166
+ f.areas += 1;
167
+ if (a.actual != null) { f.captured += 1; f.pcts.push(a.actual); }
168
+ if (a.status === 'behind' || a.status === 'not_started_late') f.behind += 1;
169
+ if (a.status === 'at_risk') f.atRisk += 1;
170
+ if (a.stale) f.stale += 1;
171
+ }
172
+ const floorList = Object.values(floors).map(({ pcts, ...f }) => ({ ...f, pct: mean(pcts) }))
173
+ .sort((a, b) => floorOrder(a.floor) - floorOrder(b.floor));
174
+
175
+ const tradeAcc = {};
176
+ for (const [name, rec] of Object.entries(store?.areas || {})) {
177
+ const last = latestCapture(rec);
178
+ (last?.items || []).forEach(i => {
179
+ if (i.pct == null) return;
180
+ const t = (tradeAcc[i.key] ||= { key: i.key, trade: i.trade, pcts: [], areas: [] });
181
+ t.pcts.push(i.pct); t.areas.push(name);
182
+ });
183
+ }
184
+ const trades = Object.values(tradeAcc).map(t => ({ key: t.key, trade: t.trade, pct: mean(t.pcts), areas: t.areas.length,
185
+ complete: t.pcts.filter(p => p >= 100).length }));
186
+
187
+ const counts = Object.fromEntries(Object.keys(STATUS).map(k => [k, 0]));
188
+ areas.forEach(a => { counts[a.status] += 1; });
189
+ const attention = areas
190
+ .filter(a => ['behind', 'at_risk', 'not_started_late'].includes(a.status) || a.stale || a.trades?.some(t => t.status === 'behind'))
191
+ .map(a => ({ name: a.name, floor: a.floor, status: a.status, stale: a.stale, daysBehind: a.daysBehind, slipDays: a.slipDays,
192
+ lastCaptureDays: a.lastCaptureDays, reason: attentionReason(a) }))
193
+ .sort((a, b) => STATUS[b.status].rank - STATUS[a.status].rank || (b.daysBehind ?? 0) - (a.daysBehind ?? 0)
194
+ || (b.lastCaptureDays ?? 0) - (a.lastCaptureDays ?? 0));
195
+
196
+ return { areas, floors: floorList, trades, counts, attention, overall: mean(captured.map(a => a.actual)),
197
+ capturedAreas: captured.length, totalAreas: areas.length };
198
+ }
199
+
200
+ function attentionReason(a) {
201
+ const parts = [];
202
+ if (a.status === 'behind') parts.push(`${a.actual}% vs ${a.planned}% planned at last capture (${a.daysBehind} day${a.daysBehind === 1 ? '' : 's'} behind)`);
203
+ if (a.status === 'not_started_late') parts.push(`planned to start ${a.daysBehind} day${a.daysBehind === 1 ? '' : 's'} ago, never captured`);
204
+ if (a.status === 'at_risk') parts.push(a.slipDays != null ? `current rate finishes ${a.slipDays} days after the planned finish` : 'no progress between recent captures');
205
+ const lateTrades = (a.trades || []).filter(t => t.status === 'behind');
206
+ if (lateTrades.length) parts.push(`trade${lateTrades.length === 1 ? '' : 's'} behind: ${lateTrades.map(t => `${t.trade} ${t.actual}% vs ${t.planned}% (${t.daysBehind} day${t.daysBehind === 1 ? '' : 's'})`).join(', ')}`);
207
+ if (a.stale) parts.push(`last captured ${a.lastCaptureDays} days ago`);
208
+ return parts.join('; ');
209
+ }
210
+
211
+ // ---------- quantities from a scaled floor plan ----------
212
+ //
213
+ // With a plan scale (feet per plan pixel, from two clicked points and a known
214
+ // distance) and the room each area is pinned in, a stage read becomes square
215
+ // feet: floor area from the room polygon, wall area from its perimeter × the
216
+ // ceiling height. Stage → how far along the trade sequence the surface is.
217
+ // This is the room outline as drawn (interior partitions inside a room, and
218
+ // openings, are not deducted) — a progress quantity, not a takeoff.
219
+
220
+ const STAGE_PCT = { wall_framing: 25, wall_board: 50, wall_taped: 75, wall_finished: 100,
221
+ ceiling_open: 33, ceiling_grid: 67, ceiling_finished: 100 };
222
+ export const WALL_MILESTONES = [['Framed', 25], ['Board hung', 50], ['Taped & mudded', 75], ['Finished', 100]];
223
+ export const CEILING_MILESTONES = [['Grid hung', 67], ['Closed', 100]];
224
+
225
+ /** Shoelace area and perimeter of a 0..1 polygon on a W×H plan, in plan pixels. */
226
+ export function polygonMetrics(poly, W, H) {
227
+ let a = 0, per = 0;
228
+ for (let i = 0; i < poly.length; i++) {
229
+ const [x1, y1] = poly[i], [x2, y2] = poly[(i + 1) % poly.length];
230
+ a += x1 * W * y2 * H - x2 * W * y1 * H;
231
+ per += Math.hypot((x2 - x1) * W, (y2 - y1) * H);
232
+ }
233
+ return { area: Math.abs(a) / 2, perimeter: per };
234
+ }
235
+
236
+ /**
237
+ * Square feet per pinned, measurable area and totals by milestone: how much
238
+ * wall has reached "board hung" or beyond, how much ceiling is closed, etc.
239
+ * Areas without a scaled plan, a detected room around the pin, or a reading
240
+ * are listed as unmeasured rather than guessed.
241
+ */
242
+ export function areaQuantities(rollup, plans = {}, { ceilingHeightFt = 9 } = {}) {
243
+ const perArea = [], unmeasured = [];
244
+ for (const a of rollup.areas) {
245
+ const plan = a.pin && plans[a.pin.plan];
246
+ const room = plan?.rooms && roomAt(plan.rooms, a.pin.x, a.pin.y);
247
+ if (!plan?.scale?.ftPerPx || !plan.size || !room) { unmeasured.push(a.name); continue; }
248
+ const m = polygonMetrics(room.poly, plan.size.w, plan.size.h);
249
+ const f = plan.scale.ftPerPx;
250
+ const wall = a.items.find(i => i.key === 'wall'), ceiling = a.items.find(i => i.key === 'ceiling');
251
+ perArea.push({ name: a.name, floorSf: Math.round(m.area * f * f), wallSf: Math.round(m.perimeter * f * ceilingHeightFt),
252
+ wallStage: wall?.stage || null, ceilingStage: ceiling?.stage || null });
253
+ }
254
+ const sumBy = (key, stageKey, milestones) => {
255
+ const total = perArea.reduce((s, q) => s + q[key], 0);
256
+ const read = perArea.filter(q => q[stageKey]).reduce((s, q) => s + q[key], 0);
257
+ return { total, read, milestones: milestones.map(([label, pct]) => ({ label, sf: perArea
258
+ .filter(q => q[stageKey] && STAGE_PCT[q[stageKey]] >= pct).reduce((s, q) => s + q[key], 0) })) };
259
+ };
260
+ return { perArea, unmeasured, ceilingHeightFt,
261
+ walls: sumBy('wallSf', 'wallStage', WALL_MILESTONES), ceilings: sumBy('floorSf', 'ceilingStage', CEILING_MILESTONES) };
262
+ }
263
+
264
+ /** Colour ramp for a % complete (grey for no reading) — the plan heatmap. */
265
+ export function pctColor(pct) {
266
+ if (pct == null) return '#868e96';
267
+ const stops = [[0, [224, 49, 49]], [50, [245, 159, 0]], [100, [47, 158, 68]]];
268
+ const p = Math.max(0, Math.min(100, pct));
269
+ const i = p <= 50 ? 0 : 1;
270
+ const [p0, c0] = stops[i], [p1, c1] = stops[i + 1];
271
+ const t = (p - p0) / (p1 - p0);
272
+ return `#${c0.map((c, k) => Math.round(c + (c1[k] - c) * t).toString(16).padStart(2, '0')).join('')}`;
273
+ }
274
+
275
+ /** Pins for one floor-plan image, coloured by % complete or by schedule status. */
276
+ export function pinsForPlan(rollup, planId, colorBy = 'pct') {
277
+ return rollup.areas.filter(a => a.pin && a.pin.plan === planId && Number.isFinite(a.pin.x) && Number.isFinite(a.pin.y))
278
+ .map(a => ({ name: a.name, x: a.pin.x, y: a.pin.y, pct: a.actual, status: a.status, stale: a.stale,
279
+ color: colorBy === 'status' ? STATUS[a.status].color : pctColor(a.actual) }));
280
+ }
281
+
282
+ /** The pin nearest (x, y) within `radius` (all in the same units), or null. */
283
+ export function nearestPin(pins, x, y, radius) {
284
+ let best = null, bestD = radius;
285
+ for (const p of pins) {
286
+ const d = Math.hypot(p.x - x, p.y - y);
287
+ if (d <= bestD) { best = p; bestD = d; }
288
+ }
289
+ return best;
290
+ }
291
+
292
+ /** Even-odd point-in-polygon; poly is [[x, y], …] in the same units as (x, y). */
293
+ export function pointInPolygon(poly, x, y) {
294
+ let inside = false;
295
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
296
+ const [xi, yi] = poly[i], [xj, yj] = poly[j];
297
+ if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
298
+ }
299
+ return inside;
300
+ }
301
+
302
+ /** Smallest detected room containing (x, y) — rooms nest when a closet sits inside a larger outline. */
303
+ export function roomAt(rooms, x, y) {
304
+ let best = null;
305
+ for (const room of rooms || []) {
306
+ if (pointInPolygon(room.poly, x, y) && (!best || room.area < best.area)) best = room;
307
+ }
308
+ return best;
309
+ }
310
+
311
+ /**
312
+ * Rooms to fill on a plan: each pin claims the room it sits in and paints it
313
+ * its colour. Two areas pinned in one room share it (the later pin's colour,
314
+ * both names listed) rather than one silently hiding the other.
315
+ */
316
+ export function roomFills(rooms, pins) {
317
+ const fills = new Map();
318
+ for (const pin of pins) {
319
+ const room = roomAt(rooms, pin.x, pin.y);
320
+ if (!room) continue;
321
+ const f = fills.get(room) || { poly: room.poly, names: [], color: pin.color, pct: pin.pct };
322
+ f.names.push(pin.name);
323
+ f.color = pin.color; f.pct = pin.pct;
324
+ fills.set(room, f);
325
+ }
326
+ return [...fills.values()];
327
+ }
328
+
329
+ const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
330
+ const day = t => (Number.isFinite(t) ? new Date(t).toISOString().slice(0, 10) : '—');
331
+
332
+ /**
333
+ * A self-contained, printable HTML progress report (the browser's Print → PDF
334
+ * makes the PDF). Every number comes from projectRollup; nothing is restated by hand.
335
+ */
336
+ export function progressReportHtml(rollup, { project = 'Project', now = Date.now(), planImages = [], quantities = null, facades = [], curve = null } = {}) {
337
+ const r = rollup;
338
+ const pctCell = p => (p == null ? '—' : `${p}%`);
339
+ const statusCell = s => `<span class="st" style="--c:${STATUS[s].color}">${STATUS[s].label}</span>`;
340
+ const rows = [...r.areas].sort((a, b) => floorOrder(a.floor) - floorOrder(b.floor) || a.name.localeCompare(b.name));
341
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc(project)} — progress ${day(now)}</title>
342
+ <style>
343
+ body{font:13px/1.45 system-ui,-apple-system,Segoe UI,sans-serif;color:#1a1d21;margin:28px;max-width:1000px}
344
+ h1{font-size:20px;margin:0 0 2px}h2{font-size:15px;margin:22px 0 6px;border-bottom:1px solid #dee2e6;padding-bottom:3px}
345
+ .sub{color:#5c636a;margin:0 0 14px}.kpis{display:flex;gap:18px;flex-wrap:wrap}.kpi b{display:block;font-size:22px}
346
+ table{border-collapse:collapse;width:100%}th,td{text-align:left;padding:4px 8px;border-bottom:1px solid #eef0f2;vertical-align:top}
347
+ th{font-weight:600;color:#5c636a;font-size:12px}th.n,td.n{text-align:right;font-variant-numeric:tabular-nums}
348
+ .st{display:inline-block;padding:0 6px;border-radius:9px;border:1px solid var(--c);color:var(--c);font-size:12px;white-space:nowrap}
349
+ .note{color:#5c636a;font-size:12px;margin-top:18px}img.plan{max-width:100%;border:1px solid #dee2e6;margin:6px 0}
350
+ @media print{body{margin:12mm}h2{break-after:avoid}tr{break-inside:avoid}}
351
+ .cv-host{position:relative;max-width:760px}details.data summary{cursor:pointer;color:#5c636a;font-size:12px;margin:4px 0}
352
+ ${CURVE_CSS}
353
+ </style></head><body>
354
+ <h1>${esc(project)} — progress report</h1>
355
+ <p class="sub">${day(now)} · ${r.capturedAreas} of ${r.totalAreas} areas captured · BuildVision Progress mode</p>
356
+ <div class="kpis">
357
+ <div class="kpi"><b>${pctCell(r.overall)}</b>average of captured areas</div>
358
+ <div class="kpi"><b>${r.counts.behind + r.counts.not_started_late}</b>behind</div>
359
+ <div class="kpi"><b>${r.counts.at_risk}</b>at risk</div>
360
+ <div class="kpi"><b>${r.areas.filter(a => a.stale).length}</b>not captured in ${STALE_DAYS}+ days</div>
361
+ </div>
362
+ ${curve?.points.length >= 2 ? curveHtml(curve) : ''}
363
+ ${r.attention.length ? `<h2>Needs attention</h2><table><tr><th>Area</th><th>Floor</th><th>Status</th><th>Why</th></tr>
364
+ ${r.attention.map(a => `<tr><td>${esc(a.name)}</td><td>${esc(a.floor)}</td><td>${statusCell(a.status)}</td><td>${esc(a.reason)}</td></tr>`).join('\n')}</table>` : ''}
365
+ <h2>By floor</h2><table><tr><th>Floor</th><th class="n">Areas</th><th class="n">Captured</th><th class="n">Complete (avg)</th><th class="n">Behind</th><th class="n">At risk</th><th class="n">Stale</th></tr>
366
+ ${r.floors.map(f => `<tr><td>${esc(f.floor)}</td><td class="n">${f.areas}</td><td class="n">${f.captured}</td><td class="n">${pctCell(f.pct)}</td><td class="n">${f.behind}</td><td class="n">${f.atRisk}</td><td class="n">${f.stale}</td></tr>`).join('\n')}</table>
367
+ ${r.trades.length ? `<h2>By trade</h2><table><tr><th>Trade</th><th class="n">Areas read</th><th class="n">Complete (avg)</th><th class="n">Areas at 100%</th></tr>
368
+ ${r.trades.map(t => `<tr><td>${esc(t.trade)}</td><td class="n">${t.areas}</td><td class="n">${pctCell(t.pct)}</td><td class="n">${t.complete}</td></tr>`).join('\n')}</table>` : ''}
369
+ <h2>All areas</h2><table><tr><th>Area</th><th>Floor</th><th>Status</th><th class="n">Actual</th><th class="n">Planned</th><th class="n">Days behind</th><th>Last capture</th><th>Projected finish</th><th>Planned finish</th></tr>
370
+ ${rows.map(a => `<tr><td>${esc(a.name)}</td><td>${esc(a.floor)}</td><td>${statusCell(a.status)}</td><td class="n">${pctCell(a.actual)}</td><td class="n">${pctCell(a.planned)}</td><td class="n">${a.daysBehind ?? '—'}</td><td>${day(a.lastCapture)}${a.stale ? ' (stale)' : ''}</td><td>${day(a.projectedFinish)}</td><td>${day(a.plannedFinish)}</td></tr>`).join('\n')}</table>
371
+ ${quantities?.perArea.length ? quantitiesHtml(quantities) : ''}
372
+ ${facades.length ? facadesHtml(facades) : ''}
373
+ ${planImages.map(p => `<h2>${esc(p.name)}</h2><img class="plan" src="${esc(p.src)}" alt="${esc(p.name)} with area pins">`).join('\n')}
374
+ <p class="note">Stages are read by a trained image model from photos and are a prompt to look, not a quantity survey. Planned % is a straight line
375
+ between each area's planned start and finish. Projected finish is the least-squares rate across that area's captures. Days behind is how long
376
+ before the capture date the plan expected the % the capture read.</p>
377
+ </body></html>`;
378
+ }
379
+
380
+ const sf = n => `${Math.round(n).toLocaleString('en-US')} sf`;
381
+
382
+ function quantitiesHtml(q) {
383
+ const row = (label, part, whole) => `<tr><td>${esc(label)}</td><td class="n">${sf(part)}</td><td class="n">${whole > 0 ? `${Math.round((part / whole) * 100)}%` : '—'}</td></tr>`;
384
+ return `<h2>Quantities (from the scaled floor plan)</h2>
385
+ <table><tr><th>Walls (${sf(q.walls.total)} at ${q.ceilingHeightFt} ft ceilings)</th><th class="n">At or past</th><th class="n">Share</th></tr>
386
+ ${q.walls.milestones.map(m => row(m.label, m.sf, q.walls.total)).join('\n')}
387
+ ${row('Stage not read', q.walls.total - q.walls.read, q.walls.total)}</table>
388
+ <table style="margin-top:8px"><tr><th>Ceilings (${sf(q.ceilings.total)})</th><th class="n">At or past</th><th class="n">Share</th></tr>
389
+ ${q.ceilings.milestones.map(m => row(m.label, m.sf, q.ceilings.total)).join('\n')}</table>
390
+ <table style="margin-top:8px"><tr><th>Area</th><th class="n">Floor</th><th class="n">Walls</th><th>Wall stage</th><th>Ceiling stage</th></tr>
391
+ ${q.perArea.map(a => `<tr><td>${esc(a.name)}</td><td class="n">${sf(a.floorSf)}</td><td class="n">${sf(a.wallSf)}</td><td>${esc(a.wallStage ? a.wallStage.replace(/^\w+_/, '').replace(/_/g, ' ') : '—')}</td><td>${esc(a.ceilingStage ? a.ceilingStage.replace(/^\w+_/, '').replace(/_/g, ' ') : '—')}</td></tr>`).join('\n')}</table>
392
+ ${q.unmeasured.length ? `<p class="note">Not measured (no scaled plan, or no room found around the pin): ${esc(q.unmeasured.join(', '))}.</p>` : ''}`;
393
+ }
394
+
395
+ /** facades: [{ name, time, summary: { enclosed, partial, open, floors, pct, enclosedThrough }, floors: [{ floor, status, closure }], forecast }] */
396
+ function facadesHtml(facades) {
397
+ const colour = { enclosed: '#2f9e44', partial: '#f59f00', open: '#e03131', unknown: '#868e96' };
398
+ return `<h2>Facade (by elevation)</h2><table><tr><th>Elevation</th><th>Captured</th><th class="n">Enclosed</th><th class="n">Partly</th><th class="n">Open</th><th class="n">Closed</th><th>Floors (bottom → top)</th><th>Projection</th></tr>
399
+ ${facades.map(f => `<tr><td>${esc(f.name)}</td><td>${day(f.time)}</td><td class="n">${f.summary.enclosed}/${f.summary.floors}</td><td class="n">${f.summary.partial}</td><td class="n">${f.summary.open}</td><td class="n">${f.summary.pct ?? '—'}%</td>
400
+ <td>${[...f.floors].sort((a, b) => a.floor - b.floor).map(fl => `<span title="Floor ${fl.floor}: ${esc(fl.status)}" style="display:inline-block;width:10px;height:14px;margin-right:1px;background:${colour[fl.status] || '#868e96'}"></span>`).join('')}</td>
401
+ <td>${esc(f.forecast || '—')}</td></tr>`).join('\n')}</table>`;
402
+ }
403
+
404
+ // ---------- planned vs actual over time (the project S-curve) ----------
405
+
406
+ /**
407
+ * Project % complete over time, planned against actual, across the areas that
408
+ * have planned dates (the only ones a plan exists for). Planned at t is the
409
+ * mean of each area's straight-line plan; actual at t is the mean of each
410
+ * area's latest capture on or before t, counting an area with no capture yet
411
+ * as 0 — so both lines describe the same set of areas. Actual stops at `now`.
412
+ */
413
+ export function projectCurve(store, now = Date.now(), { maxPoints = 60 } = {}) {
414
+ const areas = Object.values(store?.areas || {}).filter(r => Number.isFinite(r.schedule?.start) && Number.isFinite(r.schedule?.finish) && r.schedule.finish > r.schedule.start);
415
+ if (!areas.length) return { points: [], areas: 0 };
416
+ const caps = areas.flatMap(r => (r.captures || []).map(c => c.time)).filter(Number.isFinite);
417
+ const t0 = Math.min(...areas.map(r => r.schedule.start), ...caps);
418
+ const t1 = Math.max(...areas.map(r => r.schedule.finish), Math.min(now, Math.max(now, ...caps)));
419
+ const steps = Math.max(2, Math.min(maxPoints, Math.ceil((t1 - t0) / DAY) + 1));
420
+ const times = [...new Set([...Array.from({ length: steps }, (_, i) => Math.round(t0 + ((t1 - t0) * i) / (steps - 1))), ...caps.filter(t => t <= now)])].sort((a, b) => a - b);
421
+ const actualAt = (r, t) => {
422
+ let best = null;
423
+ for (const c of r.captures || []) if (c.time <= t && c.overall != null && (!best || c.time > best.time)) best = c;
424
+ return best ? best.overall : 0;
425
+ };
426
+ const mean = xs => Math.round((xs.reduce((s, x) => s + x, 0) / xs.length) * 10) / 10;
427
+ const points = times.map(t => ({ t, planned: mean(areas.map(r => plannedPctAt(r.schedule, t))),
428
+ actual: t <= now ? mean(areas.map(r => actualAt(r, t))) : null }));
429
+ return { points, areas: areas.length, now };
430
+ }
431
+
432
+ /**
433
+ * The curve as a self-contained SVG string: two 2px lines (planned, actual),
434
+ * end dots with a surface ring, a direct label at each line's end, hairline
435
+ * gridlines at 0/25/50/75/100, a "today" rule, and one invisible hit column per
436
+ * point carrying data-* for the hover script. Colours come from CSS custom
437
+ * properties (--series-1 planned, --series-2 actual, --grid, --text-2, --surface)
438
+ * so the page supplies light/dark values.
439
+ */
440
+ export function curveSvg(curve, { width = 640, height = 220 } = {}) {
441
+ const pts = curve.points;
442
+ if (pts.length < 2) return '';
443
+ const L = 40, R = 104, T = 10, B = 24, w = width - L - R, h = height - T - B;
444
+ const tMin = pts[0].t, tMax = pts[pts.length - 1].t;
445
+ const X = t => L + ((t - tMin) / Math.max(1, tMax - tMin)) * w, Y = p => T + h - (p / 100) * h;
446
+ const path = key => pts.filter(p => p[key] != null).map((p, i) => `${i ? 'L' : 'M'}${X(p.t).toFixed(1)},${Y(p[key]).toFixed(1)}`).join('');
447
+ const lastOf = key => [...pts].reverse().find(p => p[key] != null);
448
+ const lp = lastOf('planned'), la = lastOf('actual');
449
+ const fmtDay = t => new Date(t).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
450
+ const grid = [0, 25, 50, 75, 100].map(g => `<line x1="${L}" x2="${L + w}" y1="${Y(g)}" y2="${Y(g)}" class="cv-grid"/><text x="${L - 6}" y="${Y(g) + 3.5}" class="cv-axis" text-anchor="end">${g}%</text>`).join('');
451
+ const ticks = [tMin, tMin + (tMax - tMin) / 2, tMax].map((t, i) => `<text x="${X(t)}" y="${height - 6}" class="cv-axis" text-anchor="${['start', 'middle', 'end'][i]}">${fmtDay(t)}</text>`).join('');
452
+ const today = curve.now >= tMin && curve.now <= tMax ? `<line x1="${X(curve.now)}" x2="${X(curve.now)}" y1="${T}" y2="${T + h}" class="cv-today"/><text x="${X(curve.now) + 3}" y="${T + 9}" class="cv-axis">today</text>` : '';
453
+ // Direct labels at the right edge; pushed apart only when they would overlap, with a leader to the line end.
454
+ let ya = la ? Y(la.actual) : null, yp = Y(lp.planned);
455
+ if (ya != null && Math.abs(ya - yp) < 14) { const mid = (ya + yp) / 2; ya = mid + (ya >= yp ? 7 : -7); yp = mid + (ya >= yp ? -7 : 7); }
456
+ // The line's own end dot is the label's key; a leader runs to the label only when it had to move.
457
+ const label = (p, key, y, name) => `${Math.abs(y - Y(p[key])) > 1 || X(p.t) < L + w - 1 ? `<line x1="${X(p.t) + 6}" x2="${L + w + 6}" y1="${Y(p[key])}" y2="${y}" class="cv-leader"/>` : ''}<text x="${L + w + 10}" y="${y + 4}" class="cv-label">${name} ${Math.round(p[key])}%</text>`;
458
+ const cols = pts.map((p, i) => {
459
+ const x0 = i ? (X(pts[i - 1].t) + X(p.t)) / 2 : L, x1 = i < pts.length - 1 ? (X(p.t) + X(pts[i + 1].t)) / 2 : L + w;
460
+ return `<rect x="${x0.toFixed(1)}" y="${T}" width="${Math.max(1, x1 - x0).toFixed(1)}" height="${h}" class="cv-hit" data-x="${X(p.t).toFixed(1)}" data-date="${fmtDay(p.t)}" data-planned="${p.planned}" data-actual="${p.actual ?? ''}" data-yp="${Y(p.planned).toFixed(1)}" data-ya="${p.actual == null ? '' : Y(p.actual).toFixed(1)}"/>`;
461
+ }).join('');
462
+ return `<svg class="cv" viewBox="0 0 ${width} ${height}" width="100%" role="img" aria-label="Planned vs actual % complete over time: planned ${Math.round(lp.planned)}%${la ? `, actual ${Math.round(la.actual)}% at ${fmtDay(la.t)}` : ''}">
463
+ ${grid}${ticks}${today}
464
+ <path d="${path('planned')}" class="cv-planned"/><path d="${path('actual')}" class="cv-actual"/>
465
+ <circle cx="${X(lp.t)}" cy="${Y(lp.planned)}" r="4" class="cv-planned-dot"/>${la ? `<circle cx="${X(la.t)}" cy="${Y(la.actual)}" r="4" class="cv-actual-dot"/>` : ''}
466
+ ${label(lp, 'planned', yp, 'Planned')}${la ? label(la, 'actual', ya, 'Actual') : ''}
467
+ <line class="cv-cross" x1="0" x2="0" y1="${T}" y2="${T + h}" visibility="hidden"/>
468
+ <circle class="cv-hover cv-planned-dot" r="4" visibility="hidden"/><circle class="cv-hover cv-actual-dot" r="4" visibility="hidden"/>
469
+ <g class="cv-hits">${cols}</g></svg>`;
470
+ }
471
+
472
+ /** Styles for curveSvg (light + dark). Scoped under .cv. */
473
+ export const CURVE_CSS = `.cv,.cv-wrap{--series-1:#2a78d6;--series-2:#eb6834;--grid:#e6e6e3;--text-2:#52514e;--surface:#fcfcfb;overflow:visible;font:11px system-ui,sans-serif}
474
+ @media (prefers-color-scheme:dark){:root:where(:not([data-theme="light"])) :is(.cv,.cv-wrap){--series-1:#3987e5;--series-2:#d95926;--grid:#33332f;--text-2:#c3c2b7;--surface:#1a1a19}}
475
+ :root[data-theme="dark"] :is(.cv,.cv-wrap){--series-1:#3987e5;--series-2:#d95926;--grid:#33332f;--text-2:#c3c2b7;--surface:#1a1a19}
476
+ .cv-grid{stroke:var(--grid);stroke-width:1}.cv-axis{fill:var(--text-2)}.cv-today{stroke:var(--text-2);stroke-width:1;opacity:.5}
477
+ .cv-planned,.cv-actual{fill:none;stroke-width:2;stroke-linejoin:round;stroke-linecap:round}.cv-planned{stroke:var(--series-1)}.cv-actual{stroke:var(--series-2)}
478
+ .cv-planned-dot{fill:var(--series-1);stroke:var(--surface);stroke-width:2}.cv-actual-dot{fill:var(--series-2);stroke:var(--surface);stroke-width:2}
479
+ .cv-leader{stroke:var(--text-2);stroke-width:1;opacity:.35}.cv-label{fill:currentColor;font-weight:600}
480
+ .cv-cross{stroke:var(--text-2);stroke-width:1}.cv-hit{fill:transparent;cursor:crosshair}
481
+ .cv-legend{display:flex;flex-wrap:wrap;gap:4px 12px;font:12px system-ui,sans-serif;margin:0 0 4px}.cv-legend span{display:inline-flex;align-items:center;gap:5px}
482
+ .cv-legend i{display:inline-block;width:14px;height:2px;border-radius:1px}.cv-headline{font:600 13px system-ui,sans-serif;margin:0 0 4px}
483
+ .cv-tip{position:absolute;pointer-events:none;background:var(--tip-bg,#fff);color:inherit;border:1px solid rgba(0,0,0,.15);border-radius:4px;padding:4px 6px;font:12px system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 6px rgba(0,0,0,.12)}`;
484
+
485
+ /**
486
+ * Hover for a curveSvg inside `host` (position:relative): crosshair, both
487
+ * dots at the hovered date, and a tooltip with the date and both values.
488
+ * Serialised into the report too (Function#toString), so it must stay self-contained.
489
+ */
490
+ export function attachCurveHover(host) {
491
+ const svg = host.querySelector('svg.cv');
492
+ if (!svg) return;
493
+ const tip = document.createElement('div');
494
+ tip.className = 'cv-tip'; tip.hidden = true;
495
+ host.append(tip);
496
+ const cross = svg.querySelector('.cv-cross'), [dp, da] = svg.querySelectorAll('.cv-hover');
497
+ const hide = () => { tip.hidden = true; [cross, dp, da].forEach(el => el.setAttribute('visibility', 'hidden')); };
498
+ svg.querySelectorAll('.cv-hit').forEach(r => r.addEventListener('pointermove', e => {
499
+ const d = r.dataset;
500
+ cross.setAttribute('x1', d.x); cross.setAttribute('x2', d.x); cross.setAttribute('visibility', 'visible');
501
+ dp.setAttribute('cx', d.x); dp.setAttribute('cy', d.yp); dp.setAttribute('visibility', 'visible');
502
+ if (d.ya) { da.setAttribute('cx', d.x); da.setAttribute('cy', d.ya); da.setAttribute('visibility', 'visible'); } else da.setAttribute('visibility', 'hidden');
503
+ tip.textContent = `${d.date} · planned ${Math.round(+d.planned)}%${d.actual ? ` · actual ${Math.round(+d.actual)}%` : ''}`;
504
+ tip.hidden = false;
505
+ const box = host.getBoundingClientRect();
506
+ tip.style.left = `${Math.min(box.width - tip.offsetWidth, Math.max(0, e.clientX - box.left + 10))}px`;
507
+ tip.style.top = `${Math.max(0, e.clientY - box.top - 30)}px`;
508
+ }));
509
+ svg.addEventListener('pointerleave', hide);
510
+ }
511
+
512
+ function curveHtml(curve) {
513
+ const day2 = t => new Date(t).toISOString().slice(0, 10);
514
+ return `<h2>Planned vs actual (${curve.areas} scheduled area${curve.areas === 1 ? '' : 's'})</h2>
515
+ <div class="cv-host cv-wrap">${curveLegendHtml(curve)}${curveSvg(curve)}</div>
516
+ <details class="data"><summary>Show the data</summary><table><tr><th>Date</th><th class="n">Planned</th><th class="n">Actual</th></tr>
517
+ ${curve.points.map(p => `<tr><td>${day2(p.t)}</td><td class="n">${Math.round(p.planned)}%</td><td class="n">${p.actual == null ? '—' : `${Math.round(p.actual)}%`}</td></tr>`).join('\n')}</table></details>
518
+ <script>(${attachCurveHover.toString()})(document.querySelector('.cv-host'));</script>`;
519
+ }
520
+
521
+ /** Where the project stands today, from the curve: planned vs actual and the gap, for the headline line. */
522
+ export function curveToday(curve) {
523
+ const past = curve.points.filter(p => p.actual != null);
524
+ const last = past[past.length - 1];
525
+ if (!last) return null;
526
+ const planned = Math.round(last.planned), actual = Math.round(last.actual), gap = actual - planned; // from the shown numbers, so they add up
527
+ return { planned, actual, gap,
528
+ text: `Today: ${actual}% complete vs ${planned}% planned — ${gap === 0 ? 'on plan' : `${Math.abs(gap)} points ${gap < 0 ? 'behind' : 'ahead'}`}` };
529
+ }
530
+
531
+ /** Legend row + headline above the chart (identity is never colour-only: the lines also carry end labels). */
532
+ export function curveLegendHtml(curve) {
533
+ const today = curveToday(curve);
534
+ return `${today ? `<p class="cv-headline">${today.text}</p>` : ''}<div class="cv-legend"><span><i style="background:var(--series-1)"></i>Planned (straight line between each area's planned dates)</span><span><i style="background:var(--series-2)"></i>Actual (each area's latest capture)</span></div>`;
535
+ }
schedule-import.js ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Schedule import for Progress mode: planned dates from the project schedule
2
+ // instead of typed in area by area — the link Buildots makes between what the
3
+ // camera saw and the programme (P6 / MS Project). Reads a CSV export (P6,
4
+ // MS Project, Smartsheet and Excel all export one) or an MS Project XML file,
5
+ // then matches each activity to the app's areas and trades by name:
6
+ //
7
+ // "L3 Unit 3B – hang drywall" → area "L3 Unit 3B", trade Walls
8
+ // "Level 4 ceiling grid" → every area on floor L4, trade Ceiling
9
+ // "L3 Unit 3B fit-out" → area "L3 Unit 3B", the area's own window
10
+ //
11
+ // Nothing is applied until the user has seen what matched and what did not.
12
+ // Pure functions (tests/schedule-import.test.mjs).
13
+ import { floorOf } from './progress-project.js';
14
+
15
+ const MONTHS = { jan: 0, feb: 1, mar: 2, apr: 3, may: 4, jun: 5, jul: 6, aug: 7, sep: 8, oct: 9, nov: 10, dec: 11 };
16
+
17
+ /**
18
+ * Schedule dates as local noon (the app stores capture dates the same way).
19
+ * ISO 2026-09-01 (optionally with a time), US 9/1/2026 or 09/01/26, P6 01-Sep-26 / 01-Sep-2026, "Sep 1, 2026".
20
+ * A trailing "A" (P6 actual) or "*" (constraint) is ignored.
21
+ */
22
+ export function parseScheduleDate(raw) {
23
+ const s = String(raw ?? '').trim().replace(/\s*[A*]$/, '');
24
+ if (!s) return null;
25
+ let m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);
26
+ if (m) return new Date(+m[1], +m[2] - 1, +m[3], 12).getTime();
27
+ m = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})/);
28
+ if (m) return new Date(+m[3] < 100 ? 2000 + +m[3] : +m[3], +m[1] - 1, +m[2], 12).getTime();
29
+ m = s.match(/^(\d{1,2})[- ]([A-Za-z]{3})[a-z]*[- ,]+(\d{2,4})/);
30
+ if (m && MONTHS[m[2].toLowerCase()] != null) return new Date(+m[3] < 100 ? 2000 + +m[3] : +m[3], MONTHS[m[2].toLowerCase()], +m[1], 12).getTime();
31
+ m = s.match(/^([A-Za-z]{3})[a-z]*\.? (\d{1,2}),? (\d{4})/);
32
+ if (m && MONTHS[m[1].toLowerCase()] != null) return new Date(+m[3], MONTHS[m[1].toLowerCase()], +m[2], 12).getTime();
33
+ return null;
34
+ }
35
+
36
+ /** RFC-4180-ish CSV: quoted fields, doubled quotes, commas/newlines inside quotes; also tab-separated. */
37
+ export function parseCsv(text) {
38
+ const delim = (text.split('\n')[0].match(/\t/g) || []).length > (text.split('\n')[0].match(/,/g) || []).length ? '\t' : ',';
39
+ const rows = [];
40
+ let row = [], field = '', q = false;
41
+ for (let i = 0; i < text.length; i++) {
42
+ const ch = text[i];
43
+ if (q) {
44
+ if (ch === '"' && text[i + 1] === '"') { field += '"'; i++; }
45
+ else if (ch === '"') q = false;
46
+ else field += ch;
47
+ } else if (ch === '"') q = true;
48
+ else if (ch === delim) { row.push(field); field = ''; }
49
+ else if (ch === '\n' || ch === '\r') {
50
+ if (ch === '\r' && text[i + 1] === '\n') i++;
51
+ row.push(field); field = '';
52
+ if (row.some(c => c.trim())) rows.push(row);
53
+ row = [];
54
+ } else field += ch;
55
+ }
56
+ row.push(field);
57
+ if (row.some(c => c.trim())) rows.push(row);
58
+ return rows;
59
+ }
60
+
61
+ const HEADERS = {
62
+ name: /^(activity|task|activity name|task name|name|description|activity description)$/i,
63
+ start: /^(start|start date|planned start|early start|baseline start|bl start)$/i,
64
+ finish: /^(finish|finish date|end|end date|planned finish|early finish|baseline finish|bl finish)$/i,
65
+ area: /^(area|location|zone|room|space|wbs name)$/i,
66
+ trade: /^(trade|discipline|activity code|responsibility)$/i,
67
+ };
68
+
69
+ /** Activities from a CSV export: finds the header row (first row naming a start and a finish column). */
70
+ export function parseScheduleCsv(text) {
71
+ const rows = parseCsv(text);
72
+ const headerIdx = rows.findIndex(r => r.some(c => HEADERS.start.test(c.trim())) && r.some(c => HEADERS.finish.test(c.trim())));
73
+ if (headerIdx < 0) return { activities: [], problems: ['No header row with a start and a finish column was found.'] };
74
+ const header = rows[headerIdx].map(c => c.trim());
75
+ const col = key => header.findIndex(h => HEADERS[key].test(h));
76
+ const cols = { name: col('name'), start: col('start'), finish: col('finish'), area: col('area'), trade: col('trade') };
77
+ if (cols.name < 0) cols.name = header.findIndex((h, i) => i !== cols.start && i !== cols.finish && h);
78
+ const activities = [], problems = [];
79
+ rows.slice(headerIdx + 1).forEach((r, i) => {
80
+ const name = (r[cols.name] || '').trim();
81
+ const start = parseScheduleDate(r[cols.start]), finish = parseScheduleDate(r[cols.finish]);
82
+ if (!name) return;
83
+ if (start == null || finish == null) { problems.push(`Row ${headerIdx + i + 2} (${name}): unreadable dates`); return; }
84
+ activities.push({ name, start: Math.min(start, finish), finish: Math.max(start, finish),
85
+ area: cols.area >= 0 ? (r[cols.area] || '').trim() || null : null, trade: cols.trade >= 0 ? (r[cols.trade] || '').trim() || null : null });
86
+ });
87
+ return { activities, problems };
88
+ }
89
+
90
+ const xmlText = s => s.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&');
91
+
92
+ /** Activities from an MS Project XML export (File → Save As → XML). Summary tasks are skipped. */
93
+ export function parseMsProjectXml(text) {
94
+ const activities = [], problems = [];
95
+ for (const block of text.match(/<Task>[\s\S]*?<\/Task>/g) || []) {
96
+ const get = tag => { const m = block.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`)); return m ? xmlText(m[1]).trim() : null; };
97
+ if (get('Summary') === '1' || get('IsNull') === '1') continue;
98
+ const name = get('Name');
99
+ if (!name) continue;
100
+ const start = parseScheduleDate(get('Start')), finish = parseScheduleDate(get('Finish'));
101
+ if (start == null || finish == null) { problems.push(`${name}: unreadable dates`); continue; }
102
+ activities.push({ name, start, finish, area: null, trade: null });
103
+ }
104
+ return { activities, problems };
105
+ }
106
+
107
+ export function parseSchedule(text, fileName = '') {
108
+ return /\.xml$/i.test(fileName) || /^\s*<\?xml|<Project[\s>]/.test(text) ? parseMsProjectXml(text) : parseScheduleCsv(text);
109
+ }
110
+
111
+ // Trade keywords → Progress mode's item keys. Order matters: "ceiling grid" is Ceiling, not Walls.
112
+ const TRADES = [
113
+ ['ceiling', /\b(ceiling|ceilings|act|acoustic|grid|soffit|bulkhead)\b/i],
114
+ ['exits', /\bexit\b/i],
115
+ ['supply', /\b(diffuser|diffusers|supply air)\b/i],
116
+ ['returns', /\b(return|returns|grille|grilles)\b/i],
117
+ ['fixtures', /\b(light|lights|lighting|fixture|fixtures|luminaire|luminaires)\b/i],
118
+ ['wall', /\b(drywall|gypsum|gyp|plasterboard|sheetrock|board|partition|partitions|stud|studs|framing|frame|tape|taping|mud|finish walls|wall|walls|paint|painting)\b/i],
119
+ ];
120
+ export function tradeOf(text) {
121
+ for (const [key, re] of TRADES) if (re.test(text || '')) return key;
122
+ return null;
123
+ }
124
+
125
+ const norm = s => String(s || '').toLowerCase().replace(/[·•|_]+/g, ' ').replace(/[-–—]+/g, ' ').replace(/\s+/g, ' ').trim();
126
+
127
+ /** A floor named in an activity ("Level 4 …", "L4 …", "4th floor …") in the same keys floorOf gives areas. */
128
+ function floorInText(text) {
129
+ const s = String(text || '');
130
+ let m = s.match(/\b(?:l|lvl|level|fl|floor)\s*-?\s*0*(\d+)\b/i) || s.match(/\b0*(\d+)(?:st|nd|rd|th)?\s*(?:f|fl|floor)\b/i);
131
+ if (m) return `L${Number(m[1])}`;
132
+ m = s.match(/\b(?:b|basement)\s*-?\s*0*(\d+)\b/i);
133
+ return m ? `B${Number(m[1])}` : null;
134
+ }
135
+
136
+ /**
137
+ * Match activities to areas and trades. An activity names an area when the
138
+ * area's name appears in it (longest name wins, so "L3 Unit 3B" beats "L3");
139
+ * otherwise, if it names a floor, it applies to every area on that floor that
140
+ * has no activity of its own for that trade. Returns per-area windows and
141
+ * per-trade windows (earliest start → latest finish across matching activities)
142
+ * plus what could not be placed.
143
+ */
144
+ export function matchSchedule(activities, areaNames) {
145
+ const areas = [...areaNames].sort((a, b) => norm(b).length - norm(a).length);
146
+ const plan = {}, unmatched = [], used = [];
147
+ const widen = (w, a) => ({ start: Math.min(w?.start ?? Infinity, a.start), finish: Math.max(w?.finish ?? -Infinity, a.finish) });
148
+ const direct = new Set(); // "area|trade" set by an activity naming the area itself
149
+ const floorActs = [];
150
+ for (const act of activities) {
151
+ const hay = norm(`${act.area || ''} ${act.name}`);
152
+ const area = areas.find(n => norm(n) && (norm(act.area) === norm(n) || hay.includes(norm(n))));
153
+ const trade = tradeOf(act.trade) || tradeOf(act.name);
154
+ if (area) {
155
+ const p = (plan[area] ||= { window: null, trades: {}, activities: [] });
156
+ if (trade) { p.trades[trade] = widen(p.trades[trade], act); direct.add(`${area}|${trade}`); }
157
+ else p.window = widen(p.window, act);
158
+ p.activities.push(act.name);
159
+ used.push(act);
160
+ } else if (floorInText(act.area || act.name)) floorActs.push({ act, floor: floorInText(act.area || act.name), trade });
161
+ else unmatched.push(act.name);
162
+ }
163
+ for (const { act, floor, trade } of floorActs) {
164
+ const onFloor = areaNames.filter(n => floorOf(n) === floor);
165
+ if (!onFloor.length) { unmatched.push(act.name); continue; }
166
+ for (const area of onFloor) {
167
+ const p = (plan[area] ||= { window: null, trades: {}, activities: [] });
168
+ if (trade) { if (direct.has(`${area}|${trade}`)) continue; p.trades[trade] = widen(p.trades[trade], act); }
169
+ else if (!p.window) p.window = { start: act.start, finish: act.finish };
170
+ p.activities.push(`${act.name} (floor ${floor})`);
171
+ }
172
+ used.push(act);
173
+ }
174
+ // An area whose schedule only names trades gets a window spanning them —
175
+ // marked as derived, so applying it never replaces dates the area already has.
176
+ for (const p of Object.values(plan)) {
177
+ if (!p.window && Object.keys(p.trades).length) {
178
+ p.window = Object.values(p.trades).reduce((w, t) => ({ start: Math.min(w.start, t.start), finish: Math.max(w.finish, t.finish) }), { start: Infinity, finish: -Infinity });
179
+ p.derivedWindow = true;
180
+ }
181
+ }
182
+ return { plan, unmatched, matched: used.length };
183
+ }
184
+
185
+ /** Write a match into a Progress store (mutates and returns it). Imported dates replace typed ones for matched areas only. */
186
+ export function applySchedule(store, plan) {
187
+ for (const [area, p] of Object.entries(plan)) {
188
+ const rec = (store.areas[area] ||= { captures: [] });
189
+ const hasOwn = Number.isFinite(rec.schedule?.start) && Number.isFinite(rec.schedule?.finish);
190
+ const setWindow = p.window && !(p.derivedWindow && hasOwn);
191
+ rec.schedule = { ...(rec.schedule || {}), ...(setWindow ? { start: p.window.start, finish: p.window.finish } : {}),
192
+ trades: { ...(rec.schedule?.trades || {}), ...p.trades } };
193
+ }
194
+ return store;
195
+ }
style.css CHANGED
@@ -1,28 +1,1874 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  }
5
 
6
- h1 {
7
- font-size: 16px;
8
- margin-top: 0;
 
 
9
  }
10
 
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
16
  }
17
 
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
24
  }
25
 
26
- .card p:last-child {
27
- margin-bottom: 0;
 
 
 
 
 
 
 
28
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ /* Primary white / secondary dark navy — a Procore/Autodesk-style light
3
+ professional chrome instead of a dark "hacker tool" theme. Navy does
4
+ double duty as both structural accent (active tabs, focus rings) and
5
+ the default detection-box color, so the whole app reads as one brand
6
+ rather than chrome + an unrelated accent hue. */
7
+ --bg: #ffffff;
8
+ --bg-panel: #ffffff;
9
+ --bg-panel-2: #f3f5f9;
10
+ --bg-subtle: #eef1f6;
11
+ --border: #dde3ec;
12
+ --border-strong: #0f2547;
13
+ --text: #101d30;
14
+ --text-dim: #5c6b80;
15
+ --accent: #0f2547;
16
+ --accent-hover: #18345c;
17
+ --accent-soft: #e8edf5;
18
+ --success: #16a34a;
19
+ --success-soft: #e6f7ec;
20
+ --danger: #dc2626;
21
+ --danger-soft: #fdecec;
22
+ --warning: #b45309;
23
+ /* Small and mostly-uniform on purpose — flat/square, not the pill/rounded
24
+ treatment of a generic AI-tool template. */
25
+ --radius: 6px;
26
+ --radius-sm: 4px;
27
+ --radius-lg: 8px;
28
+ --shadow-xs: 0 1px 2px rgba(15, 37, 71, 0.06);
29
+ --shadow-sm: 0 1px 3px rgba(15, 37, 71, 0.08);
30
+ --shadow-md: 0 4px 16px rgba(15, 37, 71, 0.10);
31
+ font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
32
+ }
33
+
34
+ * { box-sizing: border-box; }
35
+
36
+ html, body {
37
+ margin: 0;
38
+ padding: 0;
39
+ background: var(--bg);
40
+ color: var(--text);
41
+ height: 100%;
42
+ }
43
+
44
  body {
45
+ display: flex;
46
+ flex-direction: column;
47
+ }
48
+
49
+ button, input, select { font-family: inherit; }
50
+
51
+ /* ---------- Header ---------- */
52
+
53
+ .app-header {
54
+ display: flex;
55
+ align-items: center;
56
+ justify-content: space-between;
57
+ gap: 16px;
58
+ padding: 12px 20px;
59
+ border-bottom: 1px solid var(--border);
60
+ background: var(--bg-panel);
61
+ flex: 0 0 auto;
62
+ }
63
+
64
+ .brand {
65
+ display: flex;
66
+ align-items: center;
67
+ gap: 8px;
68
+ font-weight: 700;
69
+ letter-spacing: -0.01em;
70
+ }
71
+
72
+ .brand-mark {
73
+ width: 22px;
74
+ height: 22px;
75
+ flex-shrink: 0;
76
+ color: var(--accent);
77
+ }
78
+
79
+ .brand-name {
80
+ font: inherit;
81
+ font-size: 1.05rem;
82
+ font-weight: inherit;
83
+ letter-spacing: inherit;
84
+ margin: 0;
85
+ color: var(--accent);
86
+ }
87
+
88
+ .mode-switch {
89
+ display: flex;
90
+ gap: 2px;
91
+ background: var(--bg-subtle);
92
+ border: 1px solid var(--border);
93
+ border-radius: var(--radius);
94
+ padding: 3px;
95
+ min-width: 0;
96
+ overflow-x: auto;
97
+ scrollbar-width: none;
98
+ -webkit-overflow-scrolling: touch;
99
+ /* Edge fade as a scroll affordance, but only on the side that actually has
100
+ more to reach: the old rule faded both edges unconditionally, so a bar
101
+ scrolled hard to the left still dimmed its leftmost tab as though
102
+ something were hidden behind it. `.at-start` / `.at-end` are set from
103
+ the scroll handler in main.js. With 9 modes in a 348px-wide bar, over
104
+ half the tabs are off-screen on a phone — this is the only thing telling
105
+ you Measure, Landmarks, Sketch and Drone exist at all. */
106
+ --fade-l: 14px;
107
+ --fade-r: 14px;
108
+ -webkit-mask-image: linear-gradient(to right, transparent, black var(--fade-l), black calc(100% - var(--fade-r)), transparent);
109
+ mask-image: linear-gradient(to right, transparent, black var(--fade-l), black calc(100% - var(--fade-r)), transparent);
110
+ }
111
+
112
+ .mode-switch.at-start { --fade-l: 0px; }
113
+ .mode-switch.at-end { --fade-r: 0px; }
114
+
115
+ .mode-switch::-webkit-scrollbar { display: none; }
116
+
117
+ .mode-btn {
118
+ flex: 0 0 auto;
119
+ display: flex;
120
+ align-items: center;
121
+ gap: 6px;
122
+ border: none;
123
+ background: transparent;
124
+ color: var(--text-dim);
125
+ padding: 7px 12px;
126
+ border-radius: var(--radius-sm);
127
+ font-size: 0.82rem;
128
+ font-weight: 600;
129
+ cursor: pointer;
130
+ white-space: nowrap;
131
+ transition: background 0.12s, color 0.12s;
132
+ }
133
+
134
+ .mode-btn:hover { color: var(--text); background: rgba(15, 37, 71, 0.06); }
135
+
136
+ .mode-btn.active {
137
+ background: var(--accent);
138
+ color: #ffffff;
139
+ }
140
+
141
+ /* Tabs that navigate to another page (Circuits) — look like .mode-btn without main.js binding them. */
142
+ .mode-link {
143
+ flex: 0 0 auto; display: flex; align-items: center; gap: 6px; padding: 7px 12px;
144
+ border-radius: var(--radius-sm); font-size: 0.82rem; font-weight: 600; white-space: nowrap;
145
+ color: var(--text-dim); text-decoration: none; transition: background 0.12s, color 0.12s;
146
+ }
147
+ a.mode-link:hover { color: var(--text); background: rgba(15, 37, 71, 0.06); }
148
+ .mode-link.active { background: var(--accent); color: #ffffff; }
149
+
150
+ /* Icon sprites — sized down from their 24x24 viewBox for compact chrome use.
151
+ currentColor means an icon always matches its button's current text color
152
+ (dim/hover/active states) with no extra rules needed. */
153
+ .mode-icon {
154
+ width: 14px;
155
+ height: 14px;
156
+ flex-shrink: 0;
157
+ color: currentColor;
158
+ }
159
+
160
+ .title-icon {
161
+ width: 15px;
162
+ height: 15px;
163
+ flex-shrink: 0;
164
+ margin-right: 6px;
165
+ vertical-align: -2px;
166
+ color: var(--accent);
167
+ }
168
+
169
+ .header-status { display: flex; align-items: center; gap: 8px; }
170
+
171
+ .status-pill {
172
+ display: inline-flex;
173
+ align-items: center;
174
+ gap: 6px;
175
+ font-size: 0.75rem;
176
+ color: var(--text-dim);
177
+ border: 1px solid var(--border);
178
+ border-radius: var(--radius-sm);
179
+ padding: 4px 10px;
180
+ white-space: nowrap;
181
+ background: var(--bg-panel-2);
182
+ }
183
+
184
+ .status-pill.ready { color: var(--success); border-color: var(--success-soft); background: var(--success-soft); }
185
+ .status-pill.loading { color: var(--accent); border-color: var(--accent-soft); background: var(--accent-soft); }
186
+ .model-status { font-family: inherit; cursor: default; }
187
+ .model-status[aria-busy="true"] { cursor: progress; }
188
+ .model-status.error { color: #982b2b; border-color: #edcaca; background: #fff2f2; cursor: pointer; }
189
+ .model-status.error:focus-visible { outline: 2px solid #982b2b; outline-offset: 2px; }
190
+
191
+ .weather-pill {
192
+ font-family: inherit;
193
+ font-weight: 600;
194
+ cursor: pointer;
195
+ transition: border-color 0.12s, background 0.12s;
196
+ }
197
+
198
+ .weather-pill:hover { border-color: var(--accent); background: var(--accent-soft); }
199
+ .weather-pill.loaded { color: var(--accent); border-color: var(--accent-soft); background: var(--accent-soft); }
200
+
201
+ /* ---------- Layout ---------- */
202
+
203
+ .layout {
204
+ flex: 1 1 auto;
205
+ display: grid;
206
+ grid-template-columns: 1fr 320px;
207
+ gap: 16px;
208
+ padding: 16px;
209
+ min-height: 0;
210
+ background: var(--bg-subtle);
211
+ }
212
+
213
+ .stage {
214
+ display: flex;
215
+ flex-direction: column;
216
+ gap: 10px;
217
+ min-width: 0;
218
+ }
219
+
220
+ .stage-frame {
221
+ position: relative;
222
+ flex: 1 1 auto;
223
+ /* The video/photo stage stays dark regardless of the app's light chrome —
224
+ footage needs a neutral black surround the same way a photo viewer or
225
+ video editor in a light-themed pro tool still letterboxes on black. */
226
+ background: #05070a;
227
+ border: 1px solid var(--border);
228
+ border-radius: var(--radius);
229
+ overflow: hidden;
230
+ min-height: 420px;
231
+ box-shadow: var(--shadow-xs);
232
+ background-image:
233
+ linear-gradient(rgba(120, 155, 200, 0.05) 1px, transparent 1px),
234
+ linear-gradient(90deg, rgba(120, 155, 200, 0.05) 1px, transparent 1px);
235
+ background-size: 24px 24px;
236
+ }
237
+
238
+ .scan-sweep { display:none; position:absolute; z-index:5; top:0; left:0; right:0; height:2px; pointer-events:none; opacity:0; background:linear-gradient(90deg, transparent 0%, rgba(56,189,248,.18) 12%, #67e8f9 50%, rgba(56,189,248,.18) 88%, transparent 100%); box-shadow:0 0 12px rgba(34,211,238,.62); }
239
+ .stage-frame.is-scanning .scan-sweep { display:block; animation:scan-sweep 1.35s ease-in-out infinite; }
240
+ @keyframes scan-sweep { 0% { transform:translateY(0); opacity:0; } 10% { opacity:.72; } 88% { opacity:.72; } 100% { transform:translateY(var(--scan-distance, 100vh)); opacity:0; } }
241
+ .scan-status { position:absolute; z-index:7; top:12px; right:12px; display:flex; align-items:center; gap:8px; padding:7px 10px; border:1px solid rgba(203,213,225,.22); border-radius:5px; background:rgba(8,18,32,.88); color:#f2f6fb; font-size:10px; line-height:1; font-weight:650; letter-spacing:.035em; text-transform:uppercase; box-shadow:0 4px 14px rgba(0,0,0,.2); animation:scan-status-in .16s ease-out both; pointer-events:none; }
242
+ .scan-status[hidden] { display:none; }
243
+ .scan-status-dot { width:6px; height:6px; border-radius:50%; background:#60a5fa; box-shadow:0 0 0 0 rgba(96,165,250,.48); animation:scan-dot 1.1s ease-out infinite; }
244
+ @keyframes scan-status-in { from { opacity:0; transform:translateY(-4px); } to { opacity:1; transform:translateY(0); } }
245
+ @keyframes scan-dot { 65% { box-shadow:0 0 0 5px rgba(103,232,249,0); } 100% { box-shadow:0 0 0 0 rgba(103,232,249,0); } }
246
+
247
+ #video, #overlay {
248
+ position: absolute;
249
+ inset: 0;
250
+ width: 100%;
251
+ height: 100%;
252
+ object-fit: contain;
253
+ }
254
+
255
+ #video { background: #000; }
256
+ #overlay { pointer-events: none; }
257
+
258
+ /* Persistent mode context, anchored to the stage itself rather than only the
259
+ sidebar — the same "always know what you're looking at" pattern a
260
+ Procore/Autodesk canvas keeps visible regardless of scroll position or,
261
+ on mobile, whether the settings sheet is even open. */
262
+ /* Bottom-left, not top-left. Detection labels are drawn above their boxes
263
+ and clamp to the top edge when a box runs off frame, so the top-left
264
+ corner is exactly where overlay labels pile up — the badge was landing on
265
+ top of "Building 83%" on a normal skyline shot. Nothing is ever drawn
266
+ below the bottom-most box, so this corner stays clear. */
267
+ .stage-caption {
268
+ position: absolute;
269
+ bottom: 10px;
270
+ left: 10px;
271
+ z-index: 6;
272
+ display: flex;
273
+ align-items: center;
274
+ gap: 7px;
275
+ padding: 6px 9px;
276
+ border: 1px solid rgba(203, 213, 225, 0.2);
277
+ background: rgba(8, 18, 32, 0.84);
278
+ color: #ffffff;
279
+ border-radius: 5px;
280
+ font-size: 0.68rem;
281
+ font-weight: 650;
282
+ letter-spacing: 0.055em;
283
+ text-transform: uppercase;
284
+ box-shadow: 0 3px 12px rgba(0,0,0,.16);
285
+ pointer-events: none;
286
+ }
287
+
288
+ .stage-caption .mode-icon { color: #ffffff; }
289
+
290
+ /* With no source loaded there's nothing on the stage to caption, and the
291
+ badge landed directly on top of the empty state's heading on a narrow
292
+ screen. The active mode tab already says which mode you're in, so the
293
+ badge has no job here until there's a frame under it. */
294
+ .stage-frame:not(.has-source) .stage-caption { display: none; }
295
+
296
+ /* Centered when it fits, scrollable when it doesn't. The old fixed
297
+ `justify-content: center` silently pushed content past the frame's clipped
298
+ edges on a short stage — on a 390x844 phone the "Upload Photo/Video"
299
+ button landed 45px below the frame's bottom and was simply unreachable,
300
+ which is a dead end on the device this app is most used from. `margin:
301
+ auto` on the inner block centers exactly like the old rule while still
302
+ letting overflow scroll into reach, so this holds at any viewport rather
303
+ than at the sizes that happened to be checked. */
304
+ .empty-state {
305
+ position: absolute;
306
+ inset: 0;
307
+ display: flex;
308
+ flex-direction: column;
309
+ text-align: center;
310
+ padding: 40px;
311
+ overflow-y: auto;
312
+ overscroll-behavior: contain;
313
+ color: #e8edf3;
314
+ }
315
+
316
+ .empty-state-inner {
317
+ margin: auto;
318
+ display: flex;
319
+ flex-direction: column;
320
+ align-items: center;
321
+ gap: 12px;
322
+ width: 100%;
323
+ }
324
+
325
+ /* Line-art mark rather than the 🏙️ emoji this used to be: emoji render at
326
+ the mercy of the platform's own font (a flat blue-grey block on this
327
+ machine at 2.4rem, out of key with every other icon in the app), and the
328
+ header/panel icons are already an SVG sprite set — this now matches them. */
329
+ .empty-icon {
330
+ color: #6d86a6;
331
+ display: flex;
332
+ }
333
+
334
+ .empty-hint {
335
+ font-size: 0.78rem;
336
+ color: #6d7c90;
337
+ margin: 2px 0 0;
338
+ }
339
+
340
+ .empty-state h2 {
341
+ font-size: 1.3rem;
342
+ font-weight: 700;
343
+ margin: 0;
344
+ max-width: 26ch;
345
+ }
346
+
347
+ .empty-state p {
348
+ color: #98a5b8;
349
+ max-width: 42ch;
350
+ margin: 0;
351
+ font-size: 0.9rem;
352
+ line-height: 1.5;
353
+ }
354
+
355
+ .empty-actions {
356
+ display: flex;
357
+ gap: 10px;
358
+ margin-top: 8px;
359
+ flex-wrap: wrap;
360
+ justify-content: center;
361
+ }
362
+
363
+ .stage-frame.drag-active {
364
+ outline: 2px dashed var(--accent);
365
+ outline-offset: -2px;
366
+ }
367
+
368
+ .loading-overlay[hidden] { display: none; }
369
+
370
+ .loading-overlay {
371
+ position: absolute;
372
+ inset: 0;
373
+ display: flex;
374
+ flex-direction: column;
375
+ align-items: center;
376
+ justify-content: center;
377
+ gap: 12px;
378
+ background: rgba(5, 7, 10, 0.91);
379
+ font-size: 0.9rem;
380
+ color: #b6c0cf;
381
+ letter-spacing: .025em;
382
+ backdrop-filter: blur(2px);
383
+ }
384
+
385
+ .spinner {
386
+ width: 28px;
387
+ height: 28px;
388
+ border-radius: 50%;
389
+ border: 3px solid #232b36;
390
+ border-top-color: var(--accent-hover);
391
+ animation: spin 0.8s linear infinite;
392
+ }
393
+
394
+ @keyframes spin { to { transform: rotate(360deg); } }
395
+
396
+ .stage-toolbar {
397
+ display: flex;
398
+ align-items: center;
399
+ gap: 8px;
400
+ }
401
+
402
+ .detection-count {
403
+ margin-left: auto;
404
+ font-size: 0.72rem;
405
+ font-weight: 600;
406
+ letter-spacing: .015em;
407
+ color: var(--text-dim);
408
+ }
409
+ .detection-count.readout-change { animation:readout-change .24s ease-out; }
410
+ @keyframes readout-change { from { opacity:.45; transform:translateY(2px); } to { opacity:1; transform:translateY(0); } }
411
+
412
+ /* ---------- Buttons ---------- */
413
+
414
+ .btn {
415
+ border: 1px solid var(--border);
416
+ background: var(--bg-panel);
417
+ color: var(--text);
418
+ padding: 9px 16px;
419
+ border-radius: var(--radius-sm);
420
+ font-size: 0.85rem;
421
+ font-weight: 600;
422
+ cursor: pointer;
423
+ transition: border-color 0.12s, background 0.12s, box-shadow 0.12s;
424
+ }
425
+
426
+ .btn:hover { border-color: var(--accent); background: var(--accent-soft); }
427
+
428
+ .btn-primary {
429
+ background: var(--accent);
430
+ border-color: var(--accent);
431
+ color: #ffffff;
432
+ }
433
+
434
+ .btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
435
+
436
+ .btn-secondary {
437
+ background: var(--bg-panel-2);
438
+ }
439
+
440
+ .btn-secondary:hover { background: var(--accent-soft); }
441
+
442
+ .btn-ghost {
443
+ background: transparent;
444
+ border-color: var(--border);
445
+ padding: 7px 14px;
446
+ }
447
+
448
+ /* Buttons and mode tabs had no focus style at all — the browser default is
449
+ suppressed by the custom backgrounds, so keyboard and switch-control users
450
+ had no way to tell what was focused anywhere in the app's primary
451
+ controls. `:focus-visible` rather than `:focus` so a mouse click doesn't
452
+ leave a ring behind. Offset outward so it reads clearly against both the
453
+ filled primary button and the tinted tab bar. */
454
+ .btn:focus-visible,
455
+ .mode-btn:focus-visible,
456
+ .file-btn:focus-within {
457
+ outline: 2px solid var(--accent);
458
+ outline-offset: 2px;
459
+ }
460
+
461
+ /* The active tab is already navy-filled, so a navy ring on it would be
462
+ invisible — it gets a light ring against its own dark background instead. */
463
+ .mode-btn.active:focus-visible,
464
+ .btn-primary:focus-visible {
465
+ outline-color: #ffffff;
466
+ box-shadow: 0 0 0 4px rgba(15, 37, 71, 0.45);
467
+ }
468
+
469
+ .file-btn { display: inline-flex; align-items: center; }
470
+ .btn-full { width: 100%; }
471
+
472
+ /* ---------- Sidebar ---------- */
473
+
474
+ .sidebar {
475
+ display: flex;
476
+ flex-direction: column;
477
+ gap: 12px;
478
+ overflow-y: auto;
479
+ }
480
+
481
+ .panel {
482
+ background: var(--bg-panel);
483
+ border: 1px solid var(--border);
484
+ border-radius: var(--radius);
485
+ padding: 14px;
486
+ transition: box-shadow 0.15s, border-color 0.15s;
487
+ }
488
+
489
+ .panel:hover { box-shadow: var(--shadow-xs); }
490
+
491
+ .panel-title {
492
+ display: flex;
493
+ align-items: center;
494
+ font-size: 0.8rem;
495
+ text-transform: uppercase;
496
+ letter-spacing: 0.04em;
497
+ color: var(--accent);
498
+ margin: 0 0 8px;
499
+ font-weight: 700;
500
+ }
501
+
502
+ /* ---------- Stat tiles (Job Site / BIM) ---------- */
503
+ /* A live KPI row — the same "number, then its label, in a small card" pattern
504
+ a PowerBI/Procore dashboard leads with, instead of burying these same
505
+ figures only in canvas-drawn overlay text or a plain sentence. */
506
+
507
+ .stat-tiles {
508
+ display: grid;
509
+ grid-template-columns: repeat(3, 1fr);
510
+ gap: 6px;
511
+ margin: 0 0 14px;
512
+ }
513
+
514
+ .stat-tile {
515
+ display: flex;
516
+ flex-direction: column;
517
+ gap: 2px;
518
+ padding: 8px 6px;
519
+ background: var(--bg-panel-2);
520
+ border: 1px solid var(--border);
521
+ border-radius: var(--radius-sm);
522
+ text-align: center;
523
+ }
524
+
525
+ .stat-value {
526
+ font-size: 1.05rem;
527
+ font-weight: 700;
528
+ color: var(--accent);
529
+ line-height: 1.15;
530
+ font-variant-numeric: tabular-nums;
531
+ }
532
+
533
+ .stat-label {
534
+ font-size: 0.62rem;
535
+ color: var(--text-dim);
536
+ text-transform: uppercase;
537
+ letter-spacing: 0.03em;
538
+ line-height: 1.3;
539
+ }
540
+
541
+ /* A tile left alone on the last row of the 3-up grid spans it instead of
542
+ sitting in a third of the width with two empty cells beside it. That's
543
+ BIM's "Completion stage", the one tile here whose value is a phrase rather
544
+ than a number — "Envelope in progress" was wrapping onto three cramped
545
+ lines in a narrow cell. Full width also lets it lay out as a row (label
546
+ left, value right), which is the right shape for a text value: the other
547
+ tiles are scanned as a row of numbers, this one is read as a sentence.
548
+ Written as "last child that starts a row" so it applies wherever that
549
+ shape occurs rather than being pinned to the BIM panel specifically. */
550
+ .stat-tiles > .stat-tile:last-child:nth-child(3n + 1) {
551
+ grid-column: 1 / -1;
552
+ flex-direction: row-reverse;
553
+ align-items: center;
554
+ justify-content: space-between;
555
+ gap: 10px;
556
+ text-align: left;
557
+ padding: 9px 11px;
558
+ }
559
+
560
+ .stat-tiles > .stat-tile:last-child:nth-child(3n + 1) .stat-value {
561
+ font-size: 0.9rem;
562
+ text-align: right;
563
+ }
564
+
565
+ .stat-tiles > .stat-tile:last-child:nth-child(3n + 1) .stat-label {
566
+ flex: 0 0 auto;
567
+ }
568
+
569
+ /* Four figures of the same kind (Drone): a 2x2 block, not three plus a
570
+ stretched fourth — the span-the-row rule above is for a lone text value. */
571
+ .stat-tiles.quad { grid-template-columns: repeat(2, 1fr); }
572
+ .stat-tiles.quad > .stat-tile:last-child:nth-child(3n + 1) {
573
+ grid-column: auto;
574
+ flex-direction: column;
575
+ text-align: center;
576
+ gap: 2px;
577
+ padding: 8px 6px;
578
+ }
579
+ .stat-tiles.quad > .stat-tile:last-child:nth-child(3n + 1) .stat-value { font-size: 1.05rem; text-align: center; }
580
+
581
+ /* Drone land-cover breakdown: one stacked bar (the whole frame) + legend. */
582
+ .land-cover { margin: 0 0 14px; }
583
+ .land-cover-bar {
584
+ display: flex;
585
+ height: 12px;
586
+ border-radius: var(--radius-sm);
587
+ overflow: hidden;
588
+ background: var(--bg-subtle);
589
+ border: 1px solid var(--border);
590
+ }
591
+ .land-cover-bar > span { flex-basis: 0; min-width: 2px; }
592
+ .land-cover-bar > span + span { box-shadow: -1px 0 0 var(--bg-panel); }
593
+ .land-cover-legend {
594
+ list-style: none;
595
+ margin: 8px 0 0;
596
+ padding: 0;
597
+ display: grid;
598
+ gap: 3px;
599
+ font-size: 0.74rem;
600
+ }
601
+ .land-cover-legend li { display: flex; align-items: center; gap: 7px; min-width: 0; }
602
+ .land-cover-legend i { flex: 0 0 10px; height: 10px; border-radius: 2px; }
603
+ .land-cover-legend span { flex: 1 1 auto; color: var(--text-dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
604
+ .land-cover-legend b { font-weight: 600; color: var(--text); font-variant-numeric: tabular-nums; }
605
+
606
+ .drone-scale { display: grid; gap: 8px; margin: 0 0 12px; border: 0; padding: 0; min-width: 0; }
607
+ .drone-scale legend { font-size: 0.82rem; font-weight: 600; color: var(--text); padding: 0 0 6px; }
608
+ .drone-scale label { display: grid; gap: 4px; font-size: 0.78rem; color: var(--text-dim); }
609
+ .drone-scale .panel-hint { margin: 0; }
610
+
611
+ /* ---------- Toggle groups ---------- */
612
+ /* A tinted card around a set of related checkboxes — the same "grouped
613
+ settings" convention Procore/Autodesk panels use so a cluster of options
614
+ reads as one decision ("which element types") rather than a flat list of
615
+ unrelated checkboxes. */
616
+
617
+ .toggle-group {
618
+ background: var(--bg-panel-2);
619
+ border: 1px solid var(--border);
620
+ border-radius: var(--radius-sm);
621
+ padding: 10px 12px;
622
+ }
623
+
624
+ .panel-hint {
625
+ font-size: 0.78rem;
626
+ line-height: 1.5;
627
+ color: var(--text-dim);
628
+ margin: 0 0 12px;
629
+ }
630
+
631
+ .field {
632
+ display: flex;
633
+ flex-direction: column;
634
+ gap: 6px;
635
+ font-size: 0.82rem;
636
+ margin-bottom: 10px;
637
+ }
638
+
639
+ .field:last-child { margin-bottom: 0; }
640
+
641
+ .field.checkbox {
642
+ flex-direction: row;
643
+ align-items: center;
644
+ gap: 8px;
645
+ }
646
+
647
+ .field input[type="range"] { accent-color: var(--accent); }
648
+ .field input[type="color"] {
649
+ width: 100%;
650
+ height: 32px;
651
+ border: 1px solid var(--border);
652
+ border-radius: var(--radius-sm);
653
+ background: none;
654
+ padding: 2px;
655
+ }
656
+
657
+ .class-filter {
658
+ border: none;
659
+ padding: 0;
660
+ margin: 0 0 10px;
661
+ }
662
+
663
+ .class-filter legend {
664
+ display: flex;
665
+ align-items: center;
666
+ gap: 8px;
667
+ width: 100%;
668
+ font-size: 0.82rem;
669
+ padding: 0 0 6px;
670
+ color: var(--text);
671
+ font-weight: 600;
672
+ }
673
+
674
+ .filter-actions { display:inline-flex; gap:4px; margin-left:auto; }
675
+ .filter-actions button { min-height:28px; padding:3px 8px; border:1px solid var(--border); border-radius:4px; background:var(--bg-panel); color:var(--text-dim); font-family:inherit; font-size:11px; font-weight:600; line-height:1; cursor:pointer; }
676
+ .filter-actions button:hover { color:var(--accent); border-color:var(--accent); background:var(--accent-soft); }
677
+ .filter-actions button:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
678
+
679
+ .class-filter label {
680
+ display: flex;
681
+ align-items: center;
682
+ gap: 8px;
683
+ font-size: 0.82rem;
684
+ padding: 4px 0;
685
+ color: var(--text);
686
+ }
687
+
688
+ .about-panel { color: var(--text-dim); }
689
+
690
+ /* Disclosure wrapper applied by collapseLongHints() in main.js. Styled as a
691
+ quiet inline affordance, not a button — it's supporting detail you can open,
692
+ and it shouldn't compete with the panel's actual controls for attention. */
693
+ .hint-details {
694
+ margin: 6px 0 0;
695
+ }
696
+
697
+ .hint-details > summary {
698
+ cursor: pointer;
699
+ list-style: none;
700
+ display: flex;
701
+ align-items: center;
702
+ gap: 5px;
703
+ font-size: 0.75rem;
704
+ font-weight: 600;
705
+ color: var(--text-dim);
706
+ padding: 5px 0;
707
+ user-select: none;
708
+ }
709
+
710
+ .hint-details > summary::-webkit-details-marker { display: none; }
711
+
712
+ /* Own triangle, so it can rotate on open and sit at the size/color the rest
713
+ of the sidebar uses rather than the browser's default marker. */
714
+ .hint-details > summary::before {
715
+ content: "";
716
+ width: 0;
717
+ height: 0;
718
+ border-left: 4px solid currentColor;
719
+ border-top: 3.5px solid transparent;
720
+ border-bottom: 3.5px solid transparent;
721
+ transition: transform 0.15s ease;
722
+ }
723
+
724
+ .hint-details[open] > summary::before { transform: rotate(90deg) translateX(-1px); }
725
+ .hint-details > summary:hover { color: var(--accent); }
726
+
727
+ .hint-details > summary:focus-visible {
728
+ outline: 2px solid var(--accent);
729
+ outline-offset: 2px;
730
+ border-radius: var(--radius-sm);
731
+ }
732
+
733
+ .hint-details .panel-hint.small {
734
+ margin-top: 0;
735
+ padding-left: 9px;
736
+ border-left: 2px solid var(--border);
737
+ }
738
+
739
+ .panel-hint.small {
740
+ font-size: 0.72rem;
741
+ margin-top: -4px;
742
+ }
743
+
744
+ .landmark-permissions {
745
+ display: flex;
746
+ gap: 8px;
747
+ flex-wrap: wrap;
748
+ margin-bottom: 10px;
749
+ }
750
+
751
+ .landmark-permissions .btn {
752
+ flex: 1 1 auto;
753
+ padding: 8px 10px;
754
+ font-size: 0.78rem;
755
+ }
756
+
757
+ .status-text {
758
+ font-size: 0.76rem;
759
+ color: var(--text-dim);
760
+ margin: 0 0 4px;
761
+ }
762
+
763
+ .status-text.active { color: var(--success); }
764
+
765
+ .landmark-list {
766
+ list-style: none;
767
+ margin: 10px 0 0;
768
+ padding: 0;
769
+ display: flex;
770
+ flex-direction: column;
771
+ gap: 6px;
772
+ max-height: 260px;
773
+ overflow-y: auto;
774
+ }
775
+
776
+ .landmark-list li {
777
+ display: flex;
778
+ justify-content: space-between;
779
+ gap: 10px;
780
+ font-size: 0.8rem;
781
+ border: 1px solid var(--border);
782
+ border-radius: var(--radius-sm);
783
+ padding: 7px 10px;
784
+ background: var(--bg-panel-2);
785
+ }
786
+
787
+ .landmark-list .lm-name {
788
+ font-weight: 600;
789
+ overflow: hidden;
790
+ text-overflow: ellipsis;
791
+ white-space: nowrap;
792
+ }
793
+
794
+ .zone-remove-btn {
795
+ flex: 0 0 auto;
796
+ padding: 3px 9px;
797
+ font-size: 0.72rem;
798
+ }
799
+
800
+ .lm-height {
801
+ color: var(--text-dim);
802
+ font-weight: 400;
803
+ font-size: 0.75rem;
804
+ }
805
+
806
+ .landmark-list .lm-meta {
807
+ color: var(--text-dim);
808
+ white-space: nowrap;
809
+ flex: 0 0 auto;
810
+ }
811
+ .safety-entry-copy { display:flex; min-width:0; flex-direction:column; gap:3px; }
812
+ .safety-entry-detail { color:var(--text-dim); font-size:11px; line-height:1.4; overflow-wrap:anywhere; }
813
+
814
+ .landmark-list li.empty {
815
+ color: var(--text-dim);
816
+ justify-content: center;
817
+ font-style: italic;
818
+ }
819
+
820
+ #occupancySparkline {
821
+ width: 100%;
822
+ height: 40px;
823
+ border: 1px solid var(--border);
824
+ border-radius: var(--radius-sm);
825
+ background: var(--bg-panel-2);
826
+ display: block;
827
+ }
828
+
829
+ #overlay.canvas-pointer-active {
830
+ pointer-events: auto;
831
+ cursor: crosshair;
832
+ }
833
+
834
+ .legend-swatch {
835
+ display: inline-block;
836
+ width: 10px;
837
+ height: 10px;
838
+ border-radius: 2px;
839
+ margin-right: 6px;
840
+ flex: 0 0 auto;
841
+ }
842
+
843
+ .reference-input-row[hidden] { display: none; }
844
+
845
+ .reference-input-row {
846
+ display: flex;
847
+ gap: 6px;
848
+ margin-top: 8px;
849
+ }
850
+
851
+ .reference-input-row input {
852
+ flex: 1 1 auto;
853
+ min-width: 0;
854
+ background: var(--bg-panel-2);
855
+ border: 1px solid var(--border);
856
+ border-radius: var(--radius-sm);
857
+ color: var(--text);
858
+ padding: 7px 8px;
859
+ font-size: 0.82rem;
860
+ }
861
+
862
+ .reference-input-row select {
863
+ background: var(--bg-panel-2);
864
+ border: 1px solid var(--border);
865
+ border-radius: var(--radius-sm);
866
+ color: var(--text);
867
+ font-size: 0.82rem;
868
+ padding: 7px 4px;
869
+ }
870
+
871
+ #tradeCategorySelect, #referenceUnitSelect {
872
+ background: var(--bg-panel-2);
873
+ border: 1px solid var(--border);
874
+ border-radius: var(--radius-sm);
875
+ color: var(--text);
876
+ padding: 8px;
877
+ font-size: 0.85rem;
878
+ }
879
+
880
+ .text-input-flex {
881
+ flex: 1 1 auto;
882
+ min-width: 0;
883
+ background: var(--bg-panel-2);
884
+ border: 1px solid var(--border);
885
+ border-radius: var(--radius-sm);
886
+ color: var(--text);
887
+ padding: 8px 10px;
888
+ font-size: 0.82rem;
889
+ }
890
+
891
+ #tradeNoteInput {
892
+ background: var(--bg-panel-2);
893
+ border: 1px solid var(--border);
894
+ border-radius: var(--radius-sm);
895
+ color: var(--text);
896
+ padding: 8px 10px;
897
+ font-size: 0.82rem;
898
+ width: 100%;
899
+ }
900
+
901
+ input[type="text"]:focus, input[type="number"]:focus, select:focus, .text-input-flex:focus {
902
+ outline: none;
903
+ border-color: var(--accent);
904
+ box-shadow: 0 0 0 3px var(--accent-soft);
905
+ }
906
+
907
+ /* ---------- Toggles (checkboxes) ---------- */
908
+ /* Flat, square, native <input type=checkbox> restyled via appearance:none —
909
+ no rounded pill/circle anywhere, a filled navy square with a white
910
+ checkmark when checked. Applies globally so every existing checkbox
911
+ (class filters, safety flags, display panel, etc.) picks this up without
912
+ touching markup. */
913
+
914
+ input[type="checkbox"] {
915
+ appearance: none;
916
+ -webkit-appearance: none;
917
+ width: 16px;
918
+ height: 16px;
919
+ flex: 0 0 auto;
920
+ border: 1.5px solid var(--border-strong);
921
+ border-radius: 3px;
922
+ background: var(--bg-panel);
923
+ cursor: pointer;
924
+ position: relative;
925
+ margin: 0;
926
+ transition: background-color 0.12s, border-color 0.12s;
927
+ }
928
+
929
+ input[type="checkbox"]:hover { border-color: var(--accent); }
930
+
931
+ input[type="checkbox"]:checked {
932
+ background: var(--accent);
933
+ border-color: var(--accent);
934
+ }
935
+
936
+ input[type="checkbox"]:checked::after {
937
+ content: '';
938
+ position: absolute;
939
+ left: 4px;
940
+ top: 1px;
941
+ width: 4px;
942
+ height: 8px;
943
+ border: solid #ffffff;
944
+ border-width: 0 2px 2px 0;
945
+ transform: rotate(45deg);
946
+ }
947
+
948
+ input[type="checkbox"]:focus-visible {
949
+ outline: 2px solid var(--accent);
950
+ outline-offset: 2px;
951
+ }
952
+
953
+ /* ---------- Responsive ---------- */
954
+
955
+ @media (max-width: 860px) {
956
+ .layout {
957
+ display: flex;
958
+ flex-direction: column;
959
+ overflow-y: auto;
960
+ }
961
+ .stage { flex: 0 0 auto; }
962
+ .stage-frame { flex: 0 0 auto; }
963
+ .sidebar { flex: 0 0 auto; overflow: visible; }
964
+ .app-header {
965
+ flex-wrap: wrap;
966
+ }
967
+ .stage-frame {
968
+ min-height: 280px;
969
+ }
970
+ /* iOS Safari auto-zooms the page on focusing any input under 16px — these
971
+ are the ones a user is likely to tap on a phone (text/number fields,
972
+ dropdowns), so they get bumped regardless of their desktop size. */
973
+ input[type="text"],
974
+ input[type="number"],
975
+ select,
976
+ .text-input-flex {
977
+ font-size: 16px;
978
+ }
979
+ .btn,
980
+ .mode-btn {
981
+ min-height: 40px;
982
+ }
983
+ .empty-actions .btn,
984
+ .btn-full {
985
+ min-height: 44px;
986
+ }
987
+ /* The detection-count text (BIM/Electrical stats can run long) was liable
988
+ to get squeezed against the toolbar buttons on a narrow screen — letting
989
+ it wrap to its own full-width row keeps both legible. */
990
+ .stage-toolbar {
991
+ flex-wrap: wrap;
992
+ }
993
+ .detection-count {
994
+ margin-left: 0;
995
+ flex: 1 1 100%;
996
+ text-align: right;
997
+ }
998
+ /* Native range/checkbox controls have a small hit area by default — this
999
+ grows it without changing how big they look, easier to hit precisely
1000
+ with a finger instead of a mouse pointer. */
1001
+ input[type="range"] {
1002
+ height: 28px;
1003
+ }
1004
+ input[type="checkbox"] {
1005
+ width: 20px;
1006
+ height: 20px;
1007
+ }
1008
+ input[type="checkbox"]:checked::after {
1009
+ left: 6px;
1010
+ top: 2px;
1011
+ width: 5px;
1012
+ height: 10px;
1013
+ }
1014
+
1015
+ /* The checkbox graphic grew to 20px above, but the thing a finger actually
1016
+ aims at is the whole label row, and that was still only 20px tall — well
1017
+ under the ~44px every touch guideline asks for, and this app is operated
1018
+ one-handed, outdoors, often in work gloves. Padding the row (rather than
1019
+ inflating the box) keeps the visual density while making the real hit
1020
+ area a comfortable target. */
1021
+ .field.checkbox,
1022
+ .class-filter label,
1023
+ .hint-details > summary {
1024
+ min-height: 44px;
1025
+ padding: 4px 0;
1026
+ align-items: center;
1027
+ }
1028
+
1029
+ /* The stage is the whole point of the app on a phone, and 280px of a
1030
+ 844px screen left it smaller than the settings text below it. Sized
1031
+ against the viewport so it scales with the device instead of being a
1032
+ fixed number tuned for one handset. */
1033
+ .stage-frame {
1034
+ min-height: min(56vh, 460px);
1035
+ }
1036
+
1037
+ /* Three stacked header rows (brand / tabs / status) ate 168px before the
1038
+ stage even started. The brand and the status pills have room to share a
1039
+ row at any phone width, which gives that space back to the stage. */
1040
+ .app-header {
1041
+ gap: 8px;
1042
+ padding: 10px 14px;
1043
+ }
1044
+ .brand { flex: 1 1 auto; }
1045
+ .header-status { order: 2; }
1046
+ .mode-switch { order: 3; flex: 1 1 100%; }
1047
+
1048
+ .empty-state {
1049
+ padding: 20px 16px;
1050
+ }
1051
+ .empty-state h2 {
1052
+ font-size: 1.15rem;
1053
+ }
1054
+ /* Both actions sit on one row rather than stacking — "Upload Photo/Video"
1055
+ is the primary path for anyone reviewing footage shot earlier, and
1056
+ burying it below the fold is what made it unreachable before. */
1057
+ .empty-actions {
1058
+ width: 100%;
1059
+ flex-wrap: nowrap;
1060
+ }
1061
+ .empty-actions .btn {
1062
+ flex: 1 1 0;
1063
+ padding: 9px 8px;
1064
+ justify-content: center;
1065
+ text-align: center;
1066
+ }
1067
+ }
1068
+
1069
+
1070
+ /* ---------- Reduced motion ---------- */
1071
+ /* The spinner, the tab-bar's smooth scroll, and every hover/open transition
1072
+ are decoration; a user who has asked their OS for less motion should not
1073
+ have to sit through them. The spinner keeps a slow rotation rather than
1074
+ freezing outright — a completely static "loading" indicator reads as a
1075
+ hung app, which is worse than no motion at all. */
1076
+ @media (prefers-reduced-motion: reduce) {
1077
+ *, *::before, *::after {
1078
+ animation-duration: 0.01ms !important;
1079
+ animation-iteration-count: 1 !important;
1080
+ transition-duration: 0.01ms !important;
1081
+ scroll-behavior: auto !important;
1082
+ }
1083
+ .spinner {
1084
+ animation-duration: 1.6s !important;
1085
+ animation-iteration-count: infinite !important;
1086
+ }
1087
+ }
1088
+
1089
+ /* ============================================================
1090
+ Landing page
1091
+ ============================================================
1092
+ The app's front door. It shares the app's tokens (navy accent, flat
1093
+ 6px radii, Inter) so the marketing surface and the tool read as one
1094
+ product rather than a template bolted onto a tool. Nothing here is
1095
+ loaded or measured by the app itself — when the shell is revealed the
1096
+ whole landing element is simply removed from the flow. */
1097
+
1098
+ .landing {
1099
+ --lp-max: 1120px;
1100
+ background: var(--bg);
1101
+ color: var(--text);
1102
+ overflow-x: hidden;
1103
+ }
1104
+
1105
+ .landing[hidden] { display: none; }
1106
+
1107
+ /* The app shell fills the viewport via flex on <body>; the landing is a
1108
+ normal scrolling document, so <body> has to stop stretching it. */
1109
+ body:has(.landing:not([hidden])) { display: block; height: auto; }
1110
+
1111
+ .app-shell {
1112
+ display: flex;
1113
+ flex-direction: column;
1114
+ flex: 1 1 auto;
1115
+ min-height: 0;
1116
+ }
1117
+
1118
+ .app-shell[hidden] { display: none; }
1119
+
1120
+ /* ---------- Landing nav ---------- */
1121
+
1122
+ .lp-nav {
1123
+ position: sticky;
1124
+ top: 0;
1125
+ z-index: 20;
1126
+ display: flex;
1127
+ align-items: center;
1128
+ gap: 20px;
1129
+ max-width: var(--lp-max);
1130
+ margin: 0 auto;
1131
+ padding: 14px 24px;
1132
+ background: rgba(255, 255, 255, 0.88);
1133
+ backdrop-filter: saturate(1.6) blur(10px);
1134
+ }
1135
+
1136
+ .lp-brand {
1137
+ display: flex;
1138
+ align-items: center;
1139
+ gap: 8px;
1140
+ margin-right: auto;
1141
+ text-decoration: none;
1142
+ color: var(--accent);
1143
+ font-weight: 700;
1144
+ letter-spacing: -0.01em;
1145
+ }
1146
+
1147
+ .lp-brand .brand-name { font-size: 1.05rem; }
1148
+
1149
+ .lp-nav-links { display: flex; gap: 22px; }
1150
+
1151
+ .lp-nav-links a {
1152
+ color: var(--text-dim);
1153
+ text-decoration: none;
1154
+ font-size: 0.88rem;
1155
+ font-weight: 600;
1156
+ }
1157
+
1158
+ .lp-nav-links a:hover { color: var(--accent); }
1159
+
1160
+ .lp-nav-links a:focus-visible,
1161
+ .lp-brand:focus-visible {
1162
+ outline: 2px solid var(--accent);
1163
+ outline-offset: 3px;
1164
+ border-radius: var(--radius-sm);
1165
+ }
1166
+
1167
+ /* ---------- Hero ---------- */
1168
+
1169
+ .lp-hero {
1170
+ max-width: var(--lp-max);
1171
+ margin: 0 auto;
1172
+ padding: 56px 24px 0;
1173
+ text-align: center;
1174
+ }
1175
+
1176
+ .lp-eyebrow {
1177
+ margin: 0 0 18px;
1178
+ font-size: 0.8rem;
1179
+ font-weight: 700;
1180
+ letter-spacing: 0.06em;
1181
+ text-transform: uppercase;
1182
+ color: var(--text-dim);
1183
+ }
1184
+
1185
+ /* clamp() rather than breakpoints: the headline is the one element that
1186
+ has to hold its line-shape from a 390px phone to a wide desktop. */
1187
+ .lp-h1 {
1188
+ margin: 0 auto 20px;
1189
+ max-width: 18ch;
1190
+ font-size: clamp(2.1rem, 5.4vw, 3.7rem);
1191
+ line-height: 1.05;
1192
+ letter-spacing: -0.03em;
1193
+ font-weight: 800;
1194
+ color: var(--accent);
1195
+ }
1196
+
1197
+ .lp-lede {
1198
+ margin: 0 auto;
1199
+ max-width: 62ch;
1200
+ font-size: clamp(1rem, 1.5vw, 1.15rem);
1201
+ line-height: 1.6;
1202
+ color: var(--text-dim);
1203
+ }
1204
+
1205
+ .lp-cta-row {
1206
+ display: flex;
1207
+ flex-wrap: wrap;
1208
+ gap: 12px;
1209
+ justify-content: center;
1210
+ margin: 28px 0 12px;
1211
+ }
1212
+
1213
+ .btn-lg {
1214
+ padding: 13px 26px;
1215
+ font-size: 0.95rem;
1216
+ font-weight: 700;
1217
+ text-decoration: none;
1218
+ min-height: 48px;
1219
+ align-items: center;
1220
+ }
1221
+
1222
+ .lp-cta-note {
1223
+ margin: 0;
1224
+ font-size: 0.82rem;
1225
+ color: var(--text-dim);
1226
+ }
1227
+
1228
+ /* ---------- Product shot ---------- */
1229
+
1230
+ .lp-shot {
1231
+ margin: 44px 0 0;
1232
+ }
1233
+
1234
+ .lp-shot img {
1235
+ display: block;
1236
+ width: 100%;
1237
+ height: auto;
1238
+ border: 1px solid var(--border);
1239
+ border-radius: var(--radius-lg);
1240
+ box-shadow: var(--shadow-md);
1241
+ background: var(--bg-subtle);
1242
+ }
1243
+
1244
+ .lp-shot figcaption {
1245
+ margin-top: 10px;
1246
+ font-size: 0.78rem;
1247
+ color: var(--text-dim);
1248
+ text-align: center;
1249
+ }
1250
+
1251
+ .lp-shot-inset { margin: 0; }
1252
+ .lp-shot-inset figcaption { text-align: left; }
1253
+
1254
+ /* ---------- Facts strip ---------- */
1255
+ /* Four checkable statements about the product, in place of the customer
1256
+ logos a page like this usually carries — there are no customers to
1257
+ cite, and inventing them is the one thing that would make the page
1258
+ less trustworthy rather than more. */
1259
+
1260
+ .lp-facts {
1261
+ display: grid;
1262
+ grid-template-columns: repeat(4, 1fr);
1263
+ gap: 1px;
1264
+ max-width: var(--lp-max);
1265
+ margin: 64px auto 0;
1266
+ background: var(--border);
1267
+ border: 1px solid var(--border);
1268
+ border-radius: var(--radius);
1269
+ overflow: hidden;
1270
+ }
1271
+
1272
+ .lp-facts > div {
1273
+ display: flex;
1274
+ flex-direction: column;
1275
+ gap: 4px;
1276
+ padding: 22px 18px;
1277
+ background: var(--bg-panel);
1278
+ text-align: center;
1279
+ }
1280
+
1281
+ .lp-facts strong {
1282
+ font-size: 1.9rem;
1283
+ font-weight: 800;
1284
+ color: var(--accent);
1285
+ letter-spacing: -0.02em;
1286
+ font-variant-numeric: tabular-nums;
1287
+ }
1288
+
1289
+ .lp-facts span {
1290
+ font-size: 0.78rem;
1291
+ color: var(--text-dim);
1292
+ line-height: 1.4;
1293
+ }
1294
+
1295
+ /* ---------- Sections ---------- */
1296
+
1297
+ .lp-section {
1298
+ max-width: var(--lp-max);
1299
+ margin: 0 auto;
1300
+ padding: 84px 24px 0;
1301
+ }
1302
+
1303
+ .lp-h2 {
1304
+ margin: 0 0 12px;
1305
+ font-size: clamp(1.5rem, 3vw, 2.2rem);
1306
+ line-height: 1.15;
1307
+ letter-spacing: -0.02em;
1308
+ font-weight: 800;
1309
+ color: var(--accent);
1310
  }
1311
 
1312
+ .lp-h3 {
1313
+ margin: 0 0 10px;
1314
+ font-size: 1.05rem;
1315
+ font-weight: 700;
1316
+ color: var(--accent);
1317
  }
1318
 
1319
+ .lp-sub {
1320
+ margin: 0 0 32px;
1321
+ max-width: 60ch;
1322
+ color: var(--text-dim);
1323
+ line-height: 1.6;
1324
  }
1325
 
1326
+ .lp-body {
1327
+ margin: 0 0 20px;
1328
+ max-width: 54ch;
1329
+ color: var(--text-dim);
1330
+ line-height: 1.65;
 
1331
  }
1332
 
1333
+ /* ---------- Modes grid ---------- */
1334
+
1335
+ .lp-modes {
1336
+ display: grid;
1337
+ grid-template-columns: repeat(3, 1fr);
1338
+ gap: 14px;
1339
+ margin: 0;
1340
+ padding: 0;
1341
+ list-style: none;
1342
  }
1343
+
1344
+ .lp-modes li {
1345
+ padding: 20px;
1346
+ background: var(--bg-panel);
1347
+ border: 1px solid var(--border);
1348
+ border-radius: var(--radius);
1349
+ transition: border-color 0.15s, box-shadow 0.15s, transform 0.15s;
1350
+ }
1351
+
1352
+ .lp-modes li:hover {
1353
+ border-color: var(--border-strong);
1354
+ box-shadow: var(--shadow-sm);
1355
+ transform: translateY(-2px);
1356
+ }
1357
+
1358
+ .lp-modes svg {
1359
+ width: 22px;
1360
+ height: 22px;
1361
+ color: var(--accent);
1362
+ margin-bottom: 12px;
1363
+ }
1364
+
1365
+ .lp-modes h4 {
1366
+ margin: 0 0 6px;
1367
+ font-size: 0.98rem;
1368
+ font-weight: 700;
1369
+ color: var(--text);
1370
+ }
1371
+
1372
+ .lp-modes p {
1373
+ margin: 0;
1374
+ font-size: 0.85rem;
1375
+ line-height: 1.55;
1376
+ color: var(--text-dim);
1377
+ }
1378
+
1379
+ /* ---------- Split section ---------- */
1380
+
1381
+ .lp-split {
1382
+ display: grid;
1383
+ grid-template-columns: 1fr 1fr;
1384
+ gap: 48px;
1385
+ align-items: center;
1386
+ }
1387
+
1388
+ .lp-checks {
1389
+ margin: 0;
1390
+ padding: 0;
1391
+ list-style: none;
1392
+ display: flex;
1393
+ flex-direction: column;
1394
+ gap: 12px;
1395
+ }
1396
+
1397
+ .lp-checks li {
1398
+ position: relative;
1399
+ padding-left: 28px;
1400
+ font-size: 0.9rem;
1401
+ line-height: 1.55;
1402
+ color: var(--text-dim);
1403
+ }
1404
+
1405
+ .lp-checks li::before {
1406
+ content: "";
1407
+ position: absolute;
1408
+ left: 4px;
1409
+ top: 6px;
1410
+ width: 6px;
1411
+ height: 11px;
1412
+ border: solid var(--success);
1413
+ border-width: 0 2px 2px 0;
1414
+ transform: rotate(45deg);
1415
+ }
1416
+
1417
+ /* ---------- Steps ---------- */
1418
+
1419
+ .lp-steps {
1420
+ display: grid;
1421
+ grid-template-columns: repeat(3, 1fr);
1422
+ gap: 20px;
1423
+ margin: 0;
1424
+ padding: 0;
1425
+ list-style: none;
1426
+ counter-reset: none;
1427
+ }
1428
+
1429
+ .lp-steps li {
1430
+ padding: 24px 20px;
1431
+ background: var(--bg-panel-2);
1432
+ border-radius: var(--radius);
1433
+ }
1434
+
1435
+ .lp-step-n {
1436
+ display: inline-flex;
1437
+ align-items: center;
1438
+ justify-content: center;
1439
+ width: 30px;
1440
+ height: 30px;
1441
+ margin-bottom: 14px;
1442
+ border-radius: 50%;
1443
+ background: var(--accent);
1444
+ color: #ffffff;
1445
+ font-size: 0.85rem;
1446
+ font-weight: 700;
1447
+ }
1448
+
1449
+ .lp-steps h4 {
1450
+ margin: 0 0 6px;
1451
+ font-size: 1rem;
1452
+ font-weight: 700;
1453
+ color: var(--text);
1454
+ }
1455
+
1456
+ .lp-steps p {
1457
+ margin: 0;
1458
+ font-size: 0.87rem;
1459
+ line-height: 1.55;
1460
+ color: var(--text-dim);
1461
+ }
1462
+
1463
+ /* ---------- Honest-limits block ---------- */
1464
+ /* Deliberately quiet and late in the page, but present: the app states a
1465
+ limitation at every point it makes a claim, and a landing page that
1466
+ dropped that voice would be overselling what the tool does. */
1467
+
1468
+ .lp-honest {
1469
+ max-width: 820px;
1470
+ }
1471
+
1472
+ .lp-honest p {
1473
+ margin: 0;
1474
+ padding: 20px 22px;
1475
+ background: var(--bg-panel-2);
1476
+ border-left: 3px solid var(--warning);
1477
+ border-radius: var(--radius-sm);
1478
+ font-size: 0.87rem;
1479
+ line-height: 1.65;
1480
+ color: var(--text-dim);
1481
+ }
1482
+
1483
+ /* ---------- Final CTA + footer ---------- */
1484
+
1485
+ .lp-final {
1486
+ max-width: var(--lp-max);
1487
+ margin: 96px auto 0;
1488
+ padding: 64px 24px;
1489
+ text-align: center;
1490
+ background: var(--bg-panel-2);
1491
+ border-top: 1px solid var(--border);
1492
+ border-bottom: 1px solid var(--border);
1493
+ }
1494
+
1495
+ .lp-final p {
1496
+ margin: 0 0 26px;
1497
+ color: var(--text-dim);
1498
+ }
1499
+
1500
+ .lp-footer {
1501
+ display: flex;
1502
+ flex-wrap: wrap;
1503
+ align-items: center;
1504
+ gap: 8px 18px;
1505
+ max-width: var(--lp-max);
1506
+ margin: 0 auto;
1507
+ padding: 28px 24px 44px;
1508
+ color: var(--text-dim);
1509
+ font-size: 0.82rem;
1510
+ }
1511
+
1512
+ .lp-footer p { margin: 0; }
1513
+
1514
+ /* ---------- Landing responsive ---------- */
1515
+
1516
+ @media (max-width: 900px) {
1517
+ .lp-modes { grid-template-columns: repeat(2, 1fr); }
1518
+ .lp-split { grid-template-columns: 1fr; gap: 32px; }
1519
+ .lp-facts { grid-template-columns: repeat(2, 1fr); }
1520
+ .lp-steps { grid-template-columns: 1fr; }
1521
+ }
1522
+
1523
+ @media (max-width: 620px) {
1524
+ /* The section anchors are the first thing to go: the sticky bar has to
1525
+ keep the brand and the CTA, and those are what the page is for. */
1526
+ .lp-nav-links { display: none; }
1527
+ .lp-nav { padding: 10px 16px; }
1528
+ .lp-hero { padding-top: 36px; }
1529
+ .lp-section { padding: 56px 16px 0; }
1530
+ .lp-modes { grid-template-columns: 1fr; }
1531
+ .lp-cta-row .btn { flex: 1 1 100%; justify-content: center; }
1532
+ .lp-final { margin-top: 64px; padding: 48px 16px; }
1533
+ .lp-footer { padding: 24px 16px 36px; }
1534
+ }
1535
+
1536
+ /* The app header's brand doubles as the way back to the landing page, so it
1537
+ has to be a real button — but it must not look like one sitting in the
1538
+ header, so it inherits the brand's own type and colour. */
1539
+ .brand-home {
1540
+ display: flex;
1541
+ align-items: center;
1542
+ gap: 8px;
1543
+ padding: 2px 4px;
1544
+ margin: -2px -4px;
1545
+ border: none;
1546
+ background: none;
1547
+ color: inherit;
1548
+ font: inherit;
1549
+ cursor: pointer;
1550
+ border-radius: var(--radius-sm);
1551
+ }
1552
+
1553
+ .brand-home:hover { background: var(--accent-soft); }
1554
+
1555
+ .brand-home:focus-visible {
1556
+ outline: 2px solid var(--accent);
1557
+ outline-offset: 2px;
1558
+ }
1559
+
1560
+ /* Rotate control: an icon button that carries its current angle as a badge,
1561
+ so a rotated source is obvious from the toolbar without reading the frame. */
1562
+ .rotate-btn {
1563
+ display: inline-flex;
1564
+ align-items: center;
1565
+ gap: 6px;
1566
+ }
1567
+
1568
+ .rotate-btn.is-active {
1569
+ color: var(--accent);
1570
+ border-color: var(--accent);
1571
+ background: var(--accent-soft);
1572
+ }
1573
+
1574
+ .rotation-badge {
1575
+ font-size: 0.7rem;
1576
+ font-weight: 700;
1577
+ font-variant-numeric: tabular-nums;
1578
+ padding: 1px 5px;
1579
+ border-radius: 999px;
1580
+ background: var(--accent);
1581
+ color: #ffffff;
1582
+ }
1583
+
1584
+ /* The <video> keeps playing and keeps feeding the detectors; it just stops
1585
+ being what you look at once the frame is rotated (the overlay canvas paints
1586
+ the rotated frame instead). Opacity rather than display:none so playback
1587
+ and layout are untouched. */
1588
+ .stage-frame.source-rotated #video { opacity: 0; }
1589
+
1590
+ /* Conditional controls must stay hidden when component styles set display. */
1591
+ [hidden] { display: none !important; }
1592
+ .workspace-guide { display:flex; align-items:center; justify-content:space-between; gap:18px; padding:5px 2px 8px; }
1593
+ .workspace-eyebrow { font-size:10px; font-weight:750; letter-spacing:.13em; color:var(--text-dim); }
1594
+ .workspace-guide h2 { margin:5px 0; font-size:20px; letter-spacing:-.025em; }
1595
+ .workspace-guide p { margin:0; font-size:12px; color:var(--text-dim); line-height:1.5; }
1596
+ .mode-picker { display:flex; flex-direction:column; gap:5px; flex-shrink:0; font-size:11px; color:var(--text-dim); }
1597
+ .mode-picker select { min-height:40px; min-width:130px; padding:8px 12px; border:1px solid var(--border); border-radius:6px; background:white; color:var(--text); }
1598
+ .workspace-controls { display:flex; align-items:center; gap:10px; min-height:52px; padding:8px 10px; border:1px solid var(--border); border-radius:7px; background:linear-gradient(180deg,#fff,#f9fbfd); box-shadow:var(--shadow-xs); }
1599
+ .workspace-controls-title { flex:0 0 auto; color:var(--text-dim); font-size:10px; font-weight:750; letter-spacing:.08em; text-transform:uppercase; }
1600
+ .workspace-chip { display:inline-flex; flex:0 0 auto; align-items:center; gap:6px; min-height:32px; padding:5px 9px; border:1px solid var(--border); border-radius:5px; background:#fff; color:#34445a; font-size:11px; font-weight:600; white-space:nowrap; }
1601
+ .workspace-toggle { cursor:pointer; user-select:none; transition:border-color .12s, background .12s, color .12s; }
1602
+ .workspace-toggle:has(input:checked) { border-color:#b7c6d9; background:#eef3f9; color:#142c4c; }
1603
+ .workspace-chip input[type="checkbox"] { width:14px; height:14px; margin:0; }
1604
+ .workspace-chip input[type="checkbox"]:checked::after { left:3px; top:0px; width:4px; height:8px; }
1605
+ .workspace-chip input[type="range"] { width:108px; height:18px; margin:0; accent-color:var(--accent); }
1606
+ .workspace-range-value { min-width:28px; color:var(--accent); text-align:right; font-variant-numeric:tabular-nums; }
1607
+ .workspace-select { gap:8px; }
1608
+ .workspace-select select { min-height:26px; padding:3px 6px; border:1px solid var(--border); border-radius:4px; background:white; color:var(--text); font-size:11px; }
1609
+ .workspace-toggle-list { display:flex; flex:1 1 auto; align-items:center; gap:6px; min-width:0; overflow-x:auto; scrollbar-width:thin; }
1610
+ .workspace-global-labels { margin-left:auto; }
1611
+ .workspace-controls [type="range"]:focus-visible,
1612
+ .workspace-controls select:focus-visible,
1613
+ .workspace-controls input[type="checkbox"]:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
1614
+ .video-review-controls { display:flex; align-items:center; gap:8px; min-height:48px; padding:6px 9px; border:1px solid var(--border); border-radius:7px; background:#f8fafc; }
1615
+ .video-review-controls .btn { min-height:32px; padding:5px 10px; font-size:11px; }
1616
+ .video-review-controls .video-step { min-width:42px; font-variant-numeric:tabular-nums; }
1617
+ .video-play-toggle { min-width:60px; }
1618
+ .video-scrubber-wrap { display:flex; flex:1 1 auto; min-width:60px; align-items:center; }
1619
+ .video-scrubber-wrap input { width:100%; margin:0; accent-color:var(--accent); }
1620
+ .video-time-readout { min-width:88px; color:var(--text-dim); text-align:center; font-size:11px; font-variant-numeric:tabular-nums; }
1621
+ .video-speed-wrap { display:flex; flex:0 0 auto; align-items:center; gap:6px; color:var(--text-dim); font-size:10px; font-weight:600; }
1622
+ .video-speed-wrap select { min-height:30px; padding:4px 6px; border:1px solid var(--border); border-radius:4px; background:white; color:var(--text); font-size:11px; }
1623
+ .video-annotation-hint { margin:-5px 2px 0; color:var(--text-dim); font-size:10px; line-height:1.35; }
1624
+ .sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
1625
+ .bim-baseline-tools { display:flex; gap:7px; margin:0 0 4px; }
1626
+ .bim-baseline-tools .btn { flex:1 1 auto; min-height:34px; padding:6px 9px; font-size:11px; }
1627
+ #bimBaselineNote { margin:4px 0 12px; padding:8px 10px; border:1px solid var(--border); border-radius:5px; background:#f8fafc; line-height:1.45; }
1628
+ .stage-frame:not(.has-source) #video { visibility:hidden; }
1629
+ .stage-frame:not(.has-source) { background-color:#101d30; }
1630
+ .stage-toolbar { flex-wrap:wrap; }
1631
+ .source-name { max-width:100%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:var(--text-dim); font-size:12px; flex-basis:100%; }
1632
+ .source-feedback { padding:11px 14px; border:1px solid #b8cce5; border-radius:6px; background:#eff5fc; color:#153b67; font-size:13px; line-height:1.5; overflow-wrap:anywhere; }
1633
+ .source-feedback[data-tone="error"] { color:#982b2b; background:#fff2f2; border-color:#edcaca; }
1634
+ .source-feedback[data-tone="quality"] { color:#77540a; background:#fff8df; border-color:#ead99f; }
1635
+ .safety-quality-notice { margin:10px 0; padding:10px 12px; border:1px solid #cbd9e8; border-left:4px solid #6d86a6; border-radius:5px; background:#f3f7fb; color:#34475f; font-size:12px; line-height:1.5; }
1636
+ .safety-quality-notice.limited { border-color:#ead99f; border-left-color:#c18a12; background:#fff8df; color:#654908; }
1637
+ .mode-picker select:focus-visible { outline:2px solid var(--accent); outline-offset:3px; }
1638
+ @media (max-width:620px) {
1639
+ .workspace-guide { align-items:flex-start; flex-direction:column; gap:10px; }
1640
+ .workspace-guide h2 { font-size:19px; }
1641
+ .mode-picker { width:100%; flex-direction:row; align-items:center; justify-content:space-between; }
1642
+ .mode-picker select { min-width:170px; }
1643
+ .workspace-controls { align-items:flex-start; flex-wrap:wrap; gap:6px; padding:8px; }
1644
+ .workspace-controls-title { align-self:center; margin-right:2px; }
1645
+ .workspace-toggle-list { order:5; flex-basis:100%; padding-bottom:2px; }
1646
+ .workspace-global-labels { margin-left:auto; }
1647
+ .workspace-chip { min-height:36px; }
1648
+ .workspace-chip input[type="range"] { width:94px; }
1649
+ .video-review-controls { display:grid; grid-template-columns:auto auto minmax(44px,1fr) auto auto; gap:5px; padding:6px; }
1650
+ .video-speed-wrap { grid-column:1 / -1; justify-content:flex-end; }
1651
+ .video-time-readout { min-width:74px; font-size:10px; }
1652
+ .video-review-controls .btn { min-height:40px; }
1653
+ .bim-baseline-tools .btn { min-height:42px; }
1654
+ .stage-frame:not(.has-source) { min-height:360px; }
1655
+ .stage-toolbar .btn { min-height:44px; }
1656
+ }
1657
+
1658
+ .measurement-summary { margin:12px 0 8px; padding:10px 12px; background:var(--accent-soft); border-radius:6px; font-size:12px; line-height:1.5; font-weight:600; color:var(--accent); }
1659
+ #measurementList { max-height:320px; overflow-y:auto; }
1660
+
1661
+ /* ---------- Toggles, v2 ----------
1662
+ Toolbar chips: the checkbox inside each chip is visually hidden and the
1663
+ chip itself carries the state — filled tint + solid mark when on, plain
1664
+ outline + hollow mark when off — so on/off reads at a glance from across
1665
+ the toolbar instead of from a 14px tick. The mark takes the layer's own
1666
+ overlay colour (--chip-color, copied from the panel's legend swatch), so
1667
+ a chip names the boxes it controls on the image. Square corners throughout,
1668
+ matching the flat navy theme. */
1669
+ .workspace-toggle { position: relative; gap: 7px; color: var(--text-dim); font-weight: 600; }
1670
+ .workspace-toggle > input[type="checkbox"] { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; margin: 0; cursor: pointer; border: 0; }
1671
+ .workspace-toggle > input[type="checkbox"]::after { display: none; }
1672
+ .chip-mark {
1673
+ flex: 0 0 auto; width: 10px; height: 10px; border-radius: 2px;
1674
+ border: 1.5px solid var(--chip-color, #8a98ab); background: transparent;
1675
+ transition: background-color .12s, border-color .12s, box-shadow .12s;
1676
+ }
1677
+ .workspace-toggle:hover { border-color: #9fb3cc; color: var(--text); }
1678
+ .workspace-toggle:has(input:checked) { border-color: #9fb3cc; background: var(--accent-soft); color: var(--accent); }
1679
+ .workspace-toggle:has(input:checked) .chip-mark { background: var(--chip-color, var(--accent)); border-color: var(--chip-color, var(--accent)); box-shadow: inset 0 0 0 1.5px rgba(255,255,255,.55); }
1680
+ .workspace-toggle:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
1681
+ .workspace-toggle:active { transform: translateY(1px); }
1682
+
1683
+ /* Named groups (Job Site: Detect / Safety flags / Experimental). On a wide
1684
+ screen the grouped list takes its own full-width row and wraps, so every
1685
+ chip is visible; each group is a labelled cluster. */
1686
+ .workspace-controls:has(.workspace-toggle-list.grouped) { flex-wrap: wrap; row-gap: 8px; }
1687
+ .workspace-toggle-list.grouped { flex-basis: 100%; flex-wrap: wrap; overflow: visible; gap: 6px 14px; padding-top: 8px; border-top: 1px solid var(--border); }
1688
+ .workspace-toggle-group { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
1689
+ .workspace-group-name { flex: 0 0 auto; margin-right: 2px; color: var(--text-dim); font-size: 10px; font-weight: 700; letter-spacing: .06em; text-transform: uppercase; }
1690
+ .workspace-toggle-group + .workspace-toggle-group { padding-left: 14px; border-left: 1px solid var(--border); }
1691
+
1692
+ /* A sideways-scrolling row (phones) fades out at whichever edge has more,
1693
+ so a chip cut off at the edge reads as "more this way". */
1694
+ .workspace-toggle-list.fade-right { -webkit-mask-image: linear-gradient(90deg, #000 calc(100% - 28px), transparent); mask-image: linear-gradient(90deg, #000 calc(100% - 28px), transparent); }
1695
+ .workspace-toggle-list.fade-left { -webkit-mask-image: linear-gradient(90deg, transparent, #000 28px); mask-image: linear-gradient(90deg, transparent, #000 28px); }
1696
+ .workspace-toggle-list.fade-left.fade-right { -webkit-mask-image: linear-gradient(90deg, transparent, #000 28px, #000 calc(100% - 28px), transparent); mask-image: linear-gradient(90deg, transparent, #000 28px, #000 calc(100% - 28px), transparent); }
1697
+
1698
+ /* Slider chip: value reads as part of the control, not a stray number. */
1699
+ .workspace-chip:has(input[type="range"]) { gap: 9px; }
1700
+ .workspace-range-value { padding: 2px 6px; border-radius: 3px; background: var(--accent-soft); font-size: 11px; font-weight: 700; }
1701
+
1702
+ /* Sidebar on/off rows → switches. Label first, the switch in a consistent
1703
+ right-hand column, so a long list of layers and safety flags scans as
1704
+ "what" then "on/off" instead of a ragged column of ticks. Square-cornered
1705
+ track and knob to match the flat theme. Applies to layer/flag rows only;
1706
+ checkboxes elsewhere keep the square tick. */
1707
+ .class-filter label, .field.checkbox { cursor: pointer; }
1708
+ .class-filter label > input[type="checkbox"],
1709
+ .field.checkbox > input[type="checkbox"] {
1710
+ order: 3; margin-left: auto;
1711
+ width: 30px; height: 17px; border: 0; border-radius: 3px;
1712
+ background: #c3ccd8; transition: background-color .15s;
1713
+ }
1714
+ .class-filter label > input[type="checkbox"]::after,
1715
+ .field.checkbox > input[type="checkbox"]::after {
1716
+ content: ''; position: absolute; left: 2px; top: 2px; width: 13px; height: 13px;
1717
+ border: 0; border-radius: 2px; background: #fff; transform: none;
1718
+ box-shadow: 0 1px 2px rgba(15, 37, 71, .25); transition: transform .15s;
1719
+ }
1720
+ .class-filter label > input[type="checkbox"]:checked,
1721
+ .field.checkbox > input[type="checkbox"]:checked { background: var(--accent); }
1722
+ .class-filter label > input[type="checkbox"]:checked::after,
1723
+ .field.checkbox > input[type="checkbox"]:checked::after { left: 2px; top: 2px; width: 13px; height: 13px; border: 0; transform: translateX(13px); }
1724
+ .class-filter label > input[type="checkbox"]:hover:not(:checked),
1725
+ .field.checkbox > input[type="checkbox"]:hover:not(:checked) { background: #aab6c6; }
1726
+ .class-filter label { gap: 10px; }
1727
+ .toggle-group > label + label { border-top: 1px solid rgba(221, 227, 236, .8); }
1728
+ .class-filter label:has(input:not(:checked)) { color: var(--text-dim); }
1729
+ .field.checkbox > span { flex: 1 1 auto; }
1730
+ @media (prefers-reduced-motion: reduce) {
1731
+ .class-filter label > input[type="checkbox"]::after, .field.checkbox > input[type="checkbox"]::after, .chip-mark { transition: none; }
1732
+ }
1733
+
1734
+ /* Header: a long model status ("Loading object detection model…") pushed
1735
+ the mode tabs off the edge ("Dron"). It truncates; the full text is in
1736
+ its title. */
1737
+ .model-status { max-width: 190px; overflow: hidden; text-overflow: ellipsis; display: inline-block; }
1738
+ .mode-switch { min-width: 0; }
1739
+
1740
+ @media (max-width: 860px) {
1741
+ .class-filter label > input[type="checkbox"],
1742
+ .field.checkbox > input[type="checkbox"] { width: 38px; height: 22px; }
1743
+ .class-filter label > input[type="checkbox"]::after,
1744
+ .field.checkbox > input[type="checkbox"]::after,
1745
+ .class-filter label > input[type="checkbox"]:checked::after,
1746
+ .field.checkbox > input[type="checkbox"]:checked::after { width: 18px; height: 18px; }
1747
+ .class-filter label > input[type="checkbox"]:checked::after,
1748
+ .field.checkbox > input[type="checkbox"]:checked::after { transform: translateX(16px); }
1749
+ }
1750
+ @media (max-width: 620px) {
1751
+ /* One sideways row on a phone (13 chips would wrap to five rows); groups
1752
+ stay inline, separated by their names. */
1753
+ .workspace-toggle-list.grouped { flex-wrap: nowrap; overflow-x: auto; padding-top: 6px; }
1754
+ .workspace-toggle-group { flex-wrap: nowrap; }
1755
+ }
1756
+
1757
+ /* ---------- Robot bridge panel ---------- */
1758
+ .robot-advisory { margin: 0 0 12px; padding: 8px 10px; border: 1px solid #ead99f; border-left: 4px solid #c18a12; border-radius: 5px; background: #fff8df; color: #654908; font-size: 0.75rem; line-height: 1.45; }
1759
+ .robot-fields { display: grid; gap: 8px; margin: 0 0 10px; }
1760
+ .robot-fields .field { margin: 0; font-size: 0.75rem; color: var(--text-dim); }
1761
+ .robot-fields input, .robot-fields select { min-height: 32px; padding: 5px 8px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg-panel); color: var(--text); font: inherit; font-size: 0.8rem; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
1762
+ .robot-fields select { font-family: inherit; }
1763
+ .robot-row { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
1764
+ .robot-status { display: flex; align-items: center; gap: 7px; margin: 8px 0 2px; font-size: 0.78rem; font-weight: 600; color: var(--text-dim); overflow-wrap: anywhere; }
1765
+ .robot-status::before { content: ''; flex: 0 0 8px; height: 8px; border-radius: 2px; background: #aab6c6; }
1766
+ .robot-status[data-state="connected"] { color: var(--success); }
1767
+ .robot-status[data-state="connected"]::before { background: var(--success); }
1768
+ .robot-status[data-state="connecting"]::before { background: var(--accent); }
1769
+ .robot-status[data-state="retrying"], .robot-status[data-state="error"] { color: #982b2b; }
1770
+ .robot-status[data-state="retrying"]::before, .robot-status[data-state="error"]::before { background: var(--danger); }
1771
+ #robotPanel code { font-size: 0.72rem; padding: 0 3px; border-radius: 3px; background: var(--bg-subtle); overflow-wrap: anywhere; }
1772
+ #rosDownloadBtn { margin-top: 6px; }
1773
+ @media (max-width: 860px) { .robot-fields input, .robot-fields select { font-size: 16px; min-height: 40px; } }
1774
+ .robot-fields .field, .robot-row > * { min-width: 0; }
1775
+ .robot-fields input, .robot-fields select { width: 100%; box-sizing: border-box; }
1776
+
1777
+ /* ---------- Progress mode ---------- */
1778
+ .progress-trades { display: grid; gap: 6px; margin: 4px 0 12px; }
1779
+ .progress-trade { display: grid; grid-template-columns: minmax(84px, 1fr) 2fr; grid-template-rows: auto auto; column-gap: 8px; align-items: center; font-size: 12px; }
1780
+ .progress-trade-name { font-weight: 600; color: var(--text); }
1781
+ .progress-bar { position: relative; height: 8px; background: var(--bg-subtle); border: 1px solid var(--border); border-radius: 2px; overflow: hidden; }
1782
+ .progress-bar i { position: absolute; inset: 0 auto 0 0; transition: width 0.3s ease; }
1783
+ .progress-trade-status { grid-column: 2; color: var(--text-dim); font-size: 11px; }
1784
+ .progress-plan { margin: 0 0 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 6px 8px; }
1785
+ .progress-plan summary { cursor: pointer; font-weight: 600; font-size: 12px; }
1786
+ .progress-plan-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0 8px; }
1787
+ .progress-plan-grid .field { margin-bottom: 6px; }
1788
+ .progress-plan-grid input, .progress-plan-grid select { width: 100%; min-width: 0; }
1789
+ .progress-save { display: grid; gap: 4px; margin-bottom: 10px; }
1790
+ .progress-changes { font-size: 12px; margin-bottom: 6px; }
1791
+ .progress-changes p { margin: 2px 0; }
1792
+ .progress-changes-head { color: var(--text-dim); }
1793
+ .progress-change.advanced { color: var(--success); }
1794
+ .progress-change.regressed { color: var(--danger); }
1795
+ .progress-timeline { list-style: none; margin: 0 0 10px; padding: 0; display: grid; gap: 6px; max-height: 260px; overflow-y: auto; }
1796
+ .progress-timeline li { display: flex; gap: 8px; align-items: center; font-size: 12px; padding: 4px; border: 1px solid var(--border); border-radius: var(--radius-sm); }
1797
+ .progress-timeline img { width: 64px; height: 48px; object-fit: cover; border-radius: 2px; flex: none; }
1798
+ .progress-actions { display: grid; gap: 6px; }
1799
+ .progress-confirm { font-size: 12px; margin: 0; }
1800
+ /* Progress → Project: schedule status, all-areas dashboard, floor plan with pins */
1801
+ .progress-project { margin: 10px 0 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 6px 8px; }
1802
+ .progress-project > summary { cursor: pointer; font-weight: 600; font-size: 12px; }
1803
+ .progress-project > .field { margin-bottom: 6px; }
1804
+ .progress-project > .field input { width: 100%; min-width: 0; }
1805
+ .progress-sched-status { font-size: 12px; margin: 0 0 8px; padding-left: 8px; border-left: 3px solid var(--c, transparent); color: var(--text); }
1806
+ .progress-sched-status:empty { display: none; }
1807
+ .progress-dashboard { font-size: 12px; margin-bottom: 8px; }
1808
+ .progress-kpis { margin: 0 0 6px; color: var(--text-dim); }
1809
+ .progress-attention { list-style: none; margin: 0 0 8px; padding: 0; display: grid; gap: 4px; }
1810
+ .progress-attention li { display: grid; grid-template-columns: auto 1fr; column-gap: 6px; align-items: baseline; }
1811
+ .progress-attention-why { grid-column: 1 / -1; color: var(--text-dim); font-size: 11px; }
1812
+ .progress-status-tag { font-size: 11px; padding: 0 6px; border: 1px solid var(--c); color: var(--c); border-radius: 9px; white-space: nowrap; }
1813
+ .progress-area-link { background: none; border: 0; padding: 0; font: inherit; font-weight: 600; color: var(--text); text-align: left; cursor: pointer; text-decoration: underline; text-underline-offset: 2px; min-width: 0; overflow-wrap: anywhere; }
1814
+ .progress-floors { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
1815
+ .progress-floors th, .progress-floors td { text-align: left; padding: 2px 4px; border-bottom: 1px solid var(--border); }
1816
+ .progress-floors th { color: var(--text-dim); font-weight: 600; font-size: 11px; }
1817
+ .progress-floorplan { margin: 6px 0 8px; }
1818
+ .progress-plan-upload { display: block; width: 100%; text-align: center; margin-bottom: 6px; cursor: pointer; box-sizing: border-box; }
1819
+ .progress-plan-canvas { display: block; width: 100%; border: 1px solid var(--border); border-radius: var(--radius-sm); cursor: crosshair; margin-top: 4px; }
1820
+ .progress-plan-canvas[hidden] { display: none; }
1821
+ /* BIM → Facade progress by floor */
1822
+ .facade-floors { display: grid; gap: 3px; margin: 2px 0 8px; max-height: 320px; overflow-y: auto; }
1823
+ .facade-floor { display: grid; grid-template-columns: 58px 1fr auto; gap: 6px; align-items: center; font-size: 11px; }
1824
+ .facade-floor-name { font-weight: 600; color: var(--text); }
1825
+ .facade-floor-status { color: var(--text-dim); white-space: nowrap; }
1826
+ /* Progress → Project: curve, schedule import, project files */
1827
+ .progress-curve { position: relative; margin: 0 0 8px; color: var(--text); }
1828
+ .progress-curve:empty { display: none; }
1829
+ .progress-project-files { display: grid; gap: 6px; margin-top: 8px; }
1830
+ .progress-file-btn { display: block; text-align: center; cursor: pointer; box-sizing: border-box; }
1831
+ .schedule-preview { font-size: 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 6px 8px; display: grid; gap: 4px; }
1832
+ .schedule-preview ul { margin: 0; padding-left: 16px; color: var(--text-dim); max-height: 120px; overflow-y: auto; }
1833
+ .schedule-preview .schedule-actions { display: flex; gap: 6px; }
1834
+ .survey-preview { margin: 4px 0 8px; border: 1px solid var(--border); border-radius: var(--radius-sm); }
1835
+ .survey-preview:empty { display: none; }
1836
+ /* AI assistant */
1837
+ .ai-key-row { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; margin-bottom: 4px; }
1838
+ .ai-key-row .field.checkbox { margin: 0; flex: 1 1 auto; }
1839
+ .ai-conversation { display: grid; gap: 8px; margin: 4px 0 8px; max-height: 420px; overflow-y: auto; }
1840
+ .ai-conversation:empty { display: none; }
1841
+ .ai-msg { font-size: 13px; line-height: 1.45; padding: 6px 8px; border-radius: var(--radius-sm); border: 1px solid var(--border); white-space: pre-wrap; overflow-wrap: anywhere; }
1842
+ .ai-msg.user { background: var(--bg-subtle); }
1843
+ .ai-msg.error { border-color: var(--danger); color: var(--danger); }
1844
+ .ai-msg .ai-meta { display: block; margin-top: 4px; font-size: 11px; color: var(--text-dim); white-space: normal; }
1845
+ .ai-actions { display: flex; gap: 6px; margin-bottom: 6px; }
1846
+ .ai-actions .btn-primary { flex: 1; }
1847
+ #aiQuestion { width: 100%; box-sizing: border-box; resize: vertical; font: inherit; }
1848
+ /* Progress → Video walkthrough */
1849
+ .walk-seg-suggested { font-size: 11px; color: var(--text-dim); margin-top: -3px; }
1850
+ .progress-trade-dates { margin: 0 0 8px; }
1851
+ .progress-trade-dates > summary { cursor: pointer; font-size: 12px; font-weight: 600; }
1852
+ .progress-trade-date-rows { display: grid; gap: 4px; }
1853
+ .progress-trade-date-row { display: grid; grid-template-columns: minmax(70px, 1fr) 1fr 1fr; gap: 4px; align-items: center; font-size: 11px; }
1854
+ .progress-trade-date-row input { min-width: 0; width: 100%; box-sizing: border-box; font-size: 11px; }
1855
+ .progress-scale-row { font-size: 12px; margin: 0 0 6px; }
1856
+ .progress-scale-row input { width: 80px; }
1857
+ .progress-quantities { margin: 0 0 6px; color: var(--text-dim); }
1858
+ .walk-buttons { display: flex; gap: 6px; align-items: flex-end; }
1859
+ .walk-buttons .btn { flex: 1; }
1860
+ .walk-progress { width: 100%; height: 6px; margin: 0 0 6px; }
1861
+ .walk-progress[hidden] { display: none; }
1862
+ .walk-segments { list-style: none; margin: 0 0 8px; padding: 0; display: grid; gap: 8px; }
1863
+ .walk-seg { border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 6px; display: grid; gap: 6px; }
1864
+ .walk-seg-head { display: flex; gap: 8px; align-items: flex-start; font-size: 12px; }
1865
+ .walk-seg-head img { width: 96px; height: 54px; object-fit: cover; border-radius: 2px; flex: none; }
1866
+ .walk-seg-head div { display: grid; gap: 2px; min-width: 0; }
1867
+ .walk-seg-summary { color: var(--text-dim); font-size: 11px; }
1868
+ .walk-seg-name { width: 100%; min-width: 0; box-sizing: border-box; }
1869
+ .walk-seg-actions:empty { display: none; }
1870
+ .walk-strip { display: flex; gap: 3px; overflow-x: auto; padding-bottom: 2px; }
1871
+ .walk-strip button { padding: 0; border: 1px solid var(--border); border-radius: 2px; background: none; cursor: pointer; flex: none; line-height: 0; }
1872
+ .walk-strip button:disabled { cursor: default; outline: 2px solid var(--accent); outline-offset: -2px; }
1873
+ .walk-strip img { width: 48px; height: 27px; object-fit: cover; }
1874
+ @media (prefers-reduced-motion: reduce) { .progress-bar i { transition: none; } }