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 shared **action bus** (BUS-1) — a typed, deterministic outbox facets use
11/// to hand side work (a drag move, a time-scrub, a command) to the host. The
12/// common carrier [`dragdrop`] / [`time_axis`] `Effect`s flow through.
13pub mod action_bus;
14pub mod caps;
15pub mod chrome;
16pub mod clip;
17pub mod clipboard;
18pub mod deckfx;
19/// The shared **drag-and-drop** primitive (DND-1) — the one reducer behind
20/// items-dragged-onto-zones (cards→columns, bars→lanes). Engine-agnostic sibling
21/// of [`nav::Navigable`]; the caps flag [`FacetCaps::draggable`] points here.
22pub mod dragdrop;
23pub mod edges;
24pub mod effects;
25/// The canonical **Elm contract** (FC-2 / FC-9) — the [`Elm`] trait +
26/// [`impl_facet_via_elm!`] bridge macro that lift `facett-security`'s hand-rolled
27/// Model/Msg/Effect/pure-view pattern into reusable infra. Pair with
28/// [`harness`] to drive an `Elm` component headlessly.
29pub mod elm;
30pub mod focus;
31pub mod imgscan; // image-analysis oracle (SCAN-THE-PIXELS law): spoke/high-freq/
32 // coverage/centroid features computed FROM the rendered pixels.
33pub mod labels3d;
34pub mod harness;
35pub mod look;
36pub mod nav;
37pub mod overlay;
38pub mod rabbit;
39/// The L0 shared render kernel (CONS-CORE) — shared `Camera`, z-ordered
40/// `LayerStack`, the CPU rect scissor, and (feature `wgpu`) the extracted GPU
41/// scaffold. Map skins + `facett-graphview` draw through this.
42pub mod render;
43pub mod runtrace; // in-memory, wasm-safe "what RAN" ledger (no FS) — folded into
44 // state_json["trace"]["ran"], read via the JS hook on wasm.
45pub mod scroll_engine;
46pub mod testmatrix; // functional-status → nornir test-matrix bridge (feature
47 // `testmatrix`); no-op in release.
48pub mod theme;
49/// The shared **pan/zoom-in-time axis** (TIME-1) — the one time-window model
50/// behind gantt/CFD/calendar/timeline, linkable across facets. Temporal sibling
51/// of [`nav::Navigable`]; the caps flag [`FacetCaps::time_scrollable`] points here.
52pub mod time_axis;
53pub mod trace; // structured IN/OUT/END event stream ($FACETT_TRACE) — the
54 // machine-readable data a facet actually rendered.
55pub use a11y::{Semantics, node as a11y_node, stable_id};
56pub use action_bus::{ActionBus, BusAction, BusMsg};
57pub use caps::FacetCaps;
58pub use dragdrop::{DragDrop, DragEffect, DragMsg, Move as DragMove};
59pub use clip::{ArrowColumnRef, ClipKind, ClipPayload, CopySource, PasteTarget};
60pub use clipboard::ClipAction;
61pub use deckfx::{DeckFx, DeckRaven};
62pub use elm::Elm;
63pub use imgscan::{BBox, Rgba, ScanReport, coverage, high_freq_ratio, painted_centroid_and_bbox, scan, spoke_score};
64pub use look::{Action, KeyMap, Palette};
65pub use nav::{Dir4, Navigable, nearest_in_direction};
66pub use rabbit::{Rabbit, RabbitMesh, rabbit_mesh, rabbit_outline};
67pub use scroll_engine::SmoothScroll;
68pub use theme::{Theme, set_theme, theme};
69pub use time_axis::{TimeAxis, TimeEffect, TimeMsg};
70
71// The rich look-&-feel `Theme` (the work-order architecture) is re-exported under
72// an unambiguous alias so it coexists with the legacy flat palette `Theme` above.
73pub use look::Theme as LookTheme;
74
75/// A node: a label + a colour (the *consumer* picks the colour policy — hash by
76/// label, by status, …).
77#[derive(Clone)]
78pub struct Node {
79 pub label: String,
80 pub color: Color32,
81}
82
83/// A directed edge between node indices.
84#[derive(Clone, Copy)]
85pub struct Edge {
86 pub src: usize,
87 pub dst: usize,
88}
89
90/// A drawable graph: nodes + edges (edges index into `nodes`).
91#[derive(Default, Clone)]
92pub struct Scene {
93 pub nodes: Vec<Node>,
94 pub edges: Vec<Edge>,
95}
96
97impl Scene {
98 pub fn new() -> Self {
99 Self::default()
100 }
101 /// Push a node, returning its index.
102 pub fn node(&mut self, label: impl Into<String>, color: Color32) -> usize {
103 self.nodes.push(Node { label: label.into(), color });
104 self.nodes.len() - 1
105 }
106 pub fn edge(&mut self, src: usize, dst: usize) {
107 self.edges.push(Edge { src, dst });
108 }
109 pub fn is_empty(&self) -> bool {
110 self.nodes.is_empty()
111 }
112}
113
114/// Node placement strategy.
115#[derive(Clone, Copy, PartialEq, Eq, Default)]
116pub enum Layout {
117 #[default]
118 Circular,
119 /// Deterministic Fruchterman–Reingold (edges pull, all nodes repel). O(n²)
120 /// per iteration — best for small/medium graphs.
121 Force,
122}
123
124/// Draw a `Scene` into `ui` — the reusable render primitive. Empty scenes show
125/// `empty_hint`. Labels render when the node count is small enough to read.
126pub fn draw(ui: &mut Ui, scene: &Scene, layout: Layout, empty_hint: &str) {
127 let (rect, _) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
128 let th = theme(ui);
129 let painter = ui.painter_at(rect);
130 let n = scene.nodes.len();
131 if n == 0 {
132 painter.text(rect.center(), Align2::CENTER_CENTER, empty_hint, FontId::proportional(13.0), th.text_dim);
133 return;
134 }
135 let pos = positions(layout, scene, rect);
136 for e in &scene.edges {
137 if e.src < n && e.dst < n {
138 painter.line_segment([pos[e.src], pos[e.dst]], Stroke::new(0.6, th.edge));
139 }
140 }
141 for (i, node) in scene.nodes.iter().enumerate() {
142 painter.circle_filled(pos[i], 5.0, node.color);
143 }
144 if n <= 60 {
145 for (i, node) in scene.nodes.iter().enumerate() {
146 painter.text(pos[i] + vec2(7.0, 0.0), Align2::LEFT_CENTER, &node.label, FontId::proportional(10.0), th.text);
147 }
148 }
149}
150
151/// **Test/host hook (additive).** The public, return-asserted view of the
152/// private [`positions`] layout node — the exact node centres [`draw`] paints for
153/// `scene` under `layout` inside `rect`. Exposed so the graph-skin call-chain
154/// matrix can assert the *layout* stage (finite, in-rect, count == nodes,
155/// circular radius, force-fit normalisation) without a painter. Calls the **same**
156/// private fn `draw` uses, so it IS the layout the pixels come from — additive,
157/// no behaviour change.
158pub fn layout_positions(layout: Layout, scene: &Scene, rect: Rect) -> Vec<Pos2> {
159 positions(layout, scene, rect)
160}
161
162fn positions(layout: Layout, scene: &Scene, rect: Rect) -> Vec<Pos2> {
163 let n = scene.nodes.len();
164 let center = rect.center();
165 let radius = rect.size().min_elem() * 0.42;
166 let circular = |i: usize| {
167 let a = std::f32::consts::TAU * (i as f32) / (n as f32);
168 vec2(a.cos(), a.sin())
169 };
170 match layout {
171 Layout::Circular => (0..n).map(|i| center + radius * circular(i)).collect(),
172 Layout::Force => {
173 // Deterministic Fruchterman–Reingold from a circular seed (unit space).
174 let mut p: Vec<egui::Vec2> = (0..n).map(circular).collect();
175 let k = (1.0 / (n.max(1) as f32).sqrt()).clamp(0.05, 1.0);
176 for _ in 0..120 {
177 let mut disp = vec![egui::Vec2::ZERO; n];
178 for i in 0..n {
179 for j in (i + 1)..n {
180 let d = p[i] - p[j];
181 let dist = d.length().max(1e-3);
182 let f = k * k / dist;
183 let dir = d / dist;
184 disp[i] += dir * f;
185 disp[j] -= dir * f;
186 }
187 }
188 for e in &scene.edges {
189 if e.src < n && e.dst < n {
190 let d = p[e.src] - p[e.dst];
191 let dist = d.length().max(1e-3);
192 let f = dist * dist / k;
193 let dir = d / dist;
194 disp[e.src] -= dir * f;
195 disp[e.dst] += dir * f;
196 }
197 }
198 for i in 0..n {
199 let dl = disp[i].length().max(1e-3);
200 p[i] += disp[i] / dl * dl.min(0.04); // capped step (cooling-free, deterministic)
201 }
202 }
203 // Normalise to fit the rect.
204 let (mut mn, mut mx) = (egui::vec2(f32::MAX, f32::MAX), egui::vec2(f32::MIN, f32::MIN));
205 for v in &p {
206 mn.x = mn.x.min(v.x);
207 mn.y = mn.y.min(v.y);
208 mx.x = mx.x.max(v.x);
209 mx.y = mx.y.max(v.y);
210 }
211 let span = (mx - mn).max(egui::vec2(1e-3, 1e-3));
212 p.iter()
213 .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))
214 .collect()
215 }
216 }
217}
218
219/// The facett **component contract**. Every facet — graph, map, pipeline, table,
220/// the ported nornir viewers — implements this, so consumers (korp, nornir, …)
221/// compose them uniformly *and* get headless robot-testing for free.
222///
223/// The three things a component owes its host:
224/// 1. a **title** (tab label / panel heading),
225/// 2. how to **draw** itself into egui,
226/// 3. its **observable state** as JSON — dumped to `$APP_STATE` for headless
227/// assertions. **Rule:** every visible list/status/count goes in `state_json`.
228pub trait Facet {
229 fn title(&self) -> &str;
230 fn ui(&mut self, ui: &mut Ui);
231 fn state_json(&self) -> serde_json::Value;
232
233 // --- uniform capability surface (all defaulted; see caps.rs / clipboard.rs) ---
234
235 /// What this facet can do. Override to opt into capabilities.
236 fn caps(&self) -> FacetCaps {
237 FacetCaps::NONE
238 }
239
240 /// Current uniform scale (1.0 = native). Override if `caps().scalable`.
241 fn scale(&self) -> f32 {
242 1.0
243 }
244 /// Set the uniform scale; clamp internally. Default no-op (not scalable).
245 fn set_scale(&mut self, _scale: f32) {}
246
247 /// The current selection as JSON (also folded into `state_json` by
248 /// convention). `Null` when nothing/none selectable.
249 fn selection_json(&self) -> serde_json::Value {
250 serde_json::Value::Null
251 }
252
253 /// Clipboard hooks — see clipboard.rs. Defaults: nothing to give/take.
254 /// Returns the text to place on the clipboard (None = nothing copyable now).
255 fn copy(&mut self) -> Option<String> {
256 None
257 }
258 /// Like `copy`, but also removes the selection. Default delegates to `copy`.
259 fn cut(&mut self) -> Option<String> {
260 self.copy()
261 }
262 /// Accept pasted text. Returns true if consumed.
263 fn paste(&mut self, _text: &str) -> bool {
264 false
265 }
266
267 /// Optional downcast handle for hosts that need typed access to a specific
268 /// facet living inside a [`FacetDeck`] (e.g. a robot-UI driver clicking an
269 /// app-level control that must forward to a concrete component's own API).
270 /// Defaulted to `None` so no existing facet has to change; a component opts in
271 /// by returning `Some(self)`.
272 fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
273 None
274 }
275
276 // --- cross-instance state clone (copy/paste BETWEEN same-component instances) ---
277 // See `.nornir/design/copy-paste-between-instances.md` + `clipboard.rs`. The trio
278 // below is the type-tagged STATE layer on top of the text clipboard: two
279 // instances with the SAME `kind()` exchange `portable_state()` via the OS
280 // clipboard envelope (`clipboard::encode_component`/`decode_component`). Each is
281 // defaulted to the opt-OUT floor — a component that doesn't implement all three
282 // neither copies nor accepts cross-instance state, and nothing panics.
283
284 /// Stable component-type id (e.g. `"jobview"`, `"graphpan"`, `"table"`). Two
285 /// instances with the **same** kind can exchange portable state; the empty
286 /// default `""` means **opted out** of cross-instance clone.
287 fn kind(&self) -> &'static str {
288 ""
289 }
290
291 /// The **portable** subset of this facet's state — the fields a same-kind
292 /// sibling can adopt. `None` = not cloneable. Kept SEPARATE from
293 /// [`state_json`](Self::state_json) (the introspection dump, which may carry
294 /// derived / render-only data) so this stays round-trippable through
295 /// [`load_state`](Self::load_state).
296 fn portable_state(&self) -> Option<serde_json::Value> {
297 None
298 }
299
300 /// Adopt a portable state produced by [`portable_state`](Self::portable_state)
301 /// on a same-kind sibling. Returns `true` if accepted. Default `false`
302 /// (opt-in per component).
303 fn load_state(&mut self, _state: &serde_json::Value) -> bool {
304 false
305 }
306}
307
308/// A tabbed set of [`Facet`]s — the reusable multi-component shell. Draws a tab
309/// bar + the active facet, and composes **every** facet's `state_json` under its
310/// title, so the whole-app introspection contract is free. korp/nornir can build
311/// their window from a `FacetDeck` instead of hand-rolling tabs + the state dump.
312pub struct FacetDeck {
313 facets: Vec<Box<dyn Facet>>,
314 active: usize,
315 /// Opt-in deck effects (palette override + glow). `Default` = all off, so a
316 /// deck that never opts in is unchanged and pays nothing.
317 fx: DeckFx,
318 /// A raven summoned through the deck, in flight or perched (or `None`).
319 raven: Option<DeckRaven>,
320 /// A transient, themed component-clone toast (message + the `ctx.input.time`
321 /// it was raised at), shown briefly after a Copy-/Paste-component gesture —
322 /// chiefly the type-mismatch rejection ("clipboard holds a `table`, not a
323 /// `graphpan`"). `None` = nothing to show. See [`Self::component_toast`].
324 toast: Option<(String, f64)>,
325}
326
327/// How long a component-clone [`toast`](FacetDeck::toast) stays on screen.
328const TOAST_SECS: f64 = 2.6;
329
330impl FacetDeck {
331 pub fn new(facets: Vec<Box<dyn Facet>>) -> Self {
332 Self { facets, active: 0, fx: DeckFx::OFF, raven: None, toast: None }
333 }
334 /// Append a facet (the incremental form of [`new`](Self::new)). Lets a host
335 /// build a deck pane-by-pane as it discovers what to show (e.g. one pane per
336 /// warehouse table it finds).
337 pub fn push(&mut self, facet: Box<dyn Facet>) {
338 self.facets.push(facet);
339 }
340 pub fn active(&self) -> usize {
341 self.active
342 }
343
344 /// The title of the currently-active facet (the deck's `state_json["active"]`),
345 /// or `None` if the deck is empty.
346 pub fn active_title(&self) -> Option<&str> {
347 self.facets.get(self.active).map(|f| f.title())
348 }
349
350 /// The titles of every tabbed facet, in tab order — the discoverable surface a
351 /// host (or a robot-UI control channel) enumerates to know which tabs exist.
352 pub fn titles(&self) -> Vec<&str> {
353 self.facets.iter().map(|f| f.title()).collect()
354 }
355
356 /// Make the facet titled `title` the active tab — the programmatic (headless,
357 /// robot-addressable) equivalent of clicking its tab header. Returns `true` if a
358 /// facet with that title exists (and is now active), `false` otherwise. This is
359 /// the named boundary a control channel switches tabs through (the deck analogue
360 /// of the viz's `Tab::from_name`), so a driver needn't replay a pointer click.
361 pub fn set_active_by_title(&mut self, title: &str) -> bool {
362 match self.facets.iter().position(|f| f.title() == title) {
363 Some(i) => {
364 self.active = i;
365 true
366 }
367 None => false,
368 }
369 }
370
371 /// Typed mutable access to the facet with `title`, downcast to `T` — `None` if
372 /// no such facet, or it doesn't opt into [`Facet::as_any_mut`], or the type
373 /// mismatches. Lets a host drive a concrete component's own API (e.g. a
374 /// robot-UI control forwarding a node selection to a `SystemChart`).
375 pub fn facet_mut<T: std::any::Any>(&mut self, title: &str) -> Option<&mut T> {
376 self.facets
377 .iter_mut()
378 .find(|f| f.title() == title)
379 .and_then(|f| f.as_any_mut())
380 .and_then(|a| a.downcast_mut::<T>())
381 }
382
383 /// Replace the facet whose `title` matches with `facet` (the box's own title is
384 /// what the deck enumerates afterwards). Returns `true` if a facet was replaced.
385 /// Used by hosts that **reload** a tab's data in place — e.g. the OSM region
386 /// picker rebuilds the `OSM 2D` / `OSM 3D` views from a freshly clipped region
387 /// and swaps them in, keeping the same tab slots (and the active selection).
388 pub fn replace_facet(&mut self, title: &str, facet: Box<dyn Facet>) -> bool {
389 if let Some(slot) = self.facets.iter_mut().find(|f| f.title() == title) {
390 *slot = facet;
391 true
392 } else {
393 false
394 }
395 }
396
397 // ── opt-in effects + theming (see deckfx.rs) ─────────────────────────────
398
399 /// Enable deck effects up front (builder form of [`fx_mut`](Self::fx_mut)).
400 pub fn with_fx(mut self, fx: DeckFx) -> Self {
401 self.fx = fx;
402 self
403 }
404 /// The current deck-effects config (read-only).
405 pub fn fx(&self) -> &DeckFx {
406 &self.fx
407 }
408 /// Mutate the deck-effects config (toggle glow, pin a palette, …).
409 pub fn fx_mut(&mut self) -> &mut DeckFx {
410 &mut self.fx
411 }
412 /// Override the deck theme with palette index `i` (wraps); enables the
413 /// override. Convenience over `fx_mut().set_palette(i)`.
414 pub fn set_palette(&mut self, i: usize) {
415 self.fx.set_palette(i);
416 }
417 /// Advance to the next palette in [`Theme::ALL`] (wrapping); returns the new
418 /// index. Convenience over `fx_mut().cycle_palette()`.
419 pub fn cycle_palette(&mut self) -> usize {
420 self.fx.cycle_palette()
421 }
422
423 /// **Summon the raven** to perch on `target` — any rect a facet/host hands us
424 /// (a table row, a node, a header). Replaces any raven already in flight. The
425 /// body is tinted from the deck's current palette (or the host theme). Logs an
426 /// activity trail entry. Drive/paint happens automatically inside
427 /// [`ui`](Self::ui).
428 pub fn send_raven(&mut self, target: Rect) {
429 let theme = self.effective_theme();
430 self.raven = Some(DeckRaven::new(target, &theme));
431 harness::trail(
432 harness::Kind::Render,
433 format!("raven launched → perch ({:.0},{:.0})", target.center().x, target.top()),
434 );
435 }
436 /// True while a raven is present (flying or perched).
437 pub fn has_raven(&self) -> bool {
438 self.raven.is_some()
439 }
440 /// True once the summoned raven has landed (false if none).
441 pub fn raven_perched(&self) -> bool {
442 self.raven.as_ref().map(|r| r.is_perched()).unwrap_or(false)
443 }
444 /// Dismiss any raven.
445 pub fn clear_raven(&mut self) {
446 self.raven = None;
447 }
448
449 /// The theme the deck paints with: the fx palette override if set, else
450 /// [`Theme::default`] (the host's own `set_theme` still applies its visuals;
451 /// this is just the colour source for deck-owned effects/picker).
452 fn effective_theme(&self) -> Theme {
453 self.fx.theme().unwrap_or_default()
454 }
455
456 /// Draw a one-line **palette picker** — a switcher over [`Theme::ALL`] the
457 /// host can place anywhere (toolbar, menu). Selecting a palette pins the fx
458 /// override; `ui()` then applies it each frame. Returns the chosen index if it
459 /// changed this frame.
460 ///
461 /// The override stays **off until the user actually clicks** a palette: merely
462 /// drawing the picker must not pin index 0, otherwise a host that drives its
463 /// own theme (e.g. the rich [`crate::look::Theme`]) would be silently clobbered
464 /// every frame by the legacy `set_theme` in [`ui`](Self::ui) — size still
465 /// changing (spacing) but colour frozen on `Theme::ALL[0]`. So we only pin when
466 /// the selection genuinely changed this frame.
467 pub fn palette_picker(&mut self, ui: &mut Ui) -> Option<usize> {
468 let mut sel = self.fx.palette().unwrap_or(0);
469 let before = sel;
470 ui.horizontal_wrapped(|ui| {
471 ui.label("Palette:");
472 for (i, ctor) in Theme::ALL.iter().enumerate() {
473 ui.selectable_value(&mut sel, i, ctor().name);
474 }
475 });
476 if sel != before {
477 self.fx.set_palette(sel);
478 }
479 (sel != before).then_some(sel)
480 }
481
482 /// The capabilities of the currently-active facet (or `NONE` if empty).
483 pub fn active_caps(&self) -> FacetCaps {
484 self.facets.get(self.active).map(|f| f.caps()).unwrap_or(FacetCaps::NONE)
485 }
486
487 /// Number of facets in the deck.
488 pub fn len(&self) -> usize {
489 self.facets.len()
490 }
491 /// True when the deck holds no facets.
492 pub fn is_empty(&self) -> bool {
493 self.facets.is_empty()
494 }
495
496 /// **Wall layout** — render **every** facet at once in a wrapping grid of
497 /// `cols` columns, instead of the tabbed one-at-a-time [`ui`](Self::ui). This is
498 /// the "multiple components visible simultaneously" mode a dashboard host wants
499 /// (e.g. several `Graph3D` panes side-by-side). Each cell is a titled group; the
500 /// fx palette override (if set) still applies, and every rendered facet is logged
501 /// to the runtrace ledger keyed `deck.wall:<title>` (mirrors the tab path's
502 /// `deck.render:<title>`), so `state_json`'s `trace.ran` proves each pane drew.
503 pub fn wall_ui(&mut self, ui: &mut Ui, cols: usize) {
504 if let Some(theme) = self.fx.theme() {
505 set_theme(ui.ctx(), theme);
506 }
507 if self.facets.is_empty() {
508 ui.weak("empty deck");
509 return;
510 }
511 let cols = cols.max(1);
512 let spacing = ui.spacing().item_spacing.x;
513 let total_w = ui.available_width();
514 let cell_w = ((total_w - spacing * (cols as f32 - 1.0)) / cols as f32).max(160.0);
515 // A generous cell so 3D graphs have room; the inner facet fills it.
516 let cell_h = 300.0_f32;
517 egui::ScrollArea::vertical()
518 .auto_shrink([false; 2])
519 .show(ui, |ui| {
520 ui.horizontal_wrapped(|ui| {
521 for f in self.facets.iter_mut() {
522 ui.allocate_ui(egui::vec2(cell_w, cell_h), |ui| {
523 ui.group(|ui| {
524 ui.set_min_size(egui::vec2(cell_w - 12.0, cell_h - 12.0));
525 ui.vertical(|ui| {
526 ui.strong(f.title());
527 ui.separator();
528 runtrace::ran(&format!("deck.wall:{}", f.title()));
529 f.ui(ui);
530 });
531 });
532 });
533 }
534 });
535 });
536 }
537
538 /// The active facet's current scale (1.0 if none / not scalable).
539 fn active_scale(&self) -> f32 {
540 self.facets.get(self.active).map(|f| f.scale()).unwrap_or(1.0)
541 }
542
543 /// Multiply the active facet's scale by `k`, clamped to a sane range.
544 fn scale_active(&mut self, k: f32) {
545 if let Some(f) = self.facets.get_mut(self.active) {
546 let s = (f.scale() * k).clamp(0.25, 4.0);
547 f.set_scale(s);
548 }
549 }
550
551 /// Reset the active facet's scale to native.
552 fn reset_scale(&mut self) {
553 if let Some(f) = self.facets.get_mut(self.active) {
554 f.set_scale(1.0);
555 }
556 }
557
558 /// Draw the tab bar + capability toolbar + the active facet, and route
559 /// capability-gated shortcuts (Ctrl-+/-/0 for scale; Ctrl-C/X/V for clipboard).
560 pub fn ui(&mut self, ui: &mut Ui) {
561 // Opt-in palette override: apply the chosen Theme::ALL palette + its
562 // egui Visuals each frame so the whole deck (and every facet that reads
563 // `theme(ui)`) follows. No override → the host's own theme stays.
564 if let Some(theme) = self.fx.theme() {
565 set_theme(ui.ctx(), theme);
566 }
567
568 let titles: Vec<String> = self.facets.iter().map(|f| f.title().to_string()).collect();
569 // Wrap the tab bar: with many facets a single non-wrapping row overflows
570 // the panel width and the trailing tabs become unreachable (off-screen,
571 // unclickable for a robot driver / pointer). Wrapping keeps every tab
572 // visible + clickable no matter how many facets the deck holds.
573 ui.horizontal_wrapped(|ui| {
574 for (i, t) in titles.iter().enumerate() {
575 ui.selectable_value(&mut self.active, i, t);
576 }
577 });
578
579 let caps = self.active_caps();
580
581 // Capability-driven toolbar: only show controls the active facet honors.
582 if caps.scalable {
583 ui.horizontal(|ui| {
584 if ui.button("−").on_hover_text("Zoom out (Ctrl-−)").clicked() {
585 self.scale_active(1.0 / 1.1);
586 }
587 ui.label(format!("{:.0}%", self.active_scale() * 100.0));
588 if ui.button("+").on_hover_text("Zoom in (Ctrl-+)").clicked() {
589 self.scale_active(1.1);
590 }
591 if ui.button("Reset").on_hover_text("Reset zoom (Ctrl-0)").clicked() {
592 self.reset_scale();
593 }
594 });
595 }
596
597 // Capability-gated scale shortcuts. egui has no semantic event for these,
598 // so we hand-detect the key combos (clipboard uses semantic events below).
599 if caps.scalable {
600 let (cmd, plus, minus, zero) = ui.input(|i| {
601 (
602 i.modifiers.command,
603 i.key_pressed(egui::Key::Plus) || i.key_pressed(egui::Key::Equals),
604 i.key_pressed(egui::Key::Minus),
605 i.key_pressed(egui::Key::Num0),
606 )
607 });
608 if cmd {
609 if plus {
610 self.scale_active(1.1);
611 }
612 if minus {
613 self.scale_active(1.0 / 1.1);
614 }
615 if zero {
616 self.reset_scale();
617 }
618 }
619 }
620
621 // Clipboard routing: drain semantic events and dispatch to the active
622 // facet, gated by its caps. A focused TextEdit already consumed its own.
623 self.route_clipboard(ui.ctx());
624
625 // Cross-instance component clone (DISTINCT gesture): the Ctrl+Shift+C/V
626 // accelerators + any pending envelope paste, drained the same frame.
627 self.route_component_clipboard(ui);
628
629 ui.separator();
630 // Optionally wrap the active facet in the shared glass/card chrome
631 // (`chrome` module), gated by the active EffectsPolicy. Reserve a paint slot
632 // BEFORE the content so the glass fill sits behind it; the glow + border
633 // edge is painted on top afterwards.
634 let chrome_on = self.fx.chrome;
635 let chrome_slot = chrome_on.then(|| ui.painter().add(egui::Shape::Noop));
636 // Render the active facet, capturing the rect it occupied so the deck can
637 // bloom it (opt-in glow) without the facet knowing.
638 let content = ui.scope(|ui| {
639 if let Some(f) = self.facets.get_mut(self.active) {
640 // Render-trace: this facet's `ui()` RAN this frame (the wasm-safe
641 // "what ran" ledger — folded into state_json, read via the JS hook
642 // on wasm). Keyed by tab title so the ran-list maps tab → ran?.
643 runtrace::ran(&format!("deck.render:{}", f.title()));
644 f.ui(ui);
645 }
646 });
647 let content_rect = content.response.rect;
648
649 // Paint the card chrome around the facet's content rect.
650 if let Some(slot) = chrome_slot
651 && content_rect.is_positive()
652 {
653 let theme = self.effective_theme();
654 let policy = crate::look::effects_policy(ui);
655 let style = chrome::ChromeStyle::default().for_policy(policy);
656 let card = content_rect.expand(6.0);
657 ui.painter().set(slot, chrome::fill_shape(card, &theme, policy, style));
658 chrome::edge(ui.painter(), card, &theme, policy, style);
659 }
660
661 // Right-click the active facet body → the Copy/Paste-component menu (the
662 // discoverable affordance for the cross-instance clone gesture). The
663 // text clipboard's own copy/paste is unaffected (different gesture).
664 if !self.active_kind().is_empty() {
665 content.response.context_menu(|ui| self.component_menu(ui));
666 }
667
668 // Opt-in glow on the active facet's content rect, pulsing.
669 if self.fx.glow && content_rect.is_positive() {
670 let theme = self.effective_theme();
671 let time = ui.input(|i| i.time);
672 let painter = ui.painter_at(content_rect);
673 deckfx::paint_active_glow(&painter, content_rect.shrink(2.0), &theme, &self.fx, time);
674 ui.ctx().request_repaint(); // keep the pulse animating
675 }
676
677 // Drive + paint a summoned raven on a foreground layer above everything.
678 self.drive_raven(ui.ctx());
679
680 // Paint the component-clone toast (mismatch / rejection feedback) on top.
681 self.paint_component_toast(ui);
682 }
683
684 /// Advance + paint the summoned raven (if any) on a foreground layer. Pins its
685 /// launch time on the first frame and keeps repainting while it flies.
686 fn drive_raven(&mut self, ctx: &egui::Context) {
687 let Some(raven) = self.raven.as_mut() else { return };
688 raven.sprite.update(ctx);
689 let painter =
690 ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("facett_deck_raven")));
691 raven.sprite.paint(&painter);
692 }
693
694 /// Route this frame's clipboard events to the active facet, gated by caps.
695 /// The single OS-touching write (`clipboard::put`) lives here.
696 fn route_clipboard(&mut self, ctx: &egui::Context) {
697 let caps = self.active_caps();
698 if !(caps.copyable || caps.cuttable || caps.pasteable) {
699 return;
700 }
701 for action in clipboard::poll(ctx) {
702 let Some(f) = self.facets.get_mut(self.active) else { continue };
703 match action {
704 ClipAction::Copy if caps.copyable => {
705 if let Some(t) = f.copy() {
706 clipboard::put(ctx, t);
707 }
708 }
709 ClipAction::Cut if caps.cuttable => {
710 if let Some(t) = f.cut() {
711 clipboard::put(ctx, t);
712 }
713 }
714 ClipAction::Paste(s) if caps.pasteable => {
715 f.paste(&s);
716 }
717 // Capability not declared → ignore (event may belong to a focused
718 // sub-widget egui already handled).
719 _ => {}
720 }
721 }
722 }
723
724 // ── cross-instance component clone (Copy/Paste component) ────────────────
725 //
726 // A DISTINCT gesture from the text clipboard above: it transfers a facet's
727 // type-tagged PORTABLE state (not a text selection) to a same-kind sibling.
728 // See `.nornir/design/copy-paste-between-instances.md`. Surfaced two ways —
729 // the context menu in `component_menu` (right-click the body) and the
730 // `Ctrl+Shift+C / Ctrl+Shift+V` accelerators routed in `ui`.
731
732 /// The active facet's [`Facet::kind`] (`""` if empty / opted out).
733 pub fn active_kind(&self) -> &'static str {
734 self.facets.get(self.active).map(|f| f.kind()).unwrap_or("")
735 }
736
737 /// **Copy component** — encode the active facet's [`Facet::portable_state`]
738 /// into the tagged clipboard envelope and place it on the OS clipboard.
739 /// Returns the envelope text on success, or `None` if the active facet opts
740 /// out (empty `kind()` or no `portable_state()`). This is the data half the
741 /// gesture handlers + tests drive; the OS write is the caller's via
742 /// [`clipboard::put`] (done for them in [`copy_component`](Self::copy_component)).
743 pub fn copy_component_envelope(&self) -> Option<String> {
744 let f = self.facets.get(self.active)?;
745 let kind = f.kind();
746 if kind.is_empty() {
747 return None;
748 }
749 let state = f.portable_state()?;
750 Some(clipboard::encode_component(kind, &state))
751 }
752
753 /// Copy the active facet's portable state to the OS clipboard (the full
754 /// gesture). Returns `true` if something was copied.
755 pub fn copy_component(&mut self, ctx: &egui::Context) -> bool {
756 match self.copy_component_envelope() {
757 Some(env) => {
758 clipboard::put(ctx, env);
759 true
760 }
761 None => false,
762 }
763 }
764
765 /// **Paste component** — decode a clipboard `text` envelope and, **only if its
766 /// kind matches the active facet's** [`Facet::kind`], hand the state to
767 /// [`Facet::load_state`]. Returns `true` if the active facet adopted it.
768 /// A kind mismatch (or a non-envelope / wrong-version text) is a no-op that
769 /// raises a themed mismatch [`toast`](Self::toast) — the type-match guard is
770 /// the whole point: a `table` envelope NEVER loads into a `graphpan`.
771 pub fn paste_component(&mut self, text: &str, now: f64) -> bool {
772 let Some((kind, state)) = clipboard::decode_component(text) else {
773 // Not a component envelope at all — leave it for the text path; no toast.
774 return false;
775 };
776 let active_kind = self.active_kind();
777 if active_kind.is_empty() {
778 self.toast = Some(("this view doesn't accept a pasted component".to_string(), now));
779 return false;
780 }
781 if kind != active_kind {
782 self.toast = Some((format!("clipboard holds a `{kind}`, not a `{active_kind}`"), now));
783 return false;
784 }
785 let Some(f) = self.facets.get_mut(self.active) else { return false };
786 let accepted = f.load_state(&state);
787 if !accepted {
788 self.toast = Some((format!("this `{active_kind}` could not adopt the clipboard state"), now));
789 }
790 accepted
791 }
792
793 /// The current component-clone toast message (if one is live), for tests /
794 /// hosts that want to surface it themselves.
795 pub fn component_toast(&self) -> Option<&str> {
796 self.toast.as_ref().map(|(m, _)| m.as_str())
797 }
798
799 /// Right-click context-menu entries for the cross-instance clone gesture —
800 /// **Copy component** / **Paste component** — themed by the active style. A
801 /// host attaches these to the facet body (or its tab) via
802 /// `response.context_menu(|ui| deck.component_menu(ui))`. Greys out when the
803 /// active facet opts out (empty `kind()`).
804 pub fn component_menu(&mut self, ui: &mut egui::Ui) {
805 let km = look::keymap(ui);
806 let kind = self.active_kind();
807 let can_clone = !kind.is_empty();
808 ui.add_enabled_ui(can_clone && self.copy_component_envelope().is_some(), |ui| {
809 let label = format!("Copy component {}", km.label(Action::Copy, ui.ctx()));
810 if ui.button(label).clicked() {
811 self.copy_component(ui.ctx());
812 ui.close();
813 }
814 });
815 ui.add_enabled_ui(can_clone, |ui| {
816 let label = format!("Paste component {}", km.label(Action::Paste, ui.ctx()));
817 if ui.button(label).clicked() {
818 // Pull the OS clipboard via egui's paste request; the actual text
819 // arrives next frame as an Event::Paste, routed in `route_component_clipboard`.
820 ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste);
821 ui.close();
822 }
823 });
824 }
825
826 /// Route the `Ctrl+Shift+C / Ctrl+Shift+V` component-clone accelerators +
827 /// drain any pending paste envelope. Called once per frame from [`ui`](Self::ui),
828 /// AFTER the text clipboard so a focused TextEdit's plain Ctrl+C/V is untouched
829 /// (the Shift discriminates this gesture from text copy/paste).
830 fn route_component_clipboard(&mut self, ui: &mut egui::Ui) {
831 let now = ui.input(|i| i.time);
832 // Accelerators: Ctrl+Shift+C copies; Ctrl+Shift+V triggers an OS-clipboard
833 // paste request (the text lands next frame as Event::Paste, decoded below).
834 let copy_shift = egui::KeyboardShortcut::new(
835 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
836 egui::Key::C,
837 );
838 let paste_shift = egui::KeyboardShortcut::new(
839 egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
840 egui::Key::V,
841 );
842 if ui.input_mut(|i| i.consume_shortcut(©_shift)) {
843 self.copy_component(ui.ctx());
844 }
845 if ui.input_mut(|i| i.consume_shortcut(&paste_shift)) {
846 ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste);
847 }
848 // Drain any Paste events that look like a component envelope (a plain text
849 // paste decodes to None here and is left for the text clipboard path).
850 let pastes: Vec<String> = ui.input(|i| {
851 i.events
852 .iter()
853 .filter_map(|e| match e {
854 egui::Event::Paste(s) if clipboard::decode_component(s).is_some() => Some(s.clone()),
855 _ => None,
856 })
857 .collect()
858 });
859 for text in pastes {
860 self.paste_component(&text, now);
861 }
862 // Age out the toast.
863 if let Some((_, raised)) = self.toast {
864 if now - raised > TOAST_SECS {
865 self.toast = None;
866 }
867 }
868 }
869
870 /// Paint the live component-clone toast on a foreground layer (themed, spacious),
871 /// if one is set. A no-op when there is no toast.
872 fn paint_component_toast(&self, ui: &mut egui::Ui) {
873 let Some((msg, _)) = self.toast.as_ref() else { return };
874 let th = theme(ui);
875 let ctx = ui.ctx();
876 let painter =
877 ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("facett_deck_component_toast")));
878 let screen = ctx.content_rect();
879 let font = FontId::proportional(14.0);
880 let galley = painter.layout_no_wrap(msg.clone(), font.clone(), th.text);
881 let pad = vec2(14.0, 10.0); // spacious preset padding
882 let size = galley.size() + pad * 2.0;
883 // Bottom-centre, lifted off the edge.
884 let center = Pos2::new(screen.center().x, screen.max.y - size.y * 0.5 - 18.0);
885 let rect = Rect::from_center_size(center, size);
886 painter.rect_filled(rect, 8.0, th.panel_bg);
887 painter.rect_stroke(rect, 8.0, Stroke::new(1.0, th.panel_stroke), egui::StrokeKind::Inside);
888 painter.galley(rect.min + pad, galley, th.text);
889 ctx.request_repaint(); // keep ticking so the toast ages out on time
890 }
891
892 /// The whole-app observable state: the active facet + each facet's
893 /// `state_json`, plus an **additive** sibling `caps` map (title → caps JSON)
894 /// so the existing flat `facets[title]` shape is unchanged for consumers.
895 pub fn state_json(&self) -> serde_json::Value {
896 let mut facets = serde_json::Map::new();
897 let mut caps = serde_json::Map::new();
898 for f in &self.facets {
899 facets.insert(f.title().to_string(), f.state_json());
900 caps.insert(f.title().to_string(), f.caps().to_json());
901 }
902 serde_json::json!({
903 "active": self.facets.get(self.active).map(|f| f.title()),
904 "facets": facets,
905 "caps": caps,
906 // The deck's opt-in effects (DeckFx) as data: whether the shared glass/
907 // card `chrome` wrap is on, whether the active-facet bloom glow is on, and
908 // the active palette override. A headless driver reads this to PROVE the
909 // T1.3 showcase rendering (glass + bloom) is actually wired, not eyeballed.
910 "fx": {
911 "chrome": self.fx.chrome,
912 "glow": self.fx.glow,
913 "glow_layers": self.fx.glow_layers,
914 "palette": self.fx.palette(),
915 },
916 // The wasm-safe "what RAN" ledger — every facet render + every traced
917 // control handler that has executed this session (the readable proof
918 // the shipped artifact actually ran each surface). See `runtrace`.
919 "trace": { "ran": runtrace::snapshot(), "distinct": runtrace::distinct() },
920 })
921 }
922}
923
924/// A stable, bright-ish colour from a string (FNV-1a). Handy default node colour.
925pub fn hash_color(s: &str) -> Color32 {
926 let mut h: u32 = 2166136261;
927 for b in s.bytes() {
928 h = (h ^ b as u32).wrapping_mul(16777619);
929 }
930 Color32::from_rgb((h & 0xFF) as u8 | 0x60, ((h >> 8) & 0xFF) as u8 | 0x60, ((h >> 16) & 0xFF) as u8 | 0x60)
931}
932
933#[cfg(test)]
934mod tests {
935 use super::*;
936
937 #[test]
938 fn scene_builds() {
939 let mut s = Scene::new();
940 let a = s.node("Person", hash_color("Person"));
941 let b = s.node("Company", hash_color("Company"));
942 s.edge(a, b);
943 assert_eq!(s.nodes.len(), 2);
944 assert_eq!(s.edges.len(), 1);
945 assert!(!s.is_empty());
946 }
947
948 #[test]
949 fn force_layout_produces_finite_bounded_positions() {
950 let mut scene = Scene::new();
951 for i in 0..12 { scene.node(format!("n{i}"), hash_color("n")); }
952 for i in 0..12 { scene.edge(i, (i + 1) % 12); }
953 let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(400.0, 400.0));
954 let pos = positions(Layout::Force, &scene, rect);
955 assert_eq!(pos.len(), 12);
956 for p in &pos {
957 assert!(p.x.is_finite() && p.y.is_finite(), "finite");
958 assert!(rect.expand(50.0).contains(*p), "roughly within the rect");
959 }
960 }
961
962 #[test]
963 fn hash_color_is_stable() {
964 assert_eq!(hash_color("Person"), hash_color("Person"));
965 assert_ne!(hash_color("Person"), hash_color("Company"));
966 }
967
968 /// A minimal facet for deck tests.
969 struct Stub(&'static str);
970 impl Facet for Stub {
971 fn title(&self) -> &str {
972 self.0
973 }
974 fn ui(&mut self, ui: &mut Ui) {
975 ui.label(self.0);
976 }
977 fn state_json(&self) -> serde_json::Value {
978 serde_json::json!({ "t": self.0 })
979 }
980 }
981
982 /// A component-clone-capable stub: a `kind`, a JSON `payload` it round-trips
983 /// through `portable_state`/`load_state`.
984 struct CloneStub {
985 kind: &'static str,
986 payload: serde_json::Value,
987 }
988 impl Facet for CloneStub {
989 fn title(&self) -> &str {
990 self.kind
991 }
992 fn ui(&mut self, _ui: &mut Ui) {}
993 fn state_json(&self) -> serde_json::Value {
994 serde_json::json!({ "kind": self.kind })
995 }
996 fn kind(&self) -> &'static str {
997 self.kind
998 }
999 fn portable_state(&self) -> Option<serde_json::Value> {
1000 Some(self.payload.clone())
1001 }
1002 fn load_state(&mut self, state: &serde_json::Value) -> bool {
1003 self.payload = state.clone();
1004 true
1005 }
1006 }
1007
1008 #[test]
1009 fn component_clone_round_trips_through_the_deck() {
1010 // Instance A (configured) → envelope → instance B adopts it.
1011 let a = CloneStub { kind: "graphpan", payload: serde_json::json!({ "zoom": 2.0, "pan": [3, 4] }) };
1012 let mut deck_a = FacetDeck::new(vec![Box::new(a)]);
1013 let env = deck_a.copy_component_envelope().expect("A copies its portable state");
1014
1015 let mut deck_b = FacetDeck::new(vec![Box::new(CloneStub {
1016 kind: "graphpan",
1017 payload: serde_json::json!({ "zoom": 1.0, "pan": [0, 0] }),
1018 })]);
1019 assert!(deck_b.paste_component(&env, 0.0), "same-kind paste is accepted");
1020 // B now equals A's portable state.
1021 assert_eq!(
1022 deck_b.copy_component_envelope(),
1023 deck_a.copy_component_envelope(),
1024 "B adopted A's portable state exactly"
1025 );
1026 assert!(deck_b.component_toast().is_none(), "a successful paste raises no toast");
1027 }
1028
1029 #[test]
1030 fn component_clone_rejects_a_type_mismatch_with_a_toast() {
1031 // A `table` envelope handed to a `graphpan` → load_state NOT called.
1032 let table_env = clipboard::encode_component("table", &serde_json::json!({ "rows": 3 }));
1033 let mut deck = FacetDeck::new(vec![Box::new(CloneStub {
1034 kind: "graphpan",
1035 payload: serde_json::json!({ "zoom": 1.0 }),
1036 })]);
1037 let before = deck.copy_component_envelope();
1038 assert!(!deck.paste_component(&table_env, 0.0), "cross-type paste returns false");
1039 assert_eq!(deck.copy_component_envelope(), before, "graphpan state untouched");
1040 let toast = deck.component_toast().expect("mismatch raises a toast");
1041 assert!(toast.contains("table") && toast.contains("graphpan"), "toast names both kinds: {toast}");
1042 }
1043
1044 #[test]
1045 fn component_clone_version_guard_rejects_unknown_v() {
1046 let bad = serde_json::json!({ "facett.kind": "graphpan", "v": 7, "state": { "zoom": 9.0 } }).to_string();
1047 let mut deck = FacetDeck::new(vec![Box::new(CloneStub {
1048 kind: "graphpan",
1049 payload: serde_json::json!({ "zoom": 1.0 }),
1050 })]);
1051 let before = deck.copy_component_envelope();
1052 // An unknown-version text decodes to None → it's a no-op (left for the text path).
1053 assert!(!deck.paste_component(&bad, 0.0), "unknown version is not adopted");
1054 assert_eq!(deck.copy_component_envelope(), before, "state untouched by a bad-version paste");
1055 }
1056
1057 #[test]
1058 fn component_clone_opt_out_floor_neither_copies_nor_accepts() {
1059 // The plain Stub does NOT implement the trio → empty kind, no copy.
1060 let mut deck = FacetDeck::new(vec![Box::new(Stub("plain"))]);
1061 assert_eq!(deck.active_kind(), "", "opted out");
1062 assert!(deck.copy_component_envelope().is_none(), "opt-out facet never copies a component");
1063 // A real envelope handed to an opt-out facet is refused (no panic, no state).
1064 let env = clipboard::encode_component("table", &serde_json::json!({ "rows": 1 }));
1065 assert!(!deck.paste_component(&env, 0.0), "opt-out facet never adopts a component");
1066 assert!(deck.component_toast().is_some(), "the refusal is surfaced");
1067 }
1068
1069 #[test]
1070 fn deck_fx_is_off_by_default() {
1071 let deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
1072 assert_eq!(*deck.fx(), DeckFx::OFF, "no effects until the host opts in");
1073 assert!(!deck.has_raven());
1074 assert!(!deck.fx().glow);
1075 assert!(deck.fx().palette().is_none());
1076 }
1077
1078 #[test]
1079 fn deck_state_json_reports_fx_as_data() {
1080 // The deck's opt-in effects must be observable as data (a robot proof reads
1081 // `fx.chrome` / `fx.glow` to know the showcase rendering is wired ON).
1082 let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
1083 let off = deck.state_json();
1084 assert_eq!(off["fx"]["chrome"].as_bool(), Some(false), "chrome off by default");
1085 assert_eq!(off["fx"]["glow"].as_bool(), Some(false), "glow off by default");
1086 assert!(off["fx"]["palette"].is_null(), "no palette override by default");
1087
1088 deck.fx_mut().chrome = true;
1089 deck.fx_mut().glow = true;
1090 deck.set_palette(2);
1091 let on = deck.state_json();
1092 assert_eq!(on["fx"]["chrome"].as_bool(), Some(true), "chrome wired ON shows in state");
1093 assert_eq!(on["fx"]["glow"].as_bool(), Some(true), "glow wired ON shows in state");
1094 assert_eq!(on["fx"]["palette"].as_u64(), Some(2), "palette override shows in state");
1095 }
1096
1097 #[test]
1098 fn deck_cycle_palette_walks_theme_all() {
1099 let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
1100 let first = deck.cycle_palette();
1101 assert_eq!(first, 0);
1102 assert_eq!(deck.fx().theme().map(|t| t.name), Some(Theme::ALL[0]().name));
1103 // walks forward and wraps
1104 for _ in 1..Theme::ALL.len() {
1105 deck.cycle_palette();
1106 }
1107 assert_eq!(deck.cycle_palette(), 0, "wraps back to the first palette");
1108 }
1109
1110 #[test]
1111 fn deck_send_raven_launches_and_perches_after_a_full_flight() {
1112 use crate::effects::RAVEN_FLIGHT_SECS;
1113 let mut deck = FacetDeck::new(vec![Box::new(Stub("rows"))]);
1114 assert!(!deck.has_raven());
1115 let target = egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(200.0, 28.0));
1116 deck.send_raven(target);
1117 assert!(deck.has_raven(), "raven summoned");
1118 assert!(!deck.raven_perched(), "not perched at launch");
1119
1120 // Drive the sprite headlessly past the flight duration → it perches.
1121 if let Some(r) = deck.raven.as_mut() {
1122 r.sprite.advance(RAVEN_FLIGHT_SECS + 0.1);
1123 }
1124 assert!(deck.raven_perched(), "perched after the flight duration");
1125
1126 deck.clear_raven();
1127 assert!(!deck.has_raven());
1128 }
1129
1130 /// REGRESSION (inject-assert): merely *drawing* the palette picker without a
1131 /// user click must NOT pin a palette override. The bug: the picker auto-pinned
1132 /// index 0 on the first passive frame, turning the legacy `set_theme` override
1133 /// permanently on and clobbering a host's own theme (the rich `look::Theme`)
1134 /// every frame. We render one frame with no interaction and assert the override
1135 /// is still `None` (host theme wins).
1136 #[test]
1137 fn palette_picker_does_not_pin_without_a_user_click() {
1138 let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
1139 assert!(deck.fx().palette().is_none(), "starts with no override");
1140 let ctx = egui::Context::default();
1141 let mut chosen = Some(7usize);
1142 let _ = ctx.run(egui::RawInput::default(), |ctx| {
1143 egui::CentralPanel::default().show(ctx, |ui| {
1144 // No synthetic click is fed → the picker is drawn but not used.
1145 chosen = deck.palette_picker(ui);
1146 });
1147 });
1148 assert_eq!(chosen, None, "drawing the picker reports no selection without a click");
1149 assert!(
1150 deck.fx().palette().is_none(),
1151 "drawing the picker must not pin index 0 — that would clobber the host's own theme each frame"
1152 );
1153 }
1154
1155 #[test]
1156 fn deck_palette_override_applies_theme_in_a_ui_pass() {
1157 let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
1158 deck.set_palette(1); // sci-fi
1159 let ctx = egui::Context::default();
1160 let mut seen = "";
1161 let _ = ctx.run(egui::RawInput::default(), |ctx| {
1162 egui::CentralPanel::default().show(ctx, |ui| {
1163 deck.ui(ui);
1164 seen = theme(ui).name;
1165 });
1166 });
1167 assert_eq!(seen, Theme::ALL[1]().name, "deck applied its palette override");
1168 }
1169}