facett_core/lib.rs
1//! **facett-core** — the visual kernel. Render a node/edge **`Scene`** into egui.
2//! Source-agnostic: build a `Scene` from anything (Arrow rows, a graph, a DAG),
3//! hand it here, get pixels. The CPU painter is the reference; a **wgpu** fast
4//! path (GPU viewport-cull + indirect draw, seeded from katana-osm's
5//! `osm-viewer`) lands behind this same `draw()` call — consumers don't change.
6
7use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, vec2};
8
9pub mod a11y;
10/// The bounded WebGPU adapter retry + the plain "no GPU" messages, shared by every
11/// wasm entry point (facet-wrapped mounts, facett-demo's pages bundle).
12pub mod adapter_retry;
13/// Embedded-asset integrity: the `const fn` every `include_bytes!` site in this
14/// workspace checks itself with, so a Git-LFS pointer standing in for a font fails the
15/// BUILD instead of shipping as a font that draws nothing.
16pub mod asset;
17pub mod interface;
18/// **Barnes–Hut N-body repulsion** — the shared O(n log n) force-layout kernel
19/// (dimension-generic quadtree/octree, gatling-parallel) that every facett
20/// force-directed layout consumes so a 30 000-node graph lays out without the
21/// O(n²)-per-iteration hang. See [`barnes_hut`].
22pub mod barnes_hut;
23/// The shared **action bus** (BUS-1) — a typed, deterministic outbox facets use
24/// to hand side work (a drag move, a time-scrub, a command) to the host. The
25/// common carrier [`dragdrop`] / [`time_axis`] `Effect`s flow through.
26pub mod action_bus;
27pub mod caps;
28pub mod chrome;
29pub mod clip;
30pub mod clipboard;
31pub mod deckfx;
32/// The shared **drag-and-drop** primitive (DND-1) — the one reducer behind
33/// items-dragged-onto-zones (cards→columns, bars→lanes). Engine-agnostic sibling
34/// of [`nav::Navigable`]; the caps flag [`FacetCaps::draggable`] points here.
35pub mod dragdrop;
36pub mod edges;
37pub mod effects;
38/// **THE unified view core** (ENGINE-1) — the one *cull · project · label-collide ·
39/// pick* spine that `facett-map`, `facett-map3d`, `facett-geomap`, the L1 overlay
40/// and every graph view collapse onto. Only THREE things differ between a map and
41/// a graph, and they are the three traits
42/// ([`PositionSource`](engine::PositionSource),
43/// [`ElevationSource`](engine::ElevationSource), [`Hierarchy`](engine::Hierarchy)).
44/// See [`engine`].
45pub mod engine;
46/// The **UI error-code scheme** (`facet-<component>-<n>`) — the stable, unique code
47/// every facett UI part carries so tests + consumers react to the CODE, not a matched
48/// string. See [`errcode::FacetError`], the [`facet_err!`] macro, the canonical
49/// [`errcode::REGISTRY`], and the pink [`errcode::code_color`] renderer.
50pub mod devid;
51/// **The NAMED empty state** — what a pane draws when its feed has nothing in it:
52/// the feed's own name, why it is empty (`no-rows` / `unreachable` / `not-configured`),
53/// and optionally what would fill it. The alternative a 2026-09-10 audit found in the
54/// wild was a *fixture* — plausible hand-written rows behind a `source: "fixture"`
55/// tag — and rows read as data no matter what the tag says. See [`empty::EmptyState`].
56pub mod empty;
57pub mod errcode;
58/// The canonical **Elm contract** (FC-2 / FC-9) — the [`Elm`] trait +
59/// [`impl_facet_via_elm!`] bridge macro that lift `facett-security`'s hand-rolled
60/// Model/Msg/Effect/pure-view pattern into reusable infra. Pair with
61/// [`harness`] to drive an `Elm` component headlessly.
62pub mod elm;
63pub mod focus;
64/// **The golden-image guard** (feature `golden`) — [`golden::assert_golden`], the
65/// one comparison every facett screenshot proof runs against its committed PNG.
66/// Exact match, failure artifacts under `target/`, a **missing golden FAILS**, and
67/// blessing is the explicit opt-in `UPDATE_SNAPSHOTS=1`. Enabled from the
68/// `[dev-dependencies]` of the crates that own goldens; absent from release builds.
69#[cfg(feature = "golden")]
70pub mod golden;
71pub mod imgscan; // image-analysis oracle (SCAN-THE-PIXELS law): spoke/high-freq/
72 // coverage/centroid features computed FROM the rendered pixels.
73pub mod labels3d;
74/// **ROOT LAW #0 — the rayon-free law**, as machinery a test can actually fail
75/// on ([`law`]). ONE writer for korp and facett so the two repos hold the same
76/// line: our calls and our manifests are always red, a *normal* dependency edge
77/// to rayon is red, and the known dev-only third-party edge (image→ravif inside
78/// the screenshot-diff harness) is reported as context and never fails.
79pub mod law;
80/// **The label-declutter contract** — the order-independent spatial-grid collision
81/// rule shared by the CPU painter and the WGSL compute passes (GFX_V2 item 4). One
82/// writer, two executions; see the module docs for why [`legibility::place_labels`]
83/// (greedy, order-dependent, displaces into alternative slots) could not be the one.
84pub mod label_grid;
85/// **Legibility at scale** — the shared screen-space toolbox (spatial hover index,
86/// label collision avoidance, density-aware edge thinning) that makes a 100 000-node
87/// graph or a 1 000 000-pin map readable. Pure, deterministic, headless-testable; the
88/// legibility half of the story whose speed half is [`render::gpu::graphcloud`].
89pub mod legibility;
90pub mod harness;
91pub mod look;
92pub mod nav;
93pub mod navgraph; // dev-mode numbered navigation graph + overlay (navgraph-design.md phase 1)
94pub mod overlay;
95/// The constellation-wide **`Panel` trait** (Phase 0 foundation) — the primary
96/// UI-pane seam, with backend (1) native in-process (the blanket
97/// `impl<T: Facet> Panel for T`) and backend (4) headless ([`panel::drive`]).
98/// See `.nornir/wasm-ui-panels-design.md` §1.
99pub mod panel;
100pub mod rabbit;
101/// The L0 shared render kernel (CONS-CORE) — shared `Camera`, z-ordered
102/// `LayerStack`, the CPU rect scissor, and (feature `wgpu`) the extracted GPU
103/// scaffold. Map skins + `facett-graphview` draw through this.
104pub mod render;
105pub mod runtrace; // in-memory, wasm-safe "what RAN" ledger (no FS) — folded into
106 // state_json["trace"]["ran"], read via the JS hook on wasm.
107pub mod scroll_engine;
108pub mod severity; // STRUCTURAL error signal for the Robot-UI HARD GATE — each
109 // pane/atom reports Severity{Info,Warning,Error}; the gate asserts
110 // on this instead of scanning rendered text (RESOLVED decision (a)).
111pub mod testmatrix; // functional-status → nornir test-matrix bridge (feature
112 // `testmatrix`); no-op in release.
113pub mod theme;
114/// The shared **pan/zoom-in-time axis** (TIME-1) — the one time-window model
115/// behind gantt/CFD/calendar/timeline, linkable across facets. Temporal sibling
116/// of [`nav::Navigable`]; the caps flag [`FacetCaps::time_scrollable`] points here.
117pub mod time_axis;
118pub mod trace; // structured IN/OUT/END event stream ($FACETT_TRACE) — the
119 // machine-readable data a facet actually rendered.
120pub use a11y::{Semantics, node as a11y_node, stable_id};
121pub use errcode::{FacetError, MountedFacetError};
122pub use action_bus::{ActionBus, BusAction, BusMsg};
123pub use caps::FacetCaps;
124pub use dragdrop::{DragDrop, DragEffect, DragMsg, Move as DragMove};
125pub use clip::{ArrowColumnRef, ClipKind, ClipPayload, CopySource, PasteTarget};
126pub use clipboard::ClipAction;
127pub use deckfx::{DeckFx, DeckRaven};
128pub use elm::Elm;
129pub use imgscan::{BBox, Rgba, ScanReport, coverage, high_freq_ratio, painted_centroid_and_bbox, scan, spoke_score};
130pub use look::{Action, KeyMap, Palette};
131pub use nav::{Dir4, Navigable, nearest_in_direction};
132pub use panel::Panel;
133pub use rabbit::{Rabbit, RabbitMesh, rabbit_mesh, rabbit_outline};
134pub use scroll_engine::SmoothScroll;
135pub use severity::{Severity, worst as worst_severity};
136pub use theme::{Theme, set_theme, theme};
137pub use time_axis::{TimeAxis, TimeEffect, TimeMsg};
138
139// The rich look-&-feel `Theme` (the work-order architecture) is re-exported under
140// an unambiguous alias so it coexists with the legacy flat palette `Theme` above.
141pub use look::Theme as LookTheme;
142
143/// A node: a label + a colour (the *consumer* picks the colour policy — hash by
144/// label, by status, …).
145#[derive(Clone)]
146pub struct Node {
147 pub label: String,
148 pub color: Color32,
149}
150
151/// A directed edge between node indices.
152#[derive(Clone, Copy)]
153pub struct Edge {
154 pub src: usize,
155 pub dst: usize,
156}
157
158/// A drawable graph: nodes + edges (edges index into `nodes`).
159#[derive(Default, Clone)]
160pub struct Scene {
161 pub nodes: Vec<Node>,
162 pub edges: Vec<Edge>,
163}
164
165impl Scene {
166 pub fn new() -> Self {
167 Self::default()
168 }
169 /// Push a node, returning its index.
170 pub fn node(&mut self, label: impl Into<String>, color: Color32) -> usize {
171 self.nodes.push(Node { label: label.into(), color });
172 self.nodes.len() - 1
173 }
174 pub fn edge(&mut self, src: usize, dst: usize) {
175 self.edges.push(Edge { src, dst });
176 }
177 pub fn is_empty(&self) -> bool {
178 self.nodes.is_empty()
179 }
180}
181
182/// Node placement strategy.
183#[derive(Clone, Copy, PartialEq, Eq, Default)]
184pub enum Layout {
185 #[default]
186 Circular,
187 /// Deterministic Fruchterman–Reingold (edges pull, all nodes repel). O(n²)
188 /// per iteration — best for small/medium graphs.
189 Force,
190}
191
192/// Draw a `Scene` into `ui` — the reusable render primitive. Empty scenes show
193/// `empty_hint`. Labels render when the node count is small enough to read.
194pub fn draw(ui: &mut Ui, scene: &Scene, layout: Layout, empty_hint: &str) {
195 let (rect, _) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
196 let n = scene.nodes.len();
197 if n == 0 {
198 let th = theme(ui);
199 ui.painter_at(rect).text(rect.center(), Align2::CENTER_CENTER, empty_hint, FontId::proportional(13.0), th.text_dim);
200 return;
201 }
202 let pos = positions(layout, scene, rect);
203 draw_positions(ui, scene, &pos, rect, empty_hint);
204}
205
206/// Paint a `Scene` into `rect` using **pre-computed** node positions — the drawing
207/// half of [`draw`], split out so a stateful host can **freeze** the layout: compute
208/// the O(n log n) force positions once (cached until the graph structure changes, see
209/// [`ForceCache`]) and paint them every frame WITHOUT re-running the layout. `pos`
210/// must be indexed like `scene.nodes`; short/empty falls back to the empty hint.
211pub fn draw_positions(ui: &mut Ui, scene: &Scene, pos: &[Pos2], rect: Rect, empty_hint: &str) {
212 let th = theme(ui);
213 let painter = ui.painter_at(rect);
214 let n = scene.nodes.len();
215 if n == 0 || pos.len() != n {
216 painter.text(rect.center(), Align2::CENTER_CENTER, empty_hint, FontId::proportional(13.0), th.text_dim);
217 return;
218 }
219 for e in &scene.edges {
220 if e.src < n && e.dst < n {
221 painter.line_segment([pos[e.src], pos[e.dst]], Stroke::new(0.6_f32, th.edge));
222 }
223 }
224 for (i, node) in scene.nodes.iter().enumerate() {
225 painter.circle_filled(pos[i], 5.0, node.color);
226 }
227 draw_position_labels(ui, scene, pos, rect);
228}
229
230/// The label half of [`draw_positions`] alone: a host whose node/edge cloud went to the
231/// GPU (`graphcloud::cloud::draw_cloud`) still paints the text through egui, with the
232/// same font, offset and `n <= 60` cut as the CPU painter.
233pub fn draw_position_labels(ui: &Ui, scene: &Scene, pos: &[Pos2], rect: Rect) {
234 let th = theme(ui);
235 let painter = ui.painter_at(rect);
236 let n = scene.nodes.len();
237 if n <= 60 && pos.len() == n {
238 for (i, node) in scene.nodes.iter().enumerate() {
239 painter.text(pos[i] + vec2(7.0, 0.0), Align2::LEFT_CENTER, &node.label, FontId::proportional(10.0), th.text);
240 }
241 }
242}
243
244/// **Converge-once-then-freeze** layout cache. A force layout is a pure function of
245/// the graph structure (node count + edge set) and the paint `rect`, so this holds the
246/// last-computed positions and only re-runs [`layout_positions`] when the structure or
247/// rect actually changes. Embed it on a stateful host (e.g. a `GraphView`) and call
248/// [`ForceCache::positions`] from the render path — the O(n log n) (with Barnes–Hut)
249/// or O(n²) (small graphs) layout stops running every frame, which is the other half
250/// (besides Barnes–Hut) of killing the 30 000-node hang.
251#[derive(Default, Clone)]
252pub struct ForceCache {
253 sig: u64,
254 rect: [u32; 4],
255 pos: Vec<Pos2>,
256}
257
258impl ForceCache {
259 /// The node positions for `scene` under `layout` in `rect`, computed on the first
260 /// call and on any structural/rect change, and returned from cache otherwise.
261 pub fn positions(&mut self, layout: Layout, scene: &Scene, rect: Rect) -> &[Pos2] {
262 let n = scene.nodes.len();
263 let key = self.structure_key(layout, scene);
264 let rb = [rect.min.x.to_bits(), rect.min.y.to_bits(), rect.max.x.to_bits(), rect.max.y.to_bits()];
265 if self.sig != key || self.rect != rb || self.pos.len() != n {
266 self.pos = positions(layout, scene, rect);
267 self.sig = key;
268 self.rect = rb;
269 }
270 &self.pos
271 }
272
273 /// Whether the next [`positions`](Self::positions) call for this `layout`/`scene`
274 /// in this `rect` will be a cache hit (a no-op relayout) — the *frozen/settled*
275 /// signal a `tick` can assert.
276 #[must_use]
277 pub fn is_settled(&self, layout: Layout, scene: &Scene, rect: Rect) -> bool {
278 let rb = [rect.min.x.to_bits(), rect.min.y.to_bits(), rect.max.x.to_bits(), rect.max.y.to_bits()];
279 self.sig == self.structure_key(layout, scene) && self.rect == rb && self.pos.len() == scene.nodes.len()
280 }
281
282 /// Force a recompute on the next [`positions`](Self::positions) call.
283 pub fn invalidate(&mut self) {
284 self.sig = 0;
285 self.rect = [0; 4];
286 self.pos.clear();
287 }
288
289 fn structure_key(&self, layout: Layout, scene: &Scene) -> u64 {
290 let edges: Vec<(usize, usize)> = scene.edges.iter().map(|e| (e.src, e.dst)).collect();
291 let key = match layout {
292 Layout::Circular => "circular",
293 Layout::Force => "force",
294 };
295 crate::barnes_hut::structure_sig(key, scene.nodes.len(), &edges)
296 }
297}
298
299/// **Test/host hook (additive).** The public, return-asserted view of the
300/// private [`positions`] layout node — the exact node centres [`draw`] paints for
301/// `scene` under `layout` inside `rect`. Exposed so the graph-skin call-chain
302/// matrix can assert the *layout* stage (finite, in-rect, count == nodes,
303/// circular radius, force-fit normalisation) without a painter. Calls the **same**
304/// private fn `draw` uses, so it IS the layout the pixels come from — additive,
305/// no behaviour change.
306pub fn layout_positions(layout: Layout, scene: &Scene, rect: Rect) -> Vec<Pos2> {
307 positions(layout, scene, rect)
308}
309
310fn positions(layout: Layout, scene: &Scene, rect: Rect) -> Vec<Pos2> {
311 let n = scene.nodes.len();
312 let center = rect.center();
313 let radius = rect.size().min_elem() * 0.42;
314 let circular = |i: usize| {
315 let a = std::f32::consts::TAU * (i as f32) / (n as f32);
316 vec2(a.cos(), a.sin())
317 };
318 match layout {
319 Layout::Circular => (0..n).map(|i| center + radius * circular(i)).collect(),
320 Layout::Force => {
321 // Deterministic Fruchterman–Reingold from a circular seed (unit space).
322 let mut p: Vec<egui::Vec2> = (0..n).map(circular).collect();
323 let k = (1.0 / (n.max(1) as f32).sqrt()).clamp(0.05, 1.0);
324 // Above the threshold the O(n²) all-pairs repulsion is the 30 000-node
325 // hang — swap it for the shared Barnes–Hut O(n log n) kernel (parallel,
326 // deterministic). Below the threshold the exact loop runs unchanged, so
327 // every small-graph golden is byte-for-byte identical (additive).
328 let use_bh = n >= crate::barnes_hut::BH_THRESHOLD;
329 for _ in 0..120 {
330 let mut disp = vec![egui::Vec2::ZERO; n];
331 if use_bh {
332 let pts: Vec<[f32; 2]> = p.iter().map(|v| [v.x, v.y]).collect();
333 let rep = crate::barnes_hut::repulsion_forces::<2>(&pts, k, crate::barnes_hut::BH_THETA);
334 for i in 0..n {
335 disp[i] = egui::vec2(rep[i][0], rep[i][1]);
336 }
337 } else {
338 for i in 0..n {
339 for j in (i + 1)..n {
340 let d = p[i] - p[j];
341 let dist = d.length().max(1e-3);
342 let f = k * k / dist;
343 let dir = d / dist;
344 disp[i] += dir * f;
345 disp[j] -= dir * f;
346 }
347 }
348 }
349 for e in &scene.edges {
350 if e.src < n && e.dst < n {
351 let d = p[e.src] - p[e.dst];
352 let dist = d.length().max(1e-3);
353 let f = dist * dist / k;
354 let dir = d / dist;
355 disp[e.src] -= dir * f;
356 disp[e.dst] += dir * f;
357 }
358 }
359 for i in 0..n {
360 let dl = disp[i].length().max(1e-3);
361 p[i] += disp[i] / dl * dl.min(0.04); // capped step (cooling-free, deterministic)
362 }
363 }
364 // Normalise to fit the rect.
365 let (mut mn, mut mx) = (egui::vec2(f32::MAX, f32::MAX), egui::vec2(f32::MIN, f32::MIN));
366 for v in &p {
367 mn.x = mn.x.min(v.x);
368 mn.y = mn.y.min(v.y);
369 mx.x = mx.x.max(v.x);
370 mx.y = mx.y.max(v.y);
371 }
372 let span = (mx - mn).max(egui::vec2(1e-3, 1e-3));
373 p.iter()
374 .map(|v| center + egui::vec2(((v.x - mn.x) / span.x - 0.5) * 2.0 * radius, ((v.y - mn.y) / span.y - 0.5) * 2.0 * radius))
375 .collect()
376 }
377 }
378}
379
380/// The facett **component contract**. Every facet — graph, map, pipeline, table,
381/// the ported nornir viewers — implements this, so consumers (korp, nornir, …)
382/// compose them uniformly *and* get headless robot-testing for free.
383///
384/// The things a component owes its host:
385/// 1. a **title** (tab label / panel heading),
386/// 2. how to **draw** itself into egui,
387/// 3. its **observable state** as JSON — dumped to `$APP_STATE` for headless
388/// assertions. **Rule:** every visible list/status/count goes in `state_json`.
389/// 4. (**defaulted**) [`update_json`](Facet::update_json) — the Elm mutation path,
390/// a no-op by default so it costs existing facets nothing; overriding it (and
391/// the three above) makes a facet interchangeable with a [`Panel`](crate::Panel).
392pub trait Facet {
393 fn title(&self) -> &str;
394 fn ui(&mut self, ui: &mut Ui);
395 fn state_json(&self) -> serde_json::Value;
396
397 /// The **Elm mutation path** — apply one message (JSON). This is the fourth
398 /// member of the component contract (`title`/`ui`/`state_json`/`update_json`),
399 /// and it is **defaulted to a no-op** so it is purely ADDITIVE: every existing
400 /// `impl Facet` keeps compiling unchanged, while a facet that wants the writable
401 /// input surface overrides it (an Elm-backed facet routes the JSON through its
402 /// `update`). With this default in place `Facet` and [`Panel`](crate::Panel)
403 /// share the same four-method shape, which is what lets the blanket
404 /// `impl<T: Facet> Panel for T` (see [`panel`](crate::panel)) make **every**
405 /// `Facet` a `Panel` for free. Unknown/undriven messages are ignored — the
406 /// default simply does nothing.
407 fn update_json(&mut self, _msg_json: &str) {}
408
409 /// The pane's **STRUCTURAL severity** — the RESOLVED Robot-UI error signal
410 /// (decision (a)). A facet returns the WORST [`Severity`](crate::Severity) over
411 /// its currently-rendered atoms (compute it with
412 /// [`worst_severity`](crate::worst_severity)): [`Severity::Info`] when it is
413 /// showing real data, [`Severity::Warning`] when degraded, and
414 /// [`Severity::Error`] when it surfaced a failure (a load error, an unavailable
415 /// backend, an empty data-bearing surface).
416 ///
417 /// **Defaulted to [`Severity::Info`]** so it is purely ADDITIVE — every existing
418 /// `impl Facet` stays green and keeps compiling. The Robot-UI HARD GATE reads
419 /// THIS (surfaced through the [`Panel`](crate::Panel) seam the headless robot
420 /// drives), not the `nornir_robotui::error_atoms()` substring scan, which is kept
421 /// only as a MIGRATION FALLBACK for panes that have not yet overridden this.
422 /// A pane that returns [`Severity::Error`] is RED and FAILS the gate.
423 /// **This pane's stable DEV-ID** — the [`errcode`](crate::errcode) *component*
424 /// string (the `<component>` in `facet-<component>-<n>`), so the identity a pane
425 /// shows and the identity its errors carry are the SAME vocabulary rather than two
426 /// naming schemes that drift.
427 ///
428 /// Shown as a click-to-copy chip in non-release builds ([`devid::badge`](crate::devid::badge)),
429 /// because a screenshot cannot tell you which crate drew a pane and a title like
430 /// "Map" appears in four of them. Pasting the chip resolves to a crate dir and a
431 /// source file via [`devid::resolve`](crate::devid::resolve).
432 ///
433 /// **Defaulted to `""`** so it is purely ADDITIVE — every existing `impl Facet`
434 /// keeps compiling. A pane that has not overridden it renders a visibly-different
435 /// `⟨unregistered⟩` marker instead of an id, never a plausible-looking string that
436 /// resolves to nothing (the `facet-map-99` hole that
437 /// `facett-core/tests/errcode_raise_sites.rs` documents). So the badge is also the
438 /// to-do list: every marker is a pane still to declare this.
439 fn component(&self) -> &'static str {
440 ""
441 }
442
443 fn severity(&self) -> crate::Severity {
444 crate::Severity::Info
445 }
446
447 // --- uniform capability surface (all defaulted; see caps.rs / clipboard.rs) ---
448
449 /// What this facet can do. Override to opt into capabilities.
450 fn caps(&self) -> FacetCaps {
451 FacetCaps::NONE
452 }
453
454 /// Current uniform scale (1.0 = native). Override if `caps().scalable`.
455 fn scale(&self) -> f32 {
456 1.0
457 }
458 /// Set the uniform scale; clamp internally. Default no-op (not scalable).
459 fn set_scale(&mut self, _scale: f32) {}
460
461 /// **The band `[min, max]`, relative to native (`1.0`), that this facet's uniform
462 /// scale may be driven over.** [`FacetDeck::scale_active`] clamps into it.
463 ///
464 /// The default `[0.25, 4.0]` is a *document viewer's* range — a quarter size to
465 /// quadruple size, which is all a table, a form or a text pane ever wants. It was
466 /// for years the deck's only vocabulary, hardcoded in `scale_active`, and that is
467 /// a bug for any facet whose native range is wider. A MAP's is: `OsmView`'s camera
468 /// spans `[ZOOM_MIN, ZOOM_MAX]` = a 1.25-million-fold range, so a hardcoded 16-fold
469 /// clamp both **stalls** zoom-in a couple of clicks past the fit *and* — because
470 /// the wheel and pinch drive the camera directly, never through [`Self::set_scale`]
471 /// — makes the next `+` click **saturate the clamp and slam the camera backwards**,
472 /// a zoom-IN button that visibly zooms OUT. Guarded by
473 /// `facett-geomap/tests/osm2d_deck_scale.rs`.
474 ///
475 /// Override alongside [`Self::scale`]/[`Self::set_scale`] when native has no fixed
476 /// pixel size. Must contain `1.0` — [`FacetDeck::reset_scale`] writes it.
477 fn scale_range(&self) -> (f32, f32) {
478 (0.25, 4.0)
479 }
480
481 /// The current selection as JSON (also folded into `state_json` by
482 /// convention). `Null` when nothing/none selectable.
483 fn selection_json(&self) -> serde_json::Value {
484 serde_json::Value::Null
485 }
486
487 /// Clipboard hooks — see clipboard.rs. Defaults: nothing to give/take.
488 /// Returns the text to place on the clipboard (None = nothing copyable now).
489 fn copy(&mut self) -> Option<String> {
490 None
491 }
492 /// Like `copy`, but also removes the selection. Default delegates to `copy`.
493 fn cut(&mut self) -> Option<String> {
494 self.copy()
495 }
496 /// Accept pasted text. Returns true if consumed.
497 fn paste(&mut self, _text: &str) -> bool {
498 false
499 }
500
501 /// Optional downcast handle for hosts that need typed access to a specific
502 /// facet living inside a [`FacetDeck`] (e.g. a robot-UI driver clicking an
503 /// app-level control that must forward to a concrete component's own API).
504 /// Defaulted to `None` so no existing facet has to change; a component opts in
505 /// by returning `Some(self)`.
506 fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
507 None
508 }
509
510 // --- cross-instance state clone (copy/paste BETWEEN same-component instances) ---
511 // See `.nornir/design/copy-paste-between-instances.md` + `clipboard.rs`. The trio
512 // below is the type-tagged STATE layer on top of the text clipboard: two
513 // instances with the SAME `kind()` exchange `portable_state()` via the OS
514 // clipboard envelope (`clipboard::encode_component`/`decode_component`). Each is
515 // defaulted to the opt-OUT floor — a component that doesn't implement all three
516 // neither copies nor accepts cross-instance state, and nothing panics.
517
518 /// Stable component-type id (e.g. `"jobview"`, `"graphpan"`, `"table"`). Two
519 /// instances with the **same** kind can exchange portable state; the empty
520 /// default `""` means **opted out** of cross-instance clone.
521 fn kind(&self) -> &'static str {
522 ""
523 }
524
525 /// The **portable** subset of this facet's state — the fields a same-kind
526 /// sibling can adopt. `None` = not cloneable. Kept SEPARATE from
527 /// [`state_json`](Self::state_json) (the introspection dump, which may carry
528 /// derived / render-only data) so this stays round-trippable through
529 /// [`load_state`](Self::load_state).
530 fn portable_state(&self) -> Option<serde_json::Value> {
531 None
532 }
533
534 /// Adopt a portable state produced by [`portable_state`](Self::portable_state)
535 /// on a same-kind sibling. Returns `true` if accepted. Default `false`
536 /// (opt-in per component).
537 fn load_state(&mut self, _state: &serde_json::Value) -> bool {
538 false
539 }
540}
541
542/// The per-facet states [`FacetDeck::state_json_rolling`] serves inactive tabs from.
543/// One per publishing host; `Default` = empty (the first call builds everything).
544///
545/// The map is MOVED into the returned state, not cloned (a clone of 80 tabs' JSON trees
546/// cost as much as building them), so the host hands it back with
547/// [`FacetDeck::return_rolling`] after serialising — or the next call rebuilds every tab
548/// (correct, only slow).
549#[derive(Default, Debug)]
550pub struct DeckStateCache {
551 facets: serde_json::Map<String, serde_json::Value>,
552 /// Each facet's state as JSON text ([`FacetDeck::serialize_rolling`]); dropped when
553 /// that facet's state is rebuilt, so it is re-serialised exactly then.
554 text: std::collections::HashMap<String, String>,
555 next: usize,
556 /// Facet `state_json` builds made through this cache (the honesty counter).
557 pub built: u64,
558}
559
560/// A tabbed set of [`Facet`]s — the reusable multi-component shell. Draws a tab
561/// bar + the active facet, and composes **every** facet's `state_json` under its
562/// title, so the whole-app introspection contract is free. korp/nornir can build
563/// their window from a `FacetDeck` instead of hand-rolling tabs + the state dump.
564pub struct FacetDeck {
565 facets: Vec<Box<dyn Facet>>,
566 active: usize,
567 /// Opt-in deck effects (palette override + glow). `Default` = all off, so a
568 /// deck that never opts in is unchanged and pays nothing.
569 fx: DeckFx,
570 /// A raven summoned through the deck, in flight or perched (or `None`).
571 raven: Option<DeckRaven>,
572 /// A transient, themed component-clone toast (message + the `ctx.input.time`
573 /// it was raised at), shown briefly after a Copy-/Paste-component gesture —
574 /// chiefly the type-mismatch rejection ("clipboard holds a `table`, not a
575 /// `graphpan`"). `None` = nothing to show. See [`Self::component_toast`].
576 toast: Option<(String, f64)>,
577 /// **Responsive MENU collapse.** Host-driven: on a narrow (phone-class) viewport
578 /// the long tab bar (one selectable per facet — a deck can hold 60+) wraps into
579 /// many rows and buries the active facet below the screen fold. When
580 /// `menu_collapsed` is set (by the host, classifying the viewport — e.g.
581 /// `facett_app::scene::Device`) the tab bar renders as a compact HAMBURGER header
582 /// (`≡` + the active choice's label) with the full choice list behind a drawer
583 /// (canvas-first). On a wide viewport it stays the inline wrapped strip. See
584 /// [`set_menu_collapsed`](Self::set_menu_collapsed).
585 menu_collapsed: bool,
586 /// The hamburger drawer's open state (deck-owned). Default **closed** ⇒ the
587 /// collapsed header is a single row and the canvas gets the screen; opening lists
588 /// every choice, and picking one switches the tab AND shuts the drawer.
589 menu_open: bool,
590 /// Last frame's tab-bar (menu header) rect — the observable geometry a headless
591 /// test reads (`state_json.menu.bar_rect`) to prove the collapsed menu is ONE
592 /// compact row, not a multi-row wrap that eats the viewport.
593 menu_bar_rect: Rect,
594 /// Last frame's active-facet content rect — the "canvas" the collapse hands the
595 /// screen to (`state_json.menu.content_rect`).
596 content_rect: Rect,
597 /// **Tab groups** (opt-in, [`with_groups`](Self::with_groups)). Empty = the one flat
598 /// strip, exactly as before. Set = a TWO-LEVEL bar: a row of group names, then the
599 /// active group's tabs. Every facet sits in exactly one group (unlisted ones land in
600 /// a trailing group), and the active group is DERIVED from the active facet, so a
601 /// programmatic switch ([`set_active_by_title`](Self::set_active_by_title), a deep
602 /// link, a tour) can never show a tab row that does not hold the active tab.
603 groups: Vec<TabGroup>,
604}
605
606/// One named group of deck tabs: its label and its members as facet indices, in deck
607/// order. Built by [`FacetDeck::with_groups`].
608#[derive(Clone, Debug, PartialEq, Eq)]
609pub struct TabGroup {
610 /// The group's label in the group row (also its navgraph field key).
611 pub name: String,
612 /// Facet indices, ascending (deck order).
613 pub members: Vec<usize>,
614 /// The member last shown, so re-entering a group returns to where the user was.
615 last: usize,
616}
617
618impl TabGroup {
619 /// The member index re-entering this group opens (the last one shown).
620 pub fn entry(&self) -> usize {
621 if self.members.contains(&self.last) { self.last } else { self.members.first().copied().unwrap_or(0) }
622 }
623}
624
625/// How long a component-clone [`toast`](FacetDeck::toast) stays on screen.
626const TOAST_SECS: f64 = 2.6;
627
628impl FacetDeck {
629 pub fn new(facets: Vec<Box<dyn Facet>>) -> Self {
630 Self {
631 facets,
632 active: 0,
633 fx: DeckFx::OFF,
634 raven: None,
635 toast: None,
636 menu_collapsed: false,
637 menu_open: false,
638 menu_bar_rect: Rect::ZERO,
639 content_rect: Rect::ZERO,
640 groups: Vec::new(),
641 }
642 }
643
644 /// **Group the tab bar** into named groups — `(name, tab titles)` in display order.
645 ///
646 /// Tab titles are matched exactly; a title the deck does not hold is skipped (a
647 /// native-only tab named in a list a wasm build shares). A facet no group names is
648 /// put in a trailing group called `rest` (created only when needed), so no tab can
649 /// become unreachable by being forgotten. A facet named by two groups belongs to the
650 /// first. Groups left empty are dropped. Inside a group the tabs keep DECK order, so
651 /// the tab strip's navgraph draw order is the deck order filtered, as before.
652 ///
653 /// Must be called after the facets are in place (it indexes them); a later
654 /// [`push`](Self::push) lands in the `rest` group on the next call only.
655 #[must_use]
656 pub fn with_groups(mut self, groups: &[(&str, &[&str])], rest: &str) -> Self {
657 self.set_groups(groups, rest);
658 self
659 }
660
661 /// The in-place form of [`with_groups`](Self::with_groups).
662 pub fn set_groups(&mut self, groups: &[(&str, &[&str])], rest: &str) {
663 let mut owner: Vec<Option<usize>> = vec![None; self.facets.len()];
664 for (g, (_, titles)) in groups.iter().enumerate() {
665 for t in titles.iter() {
666 if let Some(i) = self.facets.iter().position(|f| f.title() == *t)
667 && owner[i].is_none()
668 {
669 owner[i] = Some(g);
670 }
671 }
672 }
673 let mut out: Vec<TabGroup> = groups
674 .iter()
675 .enumerate()
676 .map(|(g, (name, _))| TabGroup {
677 name: (*name).to_string(),
678 members: (0..self.facets.len()).filter(|&i| owner[i] == Some(g)).collect(),
679 last: usize::MAX,
680 })
681 .collect();
682 let orphans: Vec<usize> = (0..self.facets.len()).filter(|&i| owner[i].is_none()).collect();
683 if !orphans.is_empty() {
684 // A `rest` group the caller already declared takes the orphans too.
685 match out.iter_mut().find(|g| g.name == rest) {
686 Some(g) => {
687 g.members.extend(orphans);
688 g.members.sort_unstable();
689 }
690 None => out.push(TabGroup { name: rest.to_string(), members: orphans, last: usize::MAX }),
691 }
692 }
693 out.retain(|g| !g.members.is_empty());
694 self.groups = out;
695 }
696
697 /// The tab groups (empty when the bar is one flat strip).
698 pub fn groups(&self) -> &[TabGroup] {
699 &self.groups
700 }
701
702 /// The index of the group holding the active facet, or `None` when ungrouped.
703 pub fn active_group(&self) -> Option<usize> {
704 self.groups.iter().position(|g| g.members.contains(&self.active))
705 }
706
707 /// The name of the group holding the active facet.
708 pub fn active_group_name(&self) -> Option<&str> {
709 self.active_group().map(|g| self.groups[g].name.as_str())
710 }
711
712 /// Switch to group `name`: the active facet becomes the group's last-shown member
713 /// (its first, the first time). Returns `false` for an unknown group. The
714 /// programmatic twin of clicking the group's label.
715 pub fn set_active_group(&mut self, name: &str) -> bool {
716 match self.groups.iter().find(|g| g.name == name) {
717 Some(g) => {
718 self.active = g.entry();
719 true
720 }
721 None => false,
722 }
723 }
724
725 /// Remember the active facet as its group's last-shown member.
726 fn note_group_entry(&mut self) {
727 let active = self.active;
728 if let Some(g) = self.groups.iter_mut().find(|g| g.members.contains(&active)) {
729 g.last = active;
730 }
731 }
732
733 /// The group row of a grouped bar: one selectable per group, a draw-order-declared
734 /// navgraph `groups` strip (each label a `Field`). Clicking a group opens its entry.
735 fn draw_group_row(&mut self, ui: &mut Ui) {
736 let active_group = self.active_group();
737 let mut pick: Option<usize> = None;
738 let nav = navgraph::begin(ui, "groups", navgraph::NavKind::Group, "groups");
739 navgraph::declare_draw_order(ui, nav);
740 let row = ui.horizontal_wrapped(|ui| {
741 for (gi, g) in self.groups.iter().enumerate() {
742 let r = ui
743 .selectable_label(active_group == Some(gi), g.name.as_str())
744 .on_hover_text(format!("{} tabs", g.members.len()));
745 navgraph::field(ui, &g.name, &r);
746 if r.clicked() {
747 pick = Some(gi);
748 }
749 }
750 });
751 navgraph::end(ui, nav, row.response.rect);
752 if let Some(gi) = pick {
753 self.active = self.groups[gi].entry();
754 }
755 }
756 /// Append a facet (the incremental form of [`new`](Self::new)). Lets a host
757 /// build a deck pane-by-pane as it discovers what to show (e.g. one pane per
758 /// warehouse table it finds).
759 pub fn push(&mut self, facet: Box<dyn Facet>) {
760 self.facets.push(facet);
761 }
762 pub fn active(&self) -> usize {
763 self.active
764 }
765
766 /// The title of the currently-active facet (the deck's `state_json["active"]`),
767 /// or `None` if the deck is empty.
768 pub fn active_title(&self) -> Option<&str> {
769 self.facets.get(self.active).map(|f| f.title())
770 }
771
772 /// The titles of every tabbed facet, in tab order — the discoverable surface a
773 /// host (or a robot-UI control channel) enumerates to know which tabs exist.
774 pub fn titles(&self) -> Vec<&str> {
775 self.facets.iter().map(|f| f.title()).collect()
776 }
777
778 /// Make the facet titled `title` the active tab — the programmatic (headless,
779 /// robot-addressable) equivalent of clicking its tab header. Returns `true` if a
780 /// facet with that title exists (and is now active), `false` otherwise. This is
781 /// the named boundary a control channel switches tabs through (the deck analogue
782 /// of the viz's `Tab::from_name`), so a driver needn't replay a pointer click.
783 pub fn set_active_by_title(&mut self, title: &str) -> bool {
784 match self.facets.iter().position(|f| f.title() == title) {
785 Some(i) => {
786 self.active = i;
787 true
788 }
789 None => false,
790 }
791 }
792
793 // ── responsive menu (hamburger) — the reusable narrow-viewport tab bar ───────
794
795 /// Host-driven: render the tab bar as a compact **hamburger menu** (`≡` + the
796 /// active choice's label, the full list behind a drawer) instead of the inline
797 /// wrapped strip. The host classifies the viewport (e.g.
798 /// `facett_app::scene::Device::from_width`) and calls this each frame; on a
799 /// narrow (phone-class) width the long tab bar would otherwise wrap into many
800 /// rows and bury the active facet below the screen fold. Setting it `false` (a
801 /// wide viewport) restores the inline bar AND shuts the drawer. This is the deck
802 /// analogue of the demo shell's `⚙` control-strip fold — the SAME canvas-first
803 /// pattern applied to the MAIN menu, living once here so every deck host
804 /// (korp/nornir/…) inherits it.
805 pub fn set_menu_collapsed(&mut self, collapsed: bool) {
806 if !collapsed {
807 self.menu_open = false;
808 }
809 self.menu_collapsed = collapsed;
810 }
811 /// Whether the tab bar is currently rendered as the collapsed hamburger menu.
812 pub fn menu_collapsed(&self) -> bool {
813 self.menu_collapsed
814 }
815 /// Whether the hamburger drawer is open (the full choice list is showing).
816 pub fn menu_open(&self) -> bool {
817 self.menu_open
818 }
819 /// Open / shut the hamburger drawer explicitly (the programmatic equivalent of
820 /// tapping `≡`). No visible effect while the menu is not collapsed.
821 pub fn set_menu_open(&mut self, open: bool) {
822 self.menu_open = open;
823 }
824 /// Toggle the hamburger drawer; returns the new open state.
825 pub fn toggle_menu(&mut self) -> bool {
826 self.menu_open = !self.menu_open;
827 self.menu_open
828 }
829
830 /// Typed mutable access to the facet with `title`, downcast to `T` — `None` if
831 /// no such facet, or it doesn't opt into [`Facet::as_any_mut`], or the type
832 /// mismatches. Lets a host drive a concrete component's own API (e.g. a
833 /// robot-UI control forwarding a node selection to a `SystemChart`).
834 pub fn facet_mut<T: std::any::Any>(&mut self, title: &str) -> Option<&mut T> {
835 self.facets
836 .iter_mut()
837 .find(|f| f.title() == title)
838 .and_then(|f| f.as_any_mut())
839 .and_then(|a| a.downcast_mut::<T>())
840 }
841
842 /// Forward one [`Facet::update_json`] message to the facet titled `title` — the
843 /// untyped twin of [`facet_mut`](Self::facet_mut) for a host that holds a message,
844 /// not a type (a deep link, a control channel). `false` when no such facet.
845 pub fn update_json_for(&mut self, title: &str, msg_json: &str) -> bool {
846 match self.facets.iter_mut().find(|f| f.title() == title) {
847 Some(f) => {
848 f.update_json(msg_json);
849 true
850 }
851 None => false,
852 }
853 }
854
855 /// Replace the facet whose `title` matches with `facet` (the box's own title is
856 /// what the deck enumerates afterwards). Returns `true` if a facet was replaced.
857 /// Used by hosts that **reload** a tab's data in place — e.g. the OSM region
858 /// picker rebuilds the `OSM 2D` / `OSM 3D` views from a freshly clipped region
859 /// and swaps them in, keeping the same tab slots (and the active selection).
860 pub fn replace_facet(&mut self, title: &str, facet: Box<dyn Facet>) -> bool {
861 if let Some(slot) = self.facets.iter_mut().find(|f| f.title() == title) {
862 *slot = facet;
863 true
864 } else {
865 false
866 }
867 }
868
869 // ── opt-in effects + theming (see deckfx.rs) ─────────────────────────────
870
871 /// Enable deck effects up front (builder form of [`fx_mut`](Self::fx_mut)).
872 pub fn with_fx(mut self, fx: DeckFx) -> Self {
873 self.fx = fx;
874 self
875 }
876 /// The current deck-effects config (read-only).
877 pub fn fx(&self) -> &DeckFx {
878 &self.fx
879 }
880 /// Mutate the deck-effects config (toggle glow, pin a palette, …).
881 pub fn fx_mut(&mut self) -> &mut DeckFx {
882 &mut self.fx
883 }
884 /// Override the deck theme with palette index `i` (wraps); enables the
885 /// override. Convenience over `fx_mut().set_palette(i)`.
886 pub fn set_palette(&mut self, i: usize) {
887 self.fx.set_palette(i);
888 }
889 /// Advance to the next palette in [`Theme::ALL`] (wrapping); returns the new
890 /// index. Convenience over `fx_mut().cycle_palette()`.
891 pub fn cycle_palette(&mut self) -> usize {
892 self.fx.cycle_palette()
893 }
894
895 /// **Summon the raven** to perch on `target` — any rect a facet/host hands us
896 /// (a table row, a node, a header). Replaces any raven already in flight. The
897 /// body is tinted from the deck's current palette (or the host theme). Logs an
898 /// activity trail entry. Drive/paint happens automatically inside
899 /// [`ui`](Self::ui).
900 pub fn send_raven(&mut self, target: Rect) {
901 let theme = self.effective_theme();
902 self.raven = Some(DeckRaven::new(target, &theme));
903 harness::trail(
904 harness::Kind::Render,
905 format!("raven launched → perch ({:.0},{:.0})", target.center().x, target.top()),
906 );
907 }
908 /// True while a raven is present (flying or perched).
909 pub fn has_raven(&self) -> bool {
910 self.raven.is_some()
911 }
912 /// True once the summoned raven has landed (false if none).
913 pub fn raven_perched(&self) -> bool {
914 self.raven.as_ref().map(|r| r.is_perched()).unwrap_or(false)
915 }
916 /// Dismiss any raven.
917 pub fn clear_raven(&mut self) {
918 self.raven = None;
919 }
920
921 /// The theme the deck paints with: the fx palette override if set, else
922 /// [`Theme::default`] (the host's own `set_theme` still applies its visuals;
923 /// this is just the colour source for deck-owned effects/picker).
924 fn effective_theme(&self) -> Theme {
925 self.fx.theme().unwrap_or_default()
926 }
927
928 /// Draw a one-line **palette picker** — a switcher over [`Theme::ALL`] the
929 /// host can place anywhere (toolbar, menu). Selecting a palette pins the fx
930 /// override; `ui()` then applies it each frame. Returns the chosen index if it
931 /// changed this frame.
932 ///
933 /// The override stays **off until the user actually clicks** a palette: merely
934 /// drawing the picker must not pin index 0, otherwise a host that drives its
935 /// own theme (e.g. the rich [`crate::look::Theme`]) would be silently clobbered
936 /// every frame by the legacy `set_theme` in [`ui`](Self::ui) — size still
937 /// changing (spacing) but colour frozen on `Theme::ALL[0]`. So we only pin when
938 /// the selection genuinely changed this frame.
939 pub fn palette_picker(&mut self, ui: &mut Ui) -> Option<usize> {
940 let mut sel = self.fx.palette().unwrap_or(0);
941 let before = sel;
942 ui.horizontal_wrapped(|ui| {
943 ui.label("Palette:");
944 for (i, ctor) in Theme::ALL.iter().enumerate() {
945 ui.selectable_value(&mut sel, i, ctor().name);
946 }
947 });
948 if sel != before {
949 self.fx.set_palette(sel);
950 }
951 (sel != before).then_some(sel)
952 }
953
954 /// The capabilities of the currently-active facet (or `NONE` if empty).
955 pub fn active_caps(&self) -> FacetCaps {
956 self.facets.get(self.active).map(|f| f.caps()).unwrap_or(FacetCaps::NONE)
957 }
958
959 /// Number of facets in the deck.
960 pub fn len(&self) -> usize {
961 self.facets.len()
962 }
963 /// True when the deck holds no facets.
964 pub fn is_empty(&self) -> bool {
965 self.facets.is_empty()
966 }
967
968 /// **Wall layout** — render **every** facet at once in a wrapping grid of
969 /// `cols` columns, instead of the tabbed one-at-a-time [`ui`](Self::ui). This is
970 /// the "multiple components visible simultaneously" mode a dashboard host wants
971 /// (e.g. several `Graph3D` panes side-by-side). Each cell is a titled group; the
972 /// fx palette override (if set) still applies, and every rendered facet is logged
973 /// to the runtrace ledger keyed `deck.wall:<title>` (mirrors the tab path's
974 /// `deck.render:<title>`), so `state_json`'s `trace.ran` proves each pane drew.
975 pub fn wall_ui(&mut self, ui: &mut Ui, cols: usize) {
976 if let Some(theme) = self.fx.theme() {
977 set_theme(ui.ctx(), theme);
978 }
979 if self.facets.is_empty() {
980 ui.weak("empty deck");
981 return;
982 }
983 let cols = cols.max(1);
984 let spacing = ui.spacing().item_spacing.x;
985 let total_w = ui.available_width();
986 let cell_w = ((total_w - spacing * (cols as f32 - 1.0)) / cols as f32).max(160.0);
987 // A generous cell so 3D graphs have room; the inner facet fills it.
988 let cell_h = 300.0_f32;
989 egui::ScrollArea::vertical()
990 .auto_shrink([false; 2])
991 .show(ui, |ui| {
992 ui.horizontal_wrapped(|ui| {
993 for f in self.facets.iter_mut() {
994 ui.allocate_ui(egui::vec2(cell_w, cell_h), |ui| {
995 let cell = ui.group(|ui| {
996 ui.set_min_size(egui::vec2(cell_w - 12.0, cell_h - 12.0));
997 ui.vertical(|ui| {
998 ui.strong(f.title());
999 ui.separator();
1000 runtrace::ran(&format!("deck.wall:{}", f.title()));
1001 f.ui(ui);
1002 });
1003 });
1004 // The wall shows every pane at once, which is exactly when
1005 // "which crate drew THAT one?" is hardest to answer.
1006 devid::badge(ui, cell.response.rect, f.component(), f.title());
1007 });
1008 }
1009 });
1010 });
1011 }
1012
1013 /// **Render ONE facet into the caller's `Ui`** — the seam a scene host needs to
1014 /// make a deck out of REAL panes instead of emulating one.
1015 ///
1016 /// [`wall_ui`](Self::wall_ui) owns its own grid: it decides the columns, the cell
1017 /// size and the scrolling, and draws every facet inside one `Ui`. That is right for
1018 /// a self-contained dashboard and wrong for `facett_app::scene`, which already has
1019 /// a pane tree, allots each pane its own rect, and gives each one chrome and a
1020 /// published address. A host with a scene could only mount the WHOLE deck into ONE
1021 /// pane, so N panes' worth of content ended up sharing a single allotment — which
1022 /// is precisely the shape that lets one pane's growth displace another.
1023 ///
1024 /// This renders facet `idx` and nothing else, into whatever rect the caller has
1025 /// already decided. No grid, no scroll area, no title strip — the scene's chrome
1026 /// bar carries the title, and a second one would be a second header row.
1027 ///
1028 /// Returns `false` when `idx` is out of range, so a host whose pane tree has
1029 /// drifted from the deck's contents gets a value it can assert on rather than a
1030 /// silently blank pane.
1031 ///
1032 /// The runtrace key is `deck.pane:<title>`, alongside `deck.wall:` and
1033 /// `deck.render:`, so `state_json`'s `trace.ran` still proves the pane drew.
1034 pub fn pane_ui(&mut self, idx: usize, ui: &mut Ui) -> bool {
1035 if let Some(theme) = self.fx.theme() {
1036 set_theme(ui.ctx(), theme);
1037 }
1038 let Some(f) = self.facets.get_mut(idx) else {
1039 return false;
1040 };
1041 runtrace::ran(&format!("deck.pane:{}", f.title()));
1042 // The pane's own rect, captured BEFORE it draws: a pane that consumes the whole
1043 // `Ui` leaves the cursor somewhere unhelpful, so reading it afterwards would
1044 // anchor the chip to wherever the content happened to end.
1045 let rect = ui.max_rect();
1046 let (component, title) = (f.component(), f.title().to_string());
1047 let nav = navgraph::collecting(ui.ctx())
1048 .then(|| devid::badge_text(component, &title).0)
1049 .and_then(|key| navgraph::begin(ui, &key, navgraph::NavKind::Pane, &title));
1050 f.ui(ui);
1051 navgraph::end(ui, nav, rect);
1052 // The DEV-ID chip — one draw site, so EVERY deck pane gets it for free (LAW 5)
1053 // rather than 70-odd panes each remembering to paint their own. No-op in release.
1054 devid::badge(ui, rect, component, &title);
1055 true
1056 }
1057
1058 /// Open the active facet's navgraph Pane (dev mode, collecting only — the key is a
1059 /// `format!`, so it is not built otherwise).
1060 fn nav_pane_begin(&self, ui: &Ui) -> Option<navgraph::Token> {
1061 if !navgraph::collecting(ui.ctx()) {
1062 return None;
1063 }
1064 let f = self.facets.get(self.active)?;
1065 let (key, _) = devid::badge_text(f.component(), f.title());
1066 navgraph::begin(ui, &key, navgraph::NavKind::Pane, f.title())
1067 }
1068
1069 /// The title of facet `idx`, for a host naming its panes from the deck.
1070 pub fn pane_title(&self, idx: usize) -> Option<&str> {
1071 self.facets.get(idx).map(|f| f.title())
1072 }
1073
1074 /// The active facet's current scale (1.0 if none / not scalable).
1075 fn active_scale(&self) -> f32 {
1076 self.facets.get(self.active).map(|f| f.scale()).unwrap_or(1.0)
1077 }
1078
1079 /// Multiply the active facet's scale by `k`, clamped to **the facet's own**
1080 /// [`Facet::scale_range`] — not to a hardcoded document-viewer band. A facet whose
1081 /// native range is wider (a map: 1.25-million-fold) would otherwise saturate the
1082 /// clamp on the first click and have its camera written backwards.
1083 fn scale_active(&mut self, k: f32) {
1084 if let Some(f) = self.facets.get_mut(self.active) {
1085 let (lo, hi) = f.scale_range();
1086 let s = (f.scale() * k).clamp(lo, hi);
1087 f.set_scale(s);
1088 }
1089 }
1090
1091 /// Reset the active facet's scale to native.
1092 fn reset_scale(&mut self) {
1093 if let Some(f) = self.facets.get_mut(self.active) {
1094 f.set_scale(1.0);
1095 }
1096 }
1097
1098 /// Draw the tab bar + capability toolbar + the active facet, and route
1099 /// capability-gated shortcuts (Ctrl-+/-/0 for scale; Ctrl-C/X/V for clipboard).
1100 pub fn ui(&mut self, ui: &mut Ui) {
1101 // Opt-in palette override: apply the chosen Theme::ALL palette + its
1102 // egui Visuals each frame so the whole deck (and every facet that reads
1103 // `theme(ui)`) follows. No override → the host's own theme stays.
1104 if let Some(theme) = self.fx.theme() {
1105 set_theme(ui.ctx(), theme);
1106 }
1107
1108 let titles: Vec<String> = self.facets.iter().map(|f| f.title().to_string()).collect();
1109 // The tab bar has TWO forms (responsive, host-driven via `set_menu_collapsed`):
1110 // • WIDE viewport → the inline wrapped strip (every tab visible + clickable).
1111 // • NARROW (phone) → a compact `≡` HAMBURGER header + a drawer of choices,
1112 // so the long list doesn't wrap into many rows and bury the canvas.
1113 // Capture the bar's rect either way so a headless test can prove the collapsed
1114 // menu is one compact row, not a viewport-eating wrap.
1115 let bar = ui.scope(|ui| {
1116 if self.menu_collapsed {
1117 self.draw_menu_drawer(&titles, ui);
1118 } else {
1119 // Wrap the tab bar: with many facets a single non-wrapping row overflows
1120 // the panel width and the trailing tabs become unreachable (off-screen,
1121 // unclickable for a robot driver / pointer). Wrapping keeps every tab
1122 // visible + clickable no matter how many facets the deck holds.
1123 // navgraph: the strip is a Group whose draw order IS its declared order
1124 // (the deck's facet order), and each tab is a focusable Field.
1125 //
1126 // GROUPED (opt-in `with_groups`): a group row first, then ONLY the active
1127 // group's tabs in the same `tabs` strip — so a tab's navgraph id
1128 // (`…tabs.<title>`) and its AccessKit label are the ones the flat strip had.
1129 let shown: Vec<usize> = match self.active_group() {
1130 Some(g) => {
1131 self.draw_group_row(ui);
1132 // The group row may have switched the active facet.
1133 let g = self.active_group().unwrap_or(g);
1134 self.groups[g].members.clone()
1135 }
1136 None => (0..titles.len()).collect(),
1137 };
1138 let nav = navgraph::begin(ui, "tabs", navgraph::NavKind::Group, "tabs");
1139 navgraph::declare_draw_order(ui, nav);
1140 let strip = ui.horizontal_wrapped(|ui| {
1141 for &i in &shown {
1142 let t = &titles[i];
1143 let r = ui.selectable_value(&mut self.active, i, t);
1144 navgraph::field(ui, t, &r);
1145 }
1146 });
1147 navgraph::end(ui, nav, strip.response.rect);
1148 self.note_group_entry();
1149 }
1150 });
1151 self.menu_bar_rect = bar.response.rect;
1152
1153 let caps = self.active_caps();
1154
1155 // Capability-driven toolbar: only show controls the active facet honors.
1156 if caps.scalable {
1157 ui.horizontal(|ui| {
1158 if ui.button("−").on_hover_text("Zoom out (Ctrl-−)").clicked() {
1159 self.scale_active(1.0 / 1.1);
1160 }
1161 ui.label(format!("{:.0}%", self.active_scale() * 100.0));
1162 if ui.button("+").on_hover_text("Zoom in (Ctrl-+)").clicked() {
1163 self.scale_active(1.1);
1164 }
1165 if ui.button("Reset").on_hover_text("Reset zoom (Ctrl-0)").clicked() {
1166 self.reset_scale();
1167 }
1168 });
1169 }
1170
1171 // Capability-gated scale shortcuts. egui has no semantic event for these,
1172 // so we hand-detect the key combos (clipboard uses semantic events below).
1173 if caps.scalable {
1174 let (cmd, plus, minus, zero) = ui.input(|i| {
1175 (
1176 i.modifiers.command,
1177 i.key_pressed(egui::Key::Plus) || i.key_pressed(egui::Key::Equals),
1178 i.key_pressed(egui::Key::Minus),
1179 i.key_pressed(egui::Key::Num0),
1180 )
1181 });
1182 if cmd {
1183 if plus {
1184 self.scale_active(1.1);
1185 }
1186 if minus {
1187 self.scale_active(1.0 / 1.1);
1188 }
1189 if zero {
1190 self.reset_scale();
1191 }
1192 }
1193 }
1194
1195 // Clipboard routing: drain semantic events and dispatch to the active
1196 // facet, gated by its caps. A focused TextEdit already consumed its own.
1197 self.route_clipboard(ui.ctx());
1198
1199 // Cross-instance component clone (DISTINCT gesture): the Ctrl+Shift+C/V
1200 // accelerators + any pending envelope paste, drained the same frame.
1201 self.route_component_clipboard(ui);
1202
1203 ui.separator();
1204 // Optionally wrap the active facet in the shared glass/card chrome
1205 // (`chrome` module), gated by the active EffectsPolicy. Reserve a paint slot
1206 // BEFORE the content so the glass fill sits behind it; the glow + border
1207 // edge is painted on top afterwards.
1208 let chrome_on = self.fx.chrome;
1209 let chrome_slot = chrome_on.then(|| ui.painter().add(egui::Shape::Noop));
1210 // navgraph: the active facet is a Pane keyed like its dev-id chip, opened
1211 // BEFORE it draws so its atoms hang under it; the badge below merges into it.
1212 let nav = self.nav_pane_begin(ui);
1213 // Render the active facet, capturing the rect it occupied so the deck can
1214 // bloom it (opt-in glow) without the facet knowing.
1215 let content = ui.scope(|ui| {
1216 if let Some(f) = self.facets.get_mut(self.active) {
1217 // Render-trace: this facet's `ui()` RAN this frame (the wasm-safe
1218 // "what ran" ledger — folded into state_json, read via the JS hook
1219 // on wasm). Keyed by tab title so the ran-list maps tab → ran?.
1220 runtrace::ran(&format!("deck.render:{}", f.title()));
1221 f.ui(ui);
1222 }
1223 });
1224 let content_rect = content.response.rect;
1225 navgraph::end(ui, nav, content_rect);
1226 // The DEV-ID chip, on the rect the facet actually occupied. This is the draw
1227 // path the apps really use (`Deck::ui`); `pane_ui` below is the host-driven
1228 // one. Both paint it, because a badge wired only into the path nobody calls is
1229 // a feature that ships green and never appears (facett-demo goes through HERE).
1230 if let Some(f) = self.facets.get(self.active) {
1231 let (component, title) = (f.component(), f.title().to_string());
1232 devid::badge(ui, content_rect, component, &title);
1233 }
1234 // Remember the "canvas" rect — the screen the collapsed menu hands to the
1235 // active facet (read back via `state_json.menu.content_rect`).
1236 self.content_rect = content_rect;
1237
1238 // Paint the card chrome around the facet's content rect.
1239 if let Some(slot) = chrome_slot
1240 && content_rect.is_positive()
1241 {
1242 let theme = self.effective_theme();
1243 let policy = crate::look::effects_policy(ui);
1244 let style = chrome::ChromeStyle::default().for_policy(policy);
1245 let card = content_rect.expand(6.0);
1246 ui.painter().set(slot, chrome::fill_shape(card, &theme, policy, style));
1247 chrome::edge(ui.painter(), card, &theme, policy, style);
1248 }
1249
1250 // Right-click the active facet body → the Copy/Paste-component menu (the
1251 // discoverable affordance for the cross-instance clone gesture). The
1252 // text clipboard's own copy/paste is unaffected (different gesture).
1253 if !self.active_kind().is_empty() {
1254 content.response.context_menu(|ui| self.component_menu(ui));
1255 }
1256
1257 // Opt-in glow on the active facet's content rect, pulsing.
1258 if self.fx.glow && content_rect.is_positive() {
1259 let theme = self.effective_theme();
1260 let time = ui.input(|i| i.time);
1261 let painter = ui.painter_at(content_rect);
1262 deckfx::paint_active_glow(&painter, content_rect.shrink(2.0), &theme, &self.fx, time);
1263 ui.ctx().request_repaint(); // keep the pulse animating
1264 }
1265
1266 // Drive + paint a summoned raven on a foreground layer above everything.
1267 self.drive_raven(ui.ctx());
1268
1269 // Paint the component-clone toast (mismatch / rejection feedback) on top.
1270 self.paint_component_toast(ui);
1271 }
1272
1273 /// Draw the collapsed **hamburger menu** for a narrow viewport: a compact header
1274 /// (`≡` / `✕` toggle + the active choice's label) and, when the drawer is open, the
1275 /// full choice list as a vertical, scrollable drawer. Picking a choice switches the
1276 /// active facet AND shuts the drawer (canvas-first again). Mirrors the demo shell's
1277 /// `⚙` control-strip fold, applied to the MAIN menu.
1278 fn draw_menu_drawer(&mut self, titles: &[String], ui: &mut Ui) {
1279 let active_label = titles.get(self.active).cloned().unwrap_or_default();
1280 ui.horizontal(|ui| {
1281 // The hamburger toggle. `≡` closed, `✕` open — a single tappable glyph.
1282 let glyph = if self.menu_open { "✕" } else { "≡" };
1283 let hint = if self.menu_open { "close the menu — give the canvas the screen" } else { "choose a view" };
1284 if ui.selectable_label(self.menu_open, glyph).on_hover_text(hint).clicked() {
1285 self.menu_open = !self.menu_open;
1286 }
1287 // The current choice's label, so the collapsed header still says WHAT is shown.
1288 ui.label(&active_label);
1289 });
1290 if self.menu_open {
1291 // The full choice list as a vertical DRAWER (bounded + scrollable so 60+
1292 // choices never blow past the viewport). Selecting one switches + closes.
1293 egui::Frame::group(ui.style()).show(ui, |ui| {
1294 egui::ScrollArea::vertical().max_height(420.0).auto_shrink([false, true]).show(ui, |ui| {
1295 // Grouped deck: each group's name as a heading over its tabs (a
1296 // drawer has the height for both levels at once). Ungrouped: one list.
1297 let sections: Vec<(Option<String>, Vec<usize>)> = if self.groups.is_empty() {
1298 vec![(None, (0..titles.len()).collect())]
1299 } else {
1300 self.groups.iter().map(|g| (Some(g.name.clone()), g.members.clone())).collect()
1301 };
1302 for (name, members) in sections {
1303 if let Some(name) = name {
1304 ui.add_space(4.0);
1305 ui.label(egui::RichText::new(name).strong());
1306 }
1307 for i in members {
1308 let Some(t) = titles.get(i) else { continue };
1309 if ui.selectable_label(self.active == i, t.as_str()).clicked() {
1310 self.active = i;
1311 self.menu_open = false;
1312 }
1313 }
1314 }
1315 });
1316 });
1317 }
1318 }
1319
1320 /// Advance + paint the summoned raven (if any) on a foreground layer. Pins its
1321 /// launch time on the first frame and keeps repainting while it flies.
1322 fn drive_raven(&mut self, ctx: &egui::Context) {
1323 let Some(raven) = self.raven.as_mut() else { return };
1324 raven.sprite.update(ctx);
1325 let painter =
1326 ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("facett_deck_raven")));
1327 raven.sprite.paint(&painter);
1328 }
1329
1330 /// Route this frame's clipboard events to the active facet, gated by caps.
1331 /// The single OS-touching write (`clipboard::put`) lives here.
1332 fn route_clipboard(&mut self, ctx: &egui::Context) {
1333 let caps = self.active_caps();
1334 if !(caps.copyable || caps.cuttable || caps.pasteable) {
1335 return;
1336 }
1337 for action in clipboard::poll(ctx) {
1338 let Some(f) = self.facets.get_mut(self.active) else { continue };
1339 match action {
1340 ClipAction::Copy if caps.copyable => {
1341 if let Some(t) = f.copy() {
1342 clipboard::put(ctx, t);
1343 }
1344 }
1345 ClipAction::Cut if caps.cuttable => {
1346 if let Some(t) = f.cut() {
1347 clipboard::put(ctx, t);
1348 }
1349 }
1350 ClipAction::Paste(s) if caps.pasteable => {
1351 f.paste(&s);
1352 }
1353 // Capability not declared → ignore (event may belong to a focused
1354 // sub-widget egui already handled).
1355 _ => {}
1356 }
1357 }
1358 }
1359
1360 // ── cross-instance component clone (Copy/Paste component) ────────────────
1361 //
1362 // A DISTINCT gesture from the text clipboard above: it transfers a facet's
1363 // type-tagged PORTABLE state (not a text selection) to a same-kind sibling.
1364 // See `.nornir/design/copy-paste-between-instances.md`. Surfaced two ways —
1365 // the context menu in `component_menu` (right-click the body) and the
1366 // `Ctrl+Shift+C / Ctrl+Shift+V` accelerators routed in `ui`.
1367
1368 /// The active facet's [`Facet::kind`] (`""` if empty / opted out).
1369 pub fn active_kind(&self) -> &'static str {
1370 self.facets.get(self.active).map(|f| f.kind()).unwrap_or("")
1371 }
1372
1373 /// **Copy component** — encode the active facet's [`Facet::portable_state`]
1374 /// into the tagged clipboard envelope and place it on the OS clipboard.
1375 /// Returns the envelope text on success, or `None` if the active facet opts
1376 /// out (empty `kind()` or no `portable_state()`). This is the data half the
1377 /// gesture handlers + tests drive; the OS write is the caller's via
1378 /// [`clipboard::put`] (done for them in [`copy_component`](Self::copy_component)).
1379 pub fn copy_component_envelope(&self) -> Option<String> {
1380 let f = self.facets.get(self.active)?;
1381 let kind = f.kind();
1382 if kind.is_empty() {
1383 return None;
1384 }
1385 let state = f.portable_state()?;
1386 Some(clipboard::encode_component(kind, &state))
1387 }
1388
1389 /// Copy the active facet's portable state to the OS clipboard (the full
1390 /// gesture). Returns `true` if something was copied.
1391 pub fn copy_component(&mut self, ctx: &egui::Context) -> bool {
1392 match self.copy_component_envelope() {
1393 Some(env) => {
1394 clipboard::put(ctx, env);
1395 true
1396 }
1397 None => false,
1398 }
1399 }
1400
1401 /// **Paste component** — decode a clipboard `text` envelope and, **only if its
1402 /// kind matches the active facet's** [`Facet::kind`], hand the state to
1403 /// [`Facet::load_state`]. Returns `true` if the active facet adopted it.
1404 /// A kind mismatch (or a non-envelope / wrong-version text) is a no-op that
1405 /// raises a themed mismatch [`toast`](Self::toast) — the type-match guard is
1406 /// the whole point: a `table` envelope NEVER loads into a `graphpan`.
1407 pub fn paste_component(&mut self, text: &str, now: f64) -> bool {
1408 let Some((kind, state)) = clipboard::decode_component(text) else {
1409 // Not a component envelope at all — leave it for the text path; no toast.
1410 return false;
1411 };
1412 let active_kind = self.active_kind();
1413 if active_kind.is_empty() {
1414 self.toast = Some(("this view doesn't accept a pasted component".to_string(), now));
1415 return false;
1416 }
1417 if kind != active_kind {
1418 self.toast = Some((format!("clipboard holds a `{kind}`, not a `{active_kind}`"), now));
1419 return false;
1420 }
1421 let Some(f) = self.facets.get_mut(self.active) else { return false };
1422 let accepted = f.load_state(&state);
1423 if !accepted {
1424 self.toast = Some((format!("this `{active_kind}` could not adopt the clipboard state"), now));
1425 }
1426 accepted
1427 }
1428
1429 /// The current component-clone toast message (if one is live), for tests /
1430 /// hosts that want to surface it themselves.
1431 pub fn component_toast(&self) -> Option<&str> {
1432 self.toast.as_ref().map(|(m, _)| m.as_str())
1433 }
1434
1435 /// Right-click context-menu entries for the cross-instance clone gesture —
1436 /// **Copy component** / **Paste component** — themed by the active style. A
1437 /// host attaches these to the facet body (or its tab) via
1438 /// `response.context_menu(|ui| deck.component_menu(ui))`. Greys out when the
1439 /// active facet opts out (empty `kind()`).
1440 pub fn component_menu(&mut self, ui: &mut egui::Ui) {
1441 let km = look::keymap(ui);
1442 let kind = self.active_kind();
1443 let can_clone = !kind.is_empty();
1444 ui.add_enabled_ui(can_clone && self.copy_component_envelope().is_some(), |ui| {
1445 let label = format!("Copy component {}", km.label(Action::Copy, ui.ctx()));
1446 if ui.button(label).clicked() {
1447 self.copy_component(ui.ctx());
1448 ui.close();
1449 }
1450 });
1451 ui.add_enabled_ui(can_clone, |ui| {
1452 let label = format!("Paste component {}", km.label(Action::Paste, ui.ctx()));
1453 if ui.button(label).clicked() {
1454 // Pull the OS clipboard via egui's paste request; the actual text
1455 // arrives next frame as an Event::Paste, routed in `route_component_clipboard`.
1456 ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste);
1457 ui.close();
1458 }
1459 });
1460 }
1461
1462 /// Route the `Ctrl+Shift+C / Ctrl+Shift+V` component-clone accelerators +
1463 /// drain any pending paste envelope. Called once per frame from [`ui`](Self::ui),
1464 /// AFTER the text clipboard so a focused TextEdit's plain Ctrl+C/V is untouched
1465 /// (the Shift discriminates this gesture from text copy/paste).
1466 fn route_component_clipboard(&mut self, ui: &mut egui::Ui) {
1467 let now = ui.input(|i| i.time);
1468 // Accelerators: Ctrl+Shift+C copies; Ctrl+Shift+V triggers an OS-clipboard
1469 // paste request (the text lands next frame as Event::Paste, decoded below).
1470 let copy_shift = egui::KeyboardShortcut::new(
1471 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
1472 egui::Key::C,
1473 );
1474 let paste_shift = egui::KeyboardShortcut::new(
1475 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
1476 egui::Key::V,
1477 );
1478 if ui.input_mut(|i| i.consume_shortcut(©_shift)) {
1479 self.copy_component(ui.ctx());
1480 }
1481 if ui.input_mut(|i| i.consume_shortcut(&paste_shift)) {
1482 ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste);
1483 }
1484 // Drain any Paste events that look like a component envelope (a plain text
1485 // paste decodes to None here and is left for the text clipboard path).
1486 let pastes: Vec<String> = ui.input(|i| {
1487 i.events
1488 .iter()
1489 .filter_map(|e| match e {
1490 egui::Event::Paste(s) if clipboard::decode_component(s).is_some() => Some(s.clone()),
1491 _ => None,
1492 })
1493 .collect()
1494 });
1495 for text in pastes {
1496 self.paste_component(&text, now);
1497 }
1498 // Age out the toast.
1499 if let Some((_, raised)) = self.toast && now - raised > TOAST_SECS {
1500 self.toast = None;
1501 }
1502 }
1503
1504 /// Paint the live component-clone toast on a foreground layer (themed, spacious),
1505 /// if one is set. A no-op when there is no toast.
1506 fn paint_component_toast(&self, ui: &mut egui::Ui) {
1507 let Some((msg, _)) = self.toast.as_ref() else { return };
1508 let th = theme(ui);
1509 let ctx = ui.ctx();
1510 let painter =
1511 ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("facett_deck_component_toast")));
1512 let screen = ctx.content_rect();
1513 let font = FontId::proportional(14.0);
1514 let galley = painter.layout_no_wrap(msg.clone(), font.clone(), th.text);
1515 let pad = vec2(14.0, 10.0); // spacious preset padding
1516 let size = galley.size() + pad * 2.0;
1517 // Bottom-centre, lifted off the edge.
1518 let center = Pos2::new(screen.center().x, screen.max.y - size.y * 0.5 - 18.0);
1519 let rect = Rect::from_center_size(center, size);
1520 painter.rect_filled(rect, 8.0, th.panel_bg);
1521 painter.rect_stroke(rect, 8.0, Stroke::new(1.0_f32, th.panel_stroke), egui::StrokeKind::Inside);
1522 painter.galley(rect.min + pad, galley, th.text);
1523 ctx.request_repaint(); // keep ticking so the toast ages out on time
1524 }
1525
1526 /// The whole-app observable state: the active facet + each facet's
1527 /// `state_json`, plus an **additive** sibling `caps` map (title → caps JSON)
1528 /// so the existing flat `facets[title]` shape is unchanged for consumers.
1529 pub fn state_json(&self) -> serde_json::Value {
1530 self.state_json_inner(None)
1531 }
1532
1533 /// [`state_json`](Self::state_json) for a host that publishes it **every frame**
1534 /// (the wasm demo's `window.__facett_state()`): the ACTIVE facet's state is built
1535 /// every call, ONE inactive facet's in turn (round-robin), and every other inactive
1536 /// facet's is the copy `cache` holds from its last turn — so a frame pays for the
1537 /// tab on screen plus 1/N of the rest instead of all N.
1538 ///
1539 /// MEASURED (lane M, 2026-10-02): the pages demo serialised all 81 tabs every frame;
1540 /// with `lineage` at 100k on screen that included the inactive `Graphs` tab's full
1541 /// demo-data state (its population graph: 102 kB, 1.2 ms per frame natively on
1542 /// dwarf, vs lineage's demo 34 µs when `Graphs` is the one on screen) — the whole
1543 /// gap between lineage's 56.8 fps and Graphs' 60.2 on loki's RTX 5080. An inactive
1544 /// tab's state is at most one round (N frames) old; a tab is fresh from the frame it
1545 /// becomes active. The shape is `state_json`'s exactly.
1546 pub fn state_json_rolling(&self, cache: &mut DeckStateCache) -> serde_json::Value {
1547 self.state_json_inner(Some(cache))
1548 }
1549
1550 /// Hand the facets map of a [`state_json_rolling`](Self::state_json_rolling) result
1551 /// (`deck` = that value, or the `"deck"` subtree a host embedded it in) back to `cache`.
1552 pub fn return_rolling(cache: &mut DeckStateCache, mut deck: serde_json::Value) {
1553 if let Some(serde_json::Value::Object(m)) = deck.get_mut("facets").map(serde_json::Value::take) {
1554 cache.facets = m;
1555 }
1556 }
1557
1558 /// **Serialise a state that embeds a rolling deck state** (at `deck_pointer`, e.g.
1559 /// `"/deck"`, or `""` for the deck state itself) and hand its facets back to `cache`.
1560 /// Each facet's JSON text is reused unless its state was rebuilt this call, so a
1561 /// frame serialises the tab on screen + one other, not every tab's tree — the bytes
1562 /// are `serde_json::to_string`'s exactly.
1563 pub fn serialize_rolling(cache: &mut DeckStateCache, mut state: serde_json::Value, deck_pointer: &str) -> String {
1564 const MARK: &str = "\u{0}facett-rolling-facets\u{0}";
1565 let slot = state.pointer_mut(&format!("{deck_pointer}/facets"));
1566 let Some(slot) = slot else { return serde_json::to_string(&state).unwrap_or_default() };
1567 let serde_json::Value::Object(facets) = std::mem::replace(slot, serde_json::Value::String(MARK.into())) else {
1568 return serde_json::to_string(&state).unwrap_or_default();
1569 };
1570 let head = serde_json::to_string(&state).unwrap_or_default();
1571 cache.text.retain(|k, _| facets.contains_key(k));
1572 let mut body = String::with_capacity(cache.text.values().map(|t| t.len() + 32).sum::<usize>() + 2);
1573 body.push('{');
1574 for (i, (k, v)) in facets.iter().enumerate() {
1575 if i > 0 {
1576 body.push(',');
1577 }
1578 body.push_str(&serde_json::to_string(k).unwrap_or_default());
1579 body.push(':');
1580 match cache.text.get(k) {
1581 Some(t) => body.push_str(t),
1582 None => {
1583 let t = serde_json::to_string(v).unwrap_or_default();
1584 body.push_str(&t);
1585 cache.text.insert(k.clone(), t);
1586 }
1587 }
1588 }
1589 body.push('}');
1590 cache.facets = facets;
1591 let mark = serde_json::to_string(MARK).unwrap_or_default();
1592 head.replacen(&mark, &body, 1)
1593 }
1594
1595 fn state_json_inner(&self, cache: Option<&mut DeckStateCache>) -> serde_json::Value {
1596 let mut caps = serde_json::Map::new();
1597 for f in &self.facets {
1598 caps.insert(f.title().to_string(), f.caps().to_json());
1599 }
1600 let facets = match cache {
1601 None => self.facets.iter().map(|f| (f.title().to_string(), f.state_json())).collect(),
1602 Some(c) => {
1603 let n = self.facets.len();
1604 // A map that does not hold exactly this deck's titles is rebuilt whole.
1605 if c.facets.len() != n || self.facets.iter().any(|f| !c.facets.contains_key(f.title())) {
1606 c.facets.clear();
1607 c.text.clear();
1608 }
1609 // This call's round-robin turn: the next inactive facet after the last one.
1610 let turn = (0..n).map(|k| (c.next + k) % n.max(1)).find(|&i| i != self.active);
1611 c.next = turn.map_or(0, |i| i + 1);
1612 for (i, f) in self.facets.iter().enumerate() {
1613 if i == self.active || Some(i) == turn || !c.facets.contains_key(f.title()) {
1614 c.built += 1;
1615 c.facets.insert(f.title().to_string(), f.state_json());
1616 c.text.remove(f.title());
1617 }
1618 }
1619 std::mem::take(&mut c.facets)
1620 }
1621 };
1622 let mr = self.menu_bar_rect;
1623 let cr = self.content_rect;
1624 serde_json::json!({
1625 "active": self.facets.get(self.active).map(|f| f.title()),
1626 "facets": facets,
1627 "caps": caps,
1628 // The RESPONSIVE menu (#39-follow): whether the tab bar is the collapsed
1629 // hamburger (phone-class) and, if so, whether its drawer is open — plus the
1630 // menu-header rect and the active-facet ("canvas") rect, so a headless test
1631 // proves the collapsed menu is one compact row and the canvas gets the screen.
1632 "menu": {
1633 "collapsed": self.menu_collapsed,
1634 "open": self.menu_open,
1635 "active": self.facets.get(self.active).map(|f| f.title()),
1636 "count": self.facets.len(),
1637 // The two-level bar (`with_groups`): the active group + every group's
1638 // name and size, in display order. `null` / `[]` when ungrouped.
1639 "group": self.active_group_name(),
1640 "groups": self.groups.iter().map(|g| serde_json::json!({
1641 "name": g.name,
1642 "tabs": g.members.len(),
1643 })).collect::<Vec<_>>(),
1644 "bar_rect": [mr.min.x, mr.min.y, mr.width(), mr.height()],
1645 "content_rect": [cr.min.x, cr.min.y, cr.width(), cr.height()],
1646 },
1647 // The deck's opt-in effects (DeckFx) as data: whether the shared glass/
1648 // card `chrome` wrap is on, whether the active-facet bloom glow is on, and
1649 // the active palette override. A headless driver reads this to PROVE the
1650 // T1.3 showcase rendering (glass + bloom) is actually wired, not eyeballed.
1651 "fx": {
1652 "chrome": self.fx.chrome,
1653 "glow": self.fx.glow,
1654 "glow_layers": self.fx.glow_layers,
1655 "palette": self.fx.palette(),
1656 },
1657 // The wasm-safe "what RAN" ledger — every facet render + every traced
1658 // control handler that has executed this session (the readable proof
1659 // the shipped artifact actually ran each surface). See `runtrace`.
1660 "trace": { "ran": runtrace::snapshot(), "distinct": runtrace::distinct() },
1661 // The DEV-ID gate — enabled/env/profile/source. Reports whether the chips
1662 // are SWITCHED ON, not whether one is on screen; see `devid::gate_json`.
1663 "devid": devid::gate_json(),
1664 })
1665 }
1666}
1667
1668/// A stable, bright-ish colour from a string (FNV-1a). Handy default node colour.
1669pub fn hash_color(s: &str) -> Color32 {
1670 let mut h: u32 = 2166136261;
1671 for b in s.bytes() {
1672 h = (h ^ b as u32).wrapping_mul(16777619);
1673 }
1674 Color32::from_rgb((h & 0xFF) as u8 | 0x60, ((h >> 8) & 0xFF) as u8 | 0x60, ((h >> 16) & 0xFF) as u8 | 0x60)
1675}
1676
1677#[cfg(test)]
1678mod tests {
1679 use super::*;
1680
1681 #[test]
1682 fn scene_builds() {
1683 let mut s = Scene::new();
1684 let a = s.node("Person", hash_color("Person"));
1685 let b = s.node("Company", hash_color("Company"));
1686 s.edge(a, b);
1687 assert_eq!(s.nodes.len(), 2);
1688 assert_eq!(s.edges.len(), 1);
1689 assert!(!s.is_empty());
1690 }
1691
1692 #[test]
1693 fn force_layout_produces_finite_bounded_positions() {
1694 let mut scene = Scene::new();
1695 for i in 0..12 { scene.node(format!("n{i}"), hash_color("n")); }
1696 for i in 0..12 { scene.edge(i, (i + 1) % 12); }
1697 let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(400.0, 400.0));
1698 let pos = positions(Layout::Force, &scene, rect);
1699 assert_eq!(pos.len(), 12);
1700 for p in &pos {
1701 assert!(p.x.is_finite() && p.y.is_finite(), "finite");
1702 assert!(rect.expand(50.0).contains(*p), "roughly within the rect");
1703 }
1704 }
1705
1706 /// **Scale (RED-when-broken): the repulsion is sub-quadratic, measured as a
1707 /// GROWTH RATIO and not as a wall clock.**
1708 ///
1709 /// This was `assert!(ms < 20_000.0)` on one 10 000-node run, which is two defects
1710 /// in one line (stinky `mapgpu-2`): on a loaded box a *correct* implementation
1711 /// fails (MEASURED 2026-08-03: 39 616 ms at load average 120 on 32 cores), and on
1712 /// an idle box an O(n²) implementation *passes*. A wall clock cannot answer a
1713 /// complexity question — it answers a hardware question.
1714 ///
1715 /// What is measured instead is `t(4n) / t(n)`, which is ~16 for a quadratic
1716 /// repulsion and ~2–4 for `O(n log n)`. A ratio is immune to machine load because
1717 /// both halves of it contend for the same cores in the same run, and the **4×**
1718 /// spacing (rather than 2×) is deliberate: it puts the two classes an order of
1719 /// magnitude apart, so load only has to be survived, not eliminated.
1720 ///
1721 /// **ARM 1 is a red probe that runs every time.** Below
1722 /// [`BH_THRESHOLD`](crate::barnes_hut::BH_THRESHOLD) `positions` deliberately keeps
1723 /// the exact all-pairs loop, so the same instrument is pointed at a *known
1724 /// quadratic* and required to say so against the *same gate*. If arm 1 cannot see
1725 /// quadratic growth where quadratic growth demonstrably lives, arm 2's green is not
1726 /// evidence and the test fails at arm 1 instead of passing blind.
1727 ///
1728 /// MEASURED on oden 2026-08-22, debug build, load average 91 on 32 cores:
1729 /// quadratic arm `n=250 194.4 ms → n=1000 3 625.7 ms = 18.651`; Barnes–Hut arm
1730 /// `n=2000 1 541.5 ms → n=8000 3 043.7 ms = 1.975`. That is a **9.4× separation**,
1731 /// and the single gate below sits in the empty middle of it.
1732 ///
1733 /// **SEEN RED**: an earlier 2×-spaced revision of this test was run with `use_bh`
1734 /// forced to `false` in [`positions`] — the exact regression it exists to catch —
1735 /// and failed with `26 656.7 ms → 68 839.0 ms = 2.582` against a correct 1.502 on
1736 /// the same box. That run also showed *why* the spacing was widened to 4×: at load
1737 /// average 121 a 2× step compresses a true quadratic from 3.976 to 3.151 and the
1738 /// regressed Barnes–Hut arm to 2.582, which is far too little daylight.
1739 #[test]
1740 fn force_layout_repulsion_is_sub_quadratic() {
1741 /// The gate BOTH arms are judged against. Quadratic growth over a 4× step is
1742 /// ~16; `O(n log n)` is ~2–4. One number, so the red probe and the claim
1743 /// cannot drift apart.
1744 const QUADRATIC_GATE: f64 = 8.0;
1745
1746 /// A sparse ring + chords: O(n) edges, so the only super-linear term left in
1747 /// the layout is the repulsion this test is about.
1748 fn ring_scene(n: usize) -> Scene {
1749 let mut scene = Scene::new();
1750 for i in 0..n {
1751 scene.node(format!("n{i}"), hash_color("n"));
1752 }
1753 for i in 0..n {
1754 scene.edge(i, (i + 1) % n);
1755 if i % 7 == 0 {
1756 scene.edge(i, (i + 137) % n);
1757 }
1758 }
1759 scene
1760 }
1761 let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1024.0, 1024.0));
1762 // Best of two: the MINIMUM is the estimator least polluted by a scheduler
1763 // steal, and a steal can only ever make a run slower, never faster.
1764 let run = |n: usize| -> f64 {
1765 let scene = ring_scene(n);
1766 let mut best = f64::INFINITY;
1767 for _ in 0..2 {
1768 let t0 = std::time::Instant::now();
1769 let pos = positions(Layout::Force, &scene, rect);
1770 let ms = t0.elapsed().as_secs_f64() * 1000.0;
1771 assert_eq!(pos.len(), n);
1772 for p in &pos {
1773 assert!(p.x.is_finite() && p.y.is_finite(), "every node finite at n={n}");
1774 assert!(rect.expand(50.0).contains(*p), "every node bounded at n={n}");
1775 }
1776 best = best.min(ms);
1777 }
1778 best
1779 };
1780
1781 // ── ARM 1 (RED PROBE): the instrument sees a quadratic when there IS one ──
1782 const QUAD_N: usize = 250;
1783 const _: () = assert!(
1784 4 * QUAD_N < crate::barnes_hut::BH_THRESHOLD,
1785 "arm 1 must stay entirely on the exact all-pairs path"
1786 );
1787 let q1 = run(QUAD_N);
1788 let q4 = run(4 * QUAD_N);
1789 let quad_ratio = q4 / q1;
1790 assert!(
1791 quad_ratio >= QUADRATIC_GATE,
1792 "RED PROBE FAILED: the exact all-pairs repulsion below BH_THRESHOLD grew only \
1793 {quad_ratio:.3}x from n={QUAD_N} ({q1:.1} ms) to n={} ({q4:.1} ms), against the \
1794 {QUADRATIC_GATE} this test calls quadratic (measured 18.651 on oden). This box cannot \
1795 currently tell quadratic from n log n, so the Barnes-Hut arm below would be blind — \
1796 re-run it somewhere less contended rather than trusting a green.",
1797 4 * QUAD_N
1798 );
1799
1800 // ── ARM 2: the claim ──────────────────────────────────────────────────
1801 const BH_N: usize = 2_000;
1802 const _: () = assert!(BH_N >= crate::barnes_hut::BH_THRESHOLD, "arm 2 must be on the Barnes-Hut path");
1803 let b1 = run(BH_N);
1804 let b4 = run(4 * BH_N);
1805 let bh_ratio = b4 / b1;
1806 assert!(
1807 bh_ratio < QUADRATIC_GATE,
1808 "the force layout is not sub-quadratic: t(4n)/t(n) = {bh_ratio:.3} \
1809 ({b1:.1} ms at n={BH_N} -> {b4:.1} ms at n={}), against {quad_ratio:.3} for the \
1810 all-pairs loop the same instrument measured seconds ago. A regression to quadratic \
1811 repulsion above BH_THRESHOLD lands exactly here.",
1812 4 * BH_N
1813 );
1814 }
1815
1816 #[test]
1817 fn hash_color_is_stable() {
1818 assert_eq!(hash_color("Person"), hash_color("Person"));
1819 assert_ne!(hash_color("Person"), hash_color("Company"));
1820 }
1821
1822 /// A minimal facet for deck tests.
1823 struct Stub(&'static str);
1824 impl Facet for Stub {
1825 fn title(&self) -> &str {
1826 self.0
1827 }
1828 fn ui(&mut self, ui: &mut Ui) {
1829 ui.label(self.0);
1830 }
1831 fn state_json(&self) -> serde_json::Value {
1832 serde_json::json!({ "t": self.0 })
1833 }
1834 }
1835
1836 /// A facet whose state counts its own builds (`Cell` — `state_json` takes `&self`).
1837 struct Counted(&'static str, std::rc::Rc<std::cell::Cell<u32>>);
1838 impl Facet for Counted {
1839 fn title(&self) -> &str {
1840 self.0
1841 }
1842 fn ui(&mut self, _ui: &mut Ui) {}
1843 fn state_json(&self) -> serde_json::Value {
1844 self.1.set(self.1.get() + 1);
1845 serde_json::json!({ "t": self.0, "n": self.1.get() })
1846 }
1847 }
1848
1849 /// The page publishes the deck's state every frame: the rolling form builds the
1850 /// active tab every call and ONE inactive tab per call, serves the rest from the
1851 /// cache, keeps `state_json`'s shape, and a newly active tab is fresh at once.
1852 #[test]
1853 fn rolling_state_builds_the_active_tab_and_one_other_per_frame() {
1854 let counts: Vec<_> = (0..5).map(|_| std::rc::Rc::new(std::cell::Cell::new(0u32))).collect();
1855 let names = ["a", "b", "c", "d", "e"];
1856 let mut deck = FacetDeck::new(
1857 names.iter().zip(&counts).map(|(n, c)| Box::new(Counted(n, c.clone())) as Box<dyn Facet>).collect(),
1858 );
1859 let mut cache = DeckStateCache::default();
1860 let first = deck.state_json_rolling(&mut cache);
1861 assert_eq!(cache.built, 5, "the first call builds everything");
1862 let full = deck.state_json();
1863 let keys = |v: &serde_json::Value| v.as_object().unwrap().keys().cloned().collect::<Vec<_>>();
1864 assert_eq!(keys(&first), keys(&full), "same shape as state_json");
1865 assert_eq!(keys(&first["facets"]), keys(&full["facets"]));
1866 FacetDeck::return_rolling(&mut cache, first);
1867 for _ in 0..8 {
1868 let v = deck.state_json_rolling(&mut cache);
1869 FacetDeck::return_rolling(&mut cache, v);
1870 }
1871 // 8 frames: the active tab 8 more times, the four others twice each (one per frame).
1872 assert_eq!(cache.built, 5 + 8 * 2);
1873 let after: Vec<u32> = counts.iter().map(|c| c.get()).collect();
1874 // +1 each for the plain `state_json` above.
1875 assert_eq!(after, vec![1 + 1 + 8, 1 + 1 + 2, 1 + 1 + 2, 1 + 1 + 2, 1 + 1 + 2]);
1876 // A tab made active is built on the very next call.
1877 assert!(deck.set_active_by_title("d"));
1878 let before = counts[3].get();
1879 let v = deck.state_json_rolling(&mut cache);
1880 assert_eq!(counts[3].get(), before + 1);
1881 assert_eq!(v["facets"]["d"]["n"], before + 1, "the active tab's state is this frame's");
1882 assert_eq!(v["active"], "d");
1883 // The spliced serialisation is byte-for-byte serde's, and reuses the text.
1884 let v = deck.state_json_rolling(&mut cache);
1885 let plain = serde_json::to_string(&v).unwrap();
1886 let spliced = FacetDeck::serialize_rolling(&mut cache, serde_json::json!({ "deck": v, "x": 1 }), "/deck");
1887 assert_eq!(spliced, format!("{{\"deck\":{plain},\"x\":1}}"));
1888 let v = deck.state_json_rolling(&mut cache);
1889 let plain = serde_json::to_string(&v).unwrap();
1890 assert_eq!(FacetDeck::serialize_rolling(&mut cache, v, ""), plain, "the deck state itself");
1891 // A host that never hands the map back still gets a whole, correct state.
1892 drop(deck.state_json_rolling(&mut cache));
1893 let built = cache.built;
1894 let w = deck.state_json_rolling(&mut cache);
1895 assert_eq!(cache.built, built + 5, "nothing to serve from: every tab rebuilt");
1896 assert_eq!(keys(&w["facets"]), keys(&full["facets"]));
1897 }
1898
1899 /// A component-clone-capable stub: a `kind`, a JSON `payload` it round-trips
1900 /// through `portable_state`/`load_state`.
1901 struct CloneStub {
1902 kind: &'static str,
1903 payload: serde_json::Value,
1904 }
1905 impl Facet for CloneStub {
1906 fn title(&self) -> &str {
1907 self.kind
1908 }
1909 fn ui(&mut self, _ui: &mut Ui) {}
1910 fn state_json(&self) -> serde_json::Value {
1911 serde_json::json!({ "kind": self.kind })
1912 }
1913 fn kind(&self) -> &'static str {
1914 self.kind
1915 }
1916 fn portable_state(&self) -> Option<serde_json::Value> {
1917 Some(self.payload.clone())
1918 }
1919 fn load_state(&mut self, state: &serde_json::Value) -> bool {
1920 self.payload = state.clone();
1921 true
1922 }
1923 }
1924
1925 /// **The deck reports the DEV-ID gate too.** `facett_app::scene` is korp's container,
1926 /// but facett-demo and the wasm surfaces go through `FacetDeck`, and an oracle asking
1927 /// "are the chips on?" must get the same answer from either. A gate readable from only
1928 /// one of the two containers is exactly the shape of miss #2.
1929 #[test]
1930 fn the_deck_state_reports_the_devid_gate() {
1931 let deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
1932 let gate = deck.state_json()["devid"].clone();
1933 assert!(!gate.is_null(), "the deck's state_json carries no `devid` gate");
1934 assert_eq!(gate["enabled"], devid::enabled(), "deck reports a gate badge() disobeys");
1935 assert_eq!(gate["debug_assertions"], cfg!(debug_assertions), "wrong profile: {gate}");
1936 }
1937
1938 #[test]
1939 fn component_clone_round_trips_through_the_deck() {
1940 // Instance A (configured) → envelope → instance B adopts it.
1941 let a = CloneStub { kind: "graphpan", payload: serde_json::json!({ "zoom": 2.0, "pan": [3, 4] }) };
1942 let deck_a = FacetDeck::new(vec![Box::new(a)]);
1943 let env = deck_a.copy_component_envelope().expect("A copies its portable state");
1944
1945 let mut deck_b = FacetDeck::new(vec![Box::new(CloneStub {
1946 kind: "graphpan",
1947 payload: serde_json::json!({ "zoom": 1.0, "pan": [0, 0] }),
1948 })]);
1949 assert!(deck_b.paste_component(&env, 0.0), "same-kind paste is accepted");
1950 // B now equals A's portable state.
1951 assert_eq!(
1952 deck_b.copy_component_envelope(),
1953 deck_a.copy_component_envelope(),
1954 "B adopted A's portable state exactly"
1955 );
1956 assert!(deck_b.component_toast().is_none(), "a successful paste raises no toast");
1957 }
1958
1959 #[test]
1960 fn component_clone_rejects_a_type_mismatch_with_a_toast() {
1961 // A `table` envelope handed to a `graphpan` → load_state NOT called.
1962 let table_env = clipboard::encode_component("table", &serde_json::json!({ "rows": 3 }));
1963 let mut deck = FacetDeck::new(vec![Box::new(CloneStub {
1964 kind: "graphpan",
1965 payload: serde_json::json!({ "zoom": 1.0 }),
1966 })]);
1967 let before = deck.copy_component_envelope();
1968 assert!(!deck.paste_component(&table_env, 0.0), "cross-type paste returns false");
1969 assert_eq!(deck.copy_component_envelope(), before, "graphpan state untouched");
1970 let toast = deck.component_toast().expect("mismatch raises a toast");
1971 assert!(toast.contains("table") && toast.contains("graphpan"), "toast names both kinds: {toast}");
1972 }
1973
1974 #[test]
1975 fn component_clone_version_guard_rejects_unknown_v() {
1976 let bad = serde_json::json!({ "facett.kind": "graphpan", "v": 7, "state": { "zoom": 9.0 } }).to_string();
1977 let mut deck = FacetDeck::new(vec![Box::new(CloneStub {
1978 kind: "graphpan",
1979 payload: serde_json::json!({ "zoom": 1.0 }),
1980 })]);
1981 let before = deck.copy_component_envelope();
1982 // An unknown-version text decodes to None → it's a no-op (left for the text path).
1983 assert!(!deck.paste_component(&bad, 0.0), "unknown version is not adopted");
1984 assert_eq!(deck.copy_component_envelope(), before, "state untouched by a bad-version paste");
1985 }
1986
1987 #[test]
1988 fn component_clone_opt_out_floor_neither_copies_nor_accepts() {
1989 // The plain Stub does NOT implement the trio → empty kind, no copy.
1990 let mut deck = FacetDeck::new(vec![Box::new(Stub("plain"))]);
1991 assert_eq!(deck.active_kind(), "", "opted out");
1992 assert!(deck.copy_component_envelope().is_none(), "opt-out facet never copies a component");
1993 // A real envelope handed to an opt-out facet is refused (no panic, no state).
1994 let env = clipboard::encode_component("table", &serde_json::json!({ "rows": 1 }));
1995 assert!(!deck.paste_component(&env, 0.0), "opt-out facet never adopts a component");
1996 assert!(deck.component_toast().is_some(), "the refusal is surfaced");
1997 }
1998
1999 #[test]
2000 fn deck_fx_is_off_by_default() {
2001 let deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
2002 assert_eq!(*deck.fx(), DeckFx::OFF, "no effects until the host opts in");
2003 assert!(!deck.has_raven());
2004 assert!(!deck.fx().glow);
2005 assert!(deck.fx().palette().is_none());
2006 }
2007
2008 #[test]
2009 fn deck_state_json_reports_fx_as_data() {
2010 // The deck's opt-in effects must be observable as data (a robot proof reads
2011 // `fx.chrome` / `fx.glow` to know the showcase rendering is wired ON).
2012 let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
2013 let off = deck.state_json();
2014 assert_eq!(off["fx"]["chrome"].as_bool(), Some(false), "chrome off by default");
2015 assert_eq!(off["fx"]["glow"].as_bool(), Some(false), "glow off by default");
2016 assert!(off["fx"]["palette"].is_null(), "no palette override by default");
2017
2018 deck.fx_mut().chrome = true;
2019 deck.fx_mut().glow = true;
2020 deck.set_palette(2);
2021 let on = deck.state_json();
2022 assert_eq!(on["fx"]["chrome"].as_bool(), Some(true), "chrome wired ON shows in state");
2023 assert_eq!(on["fx"]["glow"].as_bool(), Some(true), "glow wired ON shows in state");
2024 assert_eq!(on["fx"]["palette"].as_u64(), Some(2), "palette override shows in state");
2025 }
2026
2027 #[test]
2028 fn deck_cycle_palette_walks_theme_all() {
2029 let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
2030 let first = deck.cycle_palette();
2031 assert_eq!(first, 0);
2032 assert_eq!(deck.fx().theme().map(|t| t.name), Some(Theme::ALL[0]().name));
2033 // walks forward and wraps
2034 for _ in 1..Theme::ALL.len() {
2035 deck.cycle_palette();
2036 }
2037 assert_eq!(deck.cycle_palette(), 0, "wraps back to the first palette");
2038 }
2039
2040 #[test]
2041 fn deck_send_raven_launches_and_perches_after_a_full_flight() {
2042 use crate::effects::RAVEN_FLIGHT_SECS;
2043 let mut deck = FacetDeck::new(vec![Box::new(Stub("rows"))]);
2044 assert!(!deck.has_raven());
2045 let target = egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(200.0, 28.0));
2046 deck.send_raven(target);
2047 assert!(deck.has_raven(), "raven summoned");
2048 assert!(!deck.raven_perched(), "not perched at launch");
2049
2050 // Drive the sprite headlessly past the flight duration → it perches.
2051 if let Some(r) = deck.raven.as_mut() {
2052 r.sprite.advance(RAVEN_FLIGHT_SECS + 0.1);
2053 }
2054 assert!(deck.raven_perched(), "perched after the flight duration");
2055
2056 deck.clear_raven();
2057 assert!(!deck.has_raven());
2058 }
2059
2060 /// REGRESSION (inject-assert): merely *drawing* the palette picker without a
2061 /// user click must NOT pin a palette override. The bug: the picker auto-pinned
2062 /// index 0 on the first passive frame, turning the legacy `set_theme` override
2063 /// permanently on and clobbering a host's own theme (the rich `look::Theme`)
2064 /// every frame. We render one frame with no interaction and assert the override
2065 /// is still `None` (host theme wins).
2066 #[test]
2067 fn palette_picker_does_not_pin_without_a_user_click() {
2068 let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
2069 assert!(deck.fx().palette().is_none(), "starts with no override");
2070 let ctx = egui::Context::default();
2071 let mut chosen = Some(7usize);
2072 ctx.run_ui(egui::RawInput::default(), |ui| {
2073 egui::CentralPanel::default().show(ui, |ui| {
2074 // No synthetic click is fed → the picker is drawn but not used.
2075 chosen = deck.palette_picker(ui);
2076 });
2077 }).textures_delta.clear();
2078 assert_eq!(chosen, None, "drawing the picker reports no selection without a click");
2079 assert!(
2080 deck.fx().palette().is_none(),
2081 "drawing the picker must not pin index 0 — that would clobber the host's own theme each frame"
2082 );
2083 }
2084
2085 #[test]
2086 fn deck_palette_override_applies_theme_in_a_ui_pass() {
2087 let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
2088 deck.set_palette(1); // sci-fi
2089 let ctx = egui::Context::default();
2090 let mut seen = "";
2091 ctx.run_ui(egui::RawInput::default(), |ui| {
2092 egui::CentralPanel::default().show(ui, |ui| {
2093 deck.ui(ui);
2094 seen = theme(ui).name;
2095 });
2096 }).textures_delta.clear();
2097 assert_eq!(seen, Theme::ALL[1]().name, "deck applied its palette override");
2098 }
2099
2100 // ── tab groups (the two-level bar) ─────────────────────────────────────────
2101
2102 fn grouped_deck() -> FacetDeck {
2103 FacetDeck::new(vec![
2104 Box::new(Stub("graph")),
2105 Box::new(Stub("grid")),
2106 Box::new(Stub("Graphs")),
2107 Box::new(Stub("map")),
2108 Box::new(Stub("loose")),
2109 ])
2110 .with_groups(&[("Grafer", &["Graphs", "graph", "not-here"]), ("Kartor", &["map"]), ("Tom", &[])], "Övrigt")
2111 }
2112
2113 #[test]
2114 fn every_facet_lands_in_exactly_one_group_in_deck_order() {
2115 let deck = grouped_deck();
2116 let names: Vec<&str> = deck.groups().iter().map(|g| g.name.as_str()).collect();
2117 // The empty group is dropped; the unlisted facets fall into the rest group.
2118 assert_eq!(names, ["Grafer", "Kartor", "Övrigt"]);
2119 assert_eq!(deck.groups()[0].members, vec![0, 2], "deck order, not list order; unknown titles skipped");
2120 assert_eq!(deck.groups()[2].members, vec![1, 4], "grid + loose are orphans");
2121 let mut all: Vec<usize> = deck.groups().iter().flat_map(|g| g.members.clone()).collect();
2122 all.sort_unstable();
2123 assert_eq!(all, (0..deck.len()).collect::<Vec<_>>(), "each facet once");
2124 }
2125
2126 #[test]
2127 fn the_active_group_follows_the_active_tab_and_remembers_its_entry() {
2128 let mut deck = grouped_deck();
2129 assert_eq!(deck.active_group_name(), Some("Grafer"));
2130 // A programmatic switch (deep link / tour) moves the group with it.
2131 assert!(deck.set_active_by_title("map"));
2132 assert_eq!(deck.active_group_name(), Some("Kartor"));
2133 // Entering a group opens its first member the first time …
2134 assert!(deck.set_active_group("Övrigt"));
2135 assert_eq!(deck.active_title(), Some("grid"));
2136 assert!(deck.set_active_by_title("loose"));
2137 // … and the last shown member when re-entered (the bar notes it while drawing).
2138 let ctx = egui::Context::default();
2139 ctx.run_ui(egui::RawInput::default(), |ui| {
2140 egui::CentralPanel::default().show(ui, |ui| deck.ui(ui));
2141 }).textures_delta.clear();
2142 assert!(deck.set_active_group("Grafer"));
2143 assert!(deck.set_active_group("Övrigt"));
2144 assert_eq!(deck.active_title(), Some("loose"));
2145 assert!(!deck.set_active_group("nope"));
2146 let j = deck.state_json();
2147 assert_eq!(j["menu"]["group"], "Övrigt");
2148 assert_eq!(j["menu"]["groups"].as_array().unwrap().len(), 3);
2149 }
2150
2151 #[test]
2152 fn an_ungrouped_deck_keeps_the_flat_strip() {
2153 let deck = FacetDeck::new(vec![Box::new(Stub("a")), Box::new(Stub("b"))]);
2154 assert!(deck.groups().is_empty());
2155 assert_eq!(deck.active_group_name(), None);
2156 assert_eq!(deck.state_json()["menu"]["groups"], serde_json::json!([]));
2157 }
2158}