@floless/app 0.112.1 → 0.113.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -140,3 +140,172 @@ export function normalizeFilter(filter) {
140
140
  const active = (n === 0 || a < 0 || a >= n) ? 0 : a;
141
141
  return { sheets, active };
142
142
  }
143
+
144
+ /**
145
+ * One framing-plan sheet's one-line label for the switcher — "S-202 · Second Floor Framing".
146
+ *
147
+ * Pulled out of the page because the themed combobox needs the SAME string in two places (the closed
148
+ * trigger and the open option row), and two copies of a fallback rule is exactly how the two drift
149
+ * into disagreeing about what a sheet is called. The native <select> it replaced needed it once.
150
+ *
151
+ * Every part of a sheet's identity is drawing-derived, so nothing here may assume a string: an object
152
+ * reaching String() renders the literal "[object Object]" in the header, which is why `null`/`undefined`
153
+ * and anything `typeof === 'object'` (objects, arrays) drop to the "Sheet N" fallback rather than being
154
+ * coerced. The index is 1-based for humans, and the separator appears only when there IS a title — a
155
+ * numbered sheet with no title must not show a dangling "·".
156
+ */
157
+ export function sheetLabel(sheet, i) {
158
+ const s = (sheet && typeof sheet === 'object') ? sheet : {};
159
+ const text = (v) => (v == null || typeof v === 'object') ? '' : String(v).trim();
160
+ // The floor is part of the contract, not caller hygiene: "Sheet 0" (or "Sheet -4") is the exact
161
+ // thing the 1-based rule exists to prevent, so the helper refuses it rather than trusting that both
162
+ // of today's callers happen to clamp. Consistent with already refusing NaN one guard over.
163
+ const n = Number.isFinite(Number(i)) ? Math.max(0, Math.trunc(Number(i))) : 0;
164
+ const name = text(s.sheet) || ('Sheet ' + (n + 1));
165
+ const title = text(s.title);
166
+ return title ? (name + ' · ' + title) : name;
167
+ }
168
+
169
+ /** The transient "this repainted under you" chip copy. Shared with the page and its tests. */
170
+ export const NOTE_TEXT = 'Updated externally';
171
+
172
+ /**
173
+ * The header status chip's class + label for a given state. Pure so the seven states are table-tested:
174
+ * the `stale → 'conflict'` mapping is load-bearing three hops away (the page re-opens a dismissed
175
+ * banner only when the chip carries `conflict`), and a one-word regression there would silently remove
176
+ * the only route back to that banner without failing anything.
177
+ *
178
+ * `badge` is the glyph that goes in a nested <b> — that element is what the `.stat.* b` rules colour.
179
+ * `stale` deliberately shares `conflict`'s class: both mean "what you see no longer matches the
180
+ * server", so they wear one pill and no new colour enters the locked baseline.
181
+ */
182
+ export function statChip(state) {
183
+ switch (state) {
184
+ case 'dirty': return { cls: 'dirty', text: 'Unsaved ', badge: '●' };
185
+ case 'saved': return { cls: 'saved', text: 'Saved ', badge: '✓' };
186
+ case 'err': return { cls: 'err', text: 'Save failed ', badge: '✕' };
187
+ // Not an error: the user's selection is fine, the model simply moved under them.
188
+ case 'conflict': return { cls: 'conflict', text: 'Save conflict', badge: null };
189
+ case 'stale': return { cls: 'conflict', text: 'Out of date', badge: null };
190
+ // Informational, not the result of an action the user took — so no green ✓ for a save that never happened.
191
+ case 'note': return { cls: '', text: NOTE_TEXT, badge: null };
192
+ default: return { cls: '', text: '', badge: null };
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Name a write so its own SSE echo is recognised by IDENTITY rather than by a timing window (a window
198
+ * cannot tell "my echo" from someone else's write landing inside it).
199
+ *
200
+ * `cryptoLike` is injected — the page passes `self.crypto` — so all three tiers are testable. That
201
+ * matters more than it looks: the server SILENTLY drops an id that fails its `MUTATION_ID_RE`
202
+ * (`server/mutation-id.ts`), which strips `mutationId` from the broadcast and makes the tab read its
203
+ * OWN write as external, reloading the page the instant the user saves. Every tier below must produce
204
+ * something that regex accepts.
205
+ *
206
+ * Three tiers because only `randomUUID` requires a secure context, and this page is served over plain
207
+ * http in some dev setups; `getRandomValues` is a real CSPRNG, so the last resort exists only so a
208
+ * missing or throwing `crypto` cannot break saving.
209
+ */
210
+ export function newMutationId(cryptoLike) {
211
+ try {
212
+ if (cryptoLike && typeof cryptoLike.randomUUID === 'function') return cryptoLike.randomUUID();
213
+ if (cryptoLike && typeof cryptoLike.getRandomValues === 'function') {
214
+ const b = cryptoLike.getRandomValues(new Uint8Array(16));
215
+ return 'm-' + Array.from(b, (n) => n.toString(16).padStart(2, '0')).join('');
216
+ }
217
+ } catch (_) { /* fall through to the last resort */ }
218
+ return 'm-' + Date.now().toString(36) + '-'
219
+ + Math.random().toString(36).slice(2, 12) + Math.random().toString(36).slice(2, 12);
220
+ }
221
+
222
+ /**
223
+ * What an incoming SSE frame means for this tab.
224
+ *
225
+ * The filter view renders the contract's `filter` block, and several things rewrite that block from
226
+ * outside the page: the terminal AI's contract PUT, the pre-read verb, the rollback route, the
227
+ * revision-read commit and its staged confirm, and the v1→v2 migration commit. Each broadcasts
228
+ * `contract-changed`. Without this the page showed whatever it fetched at boot until someone refreshed.
229
+ *
230
+ * The pre-read verb (`server/steel-prepass-route.ts`) is the one this page cares most about, because
231
+ * `filter` is the part of its output that lands here — not, as an earlier draft of this comment claimed,
232
+ * its entire job (it also writes the datum and registration fields, and on v1 the per-sheet grid). It is a
233
+ * recent arrival to that list: it broadcast nothing until #441, which is why this comment and the empty
234
+ * state's copy both had to say so out loud for one commit.
235
+ *
236
+ * Do not restore an absolute "every write broadcasts" claim, and do not put a COUNT here — both have
237
+ * already been wrong once in this pair of files. Writes that stay silent include the project-creation seed
238
+ * in `POST /api/projects`, a pre-read the verb refuses, and a re-bake whose result is canonically equal to
239
+ * what is stored (the tag hashes key-sorted JSON, so a pure key reordering is silent too). The tally lives
240
+ * in `server/mutation-id.ts`; `verify:change-reasons` guards token↔sentence correspondence and is not a
241
+ * census of broadcast sites — it never sees the contract PUT, which uses a different builder.
242
+ *
243
+ * Pure on purpose: the steel editor's equivalent lives inline in a 9.7k-line page and needed a
244
+ * 2.2k-line DOM sandbox (`steel-editor-harness.ts`) before any of its branches could be tested. The
245
+ * decision is the part that can be wrong in a way a screenshot never shows, so it lives out here where
246
+ * `steel-filter-core.test.ts` reaches it directly, and the page keeps only the wiring.
247
+ *
248
+ * `ctx` = { appId, project, ownWrites:string[], dirty:boolean, hasDocument:boolean, seenConnected:boolean }
249
+ * Returns one of:
250
+ * { act:'ignore' } — not this app/project, or not a frame we handle
251
+ * { act:'connected' } — the stream's opening frame, first time: just record it
252
+ * { act:'gap' } — the stream RECONNECTED, so writes may have been missed
253
+ * { act:'own-echo', drop, adoptEtag } — our own write coming back; drop the first `drop` ids
254
+ * from ownWrites, and adopt `adoptEtag` when non-null
255
+ * { act:'reload' } — an external write, nothing to lose: show it
256
+ * { act:'banner', reason } — an external write, but the user has unsaved edits.
257
+ * `reason` is the frame's raw token or null; the CALLER
258
+ * maps it to a sentence (see CHANGE_LEAD), so nothing off
259
+ * the wire is ever rendered.
260
+ */
261
+ export function liveUpdateAction(frame, ctx) {
262
+ const c = ctx || {};
263
+ if (!frame || typeof frame !== 'object') return { act: 'ignore' };
264
+ // Every /api/events connection opens with `{type:'connected'}` — including every RECONNECT, which the
265
+ // browser performs on its own after a dropped socket. That makes a SECOND one the only notice we ever
266
+ // get that the channel was down: the stream carries no `id:` field, so there is no Last-Event-ID
267
+ // replay and any frame broadcast during the gap is gone for good. Without this a recovered drop leaves
268
+ // the page silently stale while readyState reads OPEN and `onerror` only ever saw CONNECTING.
269
+ if (frame.type === 'connected') return { act: c.seenConnected ? 'gap' : 'connected' };
270
+ if (frame.type !== 'contract-changed') return { act: 'ignore' };
271
+ // A tab with no app is not rendering a contract, so nothing can be "its" write.
272
+ if (!c.appId || frame.appId !== c.appId) return { act: 'ignore' };
273
+ // …and the same PROJECT. Two projects of one app share an appId, so without this a write to one
274
+ // reloads the other's tab. `|| ''` on both sides because an app-scoped write carries no `project`.
275
+ if ((frame.project || '') !== (c.project || '')) return { act: 'ignore' };
276
+ const own = Array.isArray(c.ownWrites) && frame.mutationId ? c.ownWrites.indexOf(frame.mutationId) : -1;
277
+ if (own >= 0) {
278
+ // Everything OLDER than the match is superseded: SSE preserves order on a connection, so an echo
279
+ // not seen by the time a later one arrives is never coming.
280
+ const newest = own === c.ownWrites.length - 1;
281
+ // Adopt the server's tag for our own write ONLY from the newest echo. Adopting covers the case a
282
+ // response-only flow cannot — a PUT that SUCCEEDS while its response is lost leaves `serverEtag`
283
+ // stale, so the tab's own next save is refused against its own change. The mirror image is why
284
+ // `newest` gates it: a LATE echo carries an OLDER tag, and adopting that rolls `serverEtag`
285
+ // backwards, guaranteeing a 412 on the user's next write.
286
+ // Narrowed to a NON-EMPTY STRING, and both halves earn their place: this value becomes `serverEtag`
287
+ // and then rides out as the `If-Match` header on the user's next PUT, so a number or an object
288
+ // adopted here would make every later save fail its precondition, with a reload that discards the
289
+ // toggles as the only way out. (A mutation test found this line's guard was the one thing in the
290
+ // function with no junk-input coverage.)
291
+ const adoptEtag = (newest && typeof frame.etag === 'string' && frame.etag) ? frame.etag : null;
292
+ return { act: 'own-echo', drop: own + 1, adoptEtag };
293
+ }
294
+ // An external write. Reload straight into it so the user never has to think about refreshing —
295
+ // EXCEPT when they have unsaved facet toggles, where a silent reload would discard their work.
296
+ //
297
+ // `hasDocument` is load-bearing, not defensive: the mode checkboxes ship in the STATIC markup and
298
+ // their listeners bind at module load, so a user looking at the "No filter data yet." empty state
299
+ // can tick "Thickness", set dirty=true, and hold nothing saveable (save() early-returns on `!F`).
300
+ // Without this, the first-document write / rollback / migration landing on that page would stop at a
301
+ // banner asking to protect edits that cannot be saved.
302
+ //
303
+ // `hasDocument` must mean "a filter is RENDERED", not "a `filter` key exists". Review caught the
304
+ // difference being load-bearing: boot() also shows the empty state when `filter` is present but has no
305
+ // sheet elements (`{}`, `{sheets:[]}`, a raster-only sheet), where a key-presence test reports true,
306
+ // `sel` is still null and nothing is on screen. The page therefore passes `!!sel`.
307
+ if (!(c.dirty && c.hasDocument)) return { act: 'reload' };
308
+ // Carried only on the banner, the only action that renders anything. Narrowed to a string here so the
309
+ // caller's table lookup can never be handed an object or a number off the wire.
310
+ return { act: 'banner', reason: typeof frame.reason === 'string' ? frame.reason : null };
311
+ }