Skip to main content

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;
10pub mod caps;
11pub mod clip;
12pub mod clipboard;
13pub mod deckfx;
14pub mod edges;
15pub mod effects;
16pub mod focus;
17pub mod labels3d;
18pub mod harness;
19pub mod look;
20pub mod nav;
21pub mod overlay;
22pub mod rabbit;
23pub mod scroll_engine;
24pub mod testmatrix; // functional-status → nornir test-matrix bridge (feature
25                    // `testmatrix`); no-op in release.
26pub mod theme;
27pub mod trace; // structured IN/OUT/END event stream ($FACETT_TRACE) — the
28               // machine-readable data a facet actually rendered.
29pub use a11y::{Semantics, node as a11y_node, stable_id};
30pub use caps::FacetCaps;
31pub use clip::{ArrowColumnRef, ClipKind, ClipPayload, CopySource, PasteTarget};
32pub use clipboard::ClipAction;
33pub use deckfx::{DeckFx, DeckRaven};
34pub use look::{Action, KeyMap, Palette};
35pub use nav::{Dir4, Navigable, nearest_in_direction};
36pub use rabbit::{Rabbit, RabbitMesh, rabbit_mesh, rabbit_outline};
37pub use scroll_engine::SmoothScroll;
38pub use theme::{Theme, set_theme, theme};
39
40// The rich look-&-feel `Theme` (the work-order architecture) is re-exported under
41// an unambiguous alias so it coexists with the legacy flat palette `Theme` above.
42pub use look::Theme as LookTheme;
43
44/// A node: a label + a colour (the *consumer* picks the colour policy — hash by
45/// label, by status, …).
46#[derive(Clone)]
47pub struct Node {
48    pub label: String,
49    pub color: Color32,
50}
51
52/// A directed edge between node indices.
53#[derive(Clone, Copy)]
54pub struct Edge {
55    pub src: usize,
56    pub dst: usize,
57}
58
59/// A drawable graph: nodes + edges (edges index into `nodes`).
60#[derive(Default, Clone)]
61pub struct Scene {
62    pub nodes: Vec<Node>,
63    pub edges: Vec<Edge>,
64}
65
66impl Scene {
67    pub fn new() -> Self {
68        Self::default()
69    }
70    /// Push a node, returning its index.
71    pub fn node(&mut self, label: impl Into<String>, color: Color32) -> usize {
72        self.nodes.push(Node { label: label.into(), color });
73        self.nodes.len() - 1
74    }
75    pub fn edge(&mut self, src: usize, dst: usize) {
76        self.edges.push(Edge { src, dst });
77    }
78    pub fn is_empty(&self) -> bool {
79        self.nodes.is_empty()
80    }
81}
82
83/// Node placement strategy.
84#[derive(Clone, Copy, PartialEq, Eq, Default)]
85pub enum Layout {
86    #[default]
87    Circular,
88    /// Deterministic Fruchterman–Reingold (edges pull, all nodes repel). O(n²)
89    /// per iteration — best for small/medium graphs.
90    Force,
91}
92
93/// Draw a `Scene` into `ui` — the reusable render primitive. Empty scenes show
94/// `empty_hint`. Labels render when the node count is small enough to read.
95pub fn draw(ui: &mut Ui, scene: &Scene, layout: Layout, empty_hint: &str) {
96    let (rect, _) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
97    let th = theme(ui);
98    let painter = ui.painter_at(rect);
99    let n = scene.nodes.len();
100    if n == 0 {
101        painter.text(rect.center(), Align2::CENTER_CENTER, empty_hint, FontId::proportional(13.0), th.text_dim);
102        return;
103    }
104    let pos = positions(layout, scene, rect);
105    for e in &scene.edges {
106        if e.src < n && e.dst < n {
107            painter.line_segment([pos[e.src], pos[e.dst]], Stroke::new(0.6, th.edge));
108        }
109    }
110    for (i, node) in scene.nodes.iter().enumerate() {
111        painter.circle_filled(pos[i], 5.0, node.color);
112    }
113    if n <= 60 {
114        for (i, node) in scene.nodes.iter().enumerate() {
115            painter.text(pos[i] + vec2(7.0, 0.0), Align2::LEFT_CENTER, &node.label, FontId::proportional(10.0), th.text);
116        }
117    }
118}
119
120fn positions(layout: Layout, scene: &Scene, rect: Rect) -> Vec<Pos2> {
121    let n = scene.nodes.len();
122    let center = rect.center();
123    let radius = rect.size().min_elem() * 0.42;
124    let circular = |i: usize| {
125        let a = std::f32::consts::TAU * (i as f32) / (n as f32);
126        vec2(a.cos(), a.sin())
127    };
128    match layout {
129        Layout::Circular => (0..n).map(|i| center + radius * circular(i)).collect(),
130        Layout::Force => {
131            // Deterministic Fruchterman–Reingold from a circular seed (unit space).
132            let mut p: Vec<egui::Vec2> = (0..n).map(circular).collect();
133            let k = (1.0 / (n.max(1) as f32).sqrt()).clamp(0.05, 1.0);
134            for _ in 0..120 {
135                let mut disp = vec![egui::Vec2::ZERO; n];
136                for i in 0..n {
137                    for j in (i + 1)..n {
138                        let d = p[i] - p[j];
139                        let dist = d.length().max(1e-3);
140                        let f = k * k / dist;
141                        let dir = d / dist;
142                        disp[i] += dir * f;
143                        disp[j] -= dir * f;
144                    }
145                }
146                for e in &scene.edges {
147                    if e.src < n && e.dst < n {
148                        let d = p[e.src] - p[e.dst];
149                        let dist = d.length().max(1e-3);
150                        let f = dist * dist / k;
151                        let dir = d / dist;
152                        disp[e.src] -= dir * f;
153                        disp[e.dst] += dir * f;
154                    }
155                }
156                for i in 0..n {
157                    let dl = disp[i].length().max(1e-3);
158                    p[i] += disp[i] / dl * dl.min(0.04); // capped step (cooling-free, deterministic)
159                }
160            }
161            // Normalise to fit the rect.
162            let (mut mn, mut mx) = (egui::vec2(f32::MAX, f32::MAX), egui::vec2(f32::MIN, f32::MIN));
163            for v in &p {
164                mn.x = mn.x.min(v.x);
165                mn.y = mn.y.min(v.y);
166                mx.x = mx.x.max(v.x);
167                mx.y = mx.y.max(v.y);
168            }
169            let span = (mx - mn).max(egui::vec2(1e-3, 1e-3));
170            p.iter()
171                .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))
172                .collect()
173        }
174    }
175}
176
177/// The facett **component contract**. Every facet — graph, map, pipeline, table,
178/// the ported nornir viewers — implements this, so consumers (korp, nornir, …)
179/// compose them uniformly *and* get headless robot-testing for free.
180///
181/// The three things a component owes its host:
182/// 1. a **title** (tab label / panel heading),
183/// 2. how to **draw** itself into egui,
184/// 3. its **observable state** as JSON — dumped to `$APP_STATE` for headless
185///    assertions. **Rule:** every visible list/status/count goes in `state_json`.
186pub trait Facet {
187    fn title(&self) -> &str;
188    fn ui(&mut self, ui: &mut Ui);
189    fn state_json(&self) -> serde_json::Value;
190
191    // --- uniform capability surface (all defaulted; see caps.rs / clipboard.rs) ---
192
193    /// What this facet can do. Override to opt into capabilities.
194    fn caps(&self) -> FacetCaps {
195        FacetCaps::NONE
196    }
197
198    /// Current uniform scale (1.0 = native). Override if `caps().scalable`.
199    fn scale(&self) -> f32 {
200        1.0
201    }
202    /// Set the uniform scale; clamp internally. Default no-op (not scalable).
203    fn set_scale(&mut self, _scale: f32) {}
204
205    /// The current selection as JSON (also folded into `state_json` by
206    /// convention). `Null` when nothing/none selectable.
207    fn selection_json(&self) -> serde_json::Value {
208        serde_json::Value::Null
209    }
210
211    /// Clipboard hooks — see clipboard.rs. Defaults: nothing to give/take.
212    /// Returns the text to place on the clipboard (None = nothing copyable now).
213    fn copy(&mut self) -> Option<String> {
214        None
215    }
216    /// Like `copy`, but also removes the selection. Default delegates to `copy`.
217    fn cut(&mut self) -> Option<String> {
218        self.copy()
219    }
220    /// Accept pasted text. Returns true if consumed.
221    fn paste(&mut self, _text: &str) -> bool {
222        false
223    }
224
225    /// Optional downcast handle for hosts that need typed access to a specific
226    /// facet living inside a [`FacetDeck`] (e.g. a robot-UI driver clicking an
227    /// app-level control that must forward to a concrete component's own API).
228    /// Defaulted to `None` so no existing facet has to change; a component opts in
229    /// by returning `Some(self)`.
230    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
231        None
232    }
233}
234
235/// A tabbed set of [`Facet`]s — the reusable multi-component shell. Draws a tab
236/// bar + the active facet, and composes **every** facet's `state_json` under its
237/// title, so the whole-app introspection contract is free. korp/nornir can build
238/// their window from a `FacetDeck` instead of hand-rolling tabs + the state dump.
239pub struct FacetDeck {
240    facets: Vec<Box<dyn Facet>>,
241    active: usize,
242    /// Opt-in deck effects (palette override + glow). `Default` = all off, so a
243    /// deck that never opts in is unchanged and pays nothing.
244    fx: DeckFx,
245    /// A raven summoned through the deck, in flight or perched (or `None`).
246    raven: Option<DeckRaven>,
247}
248
249impl FacetDeck {
250    pub fn new(facets: Vec<Box<dyn Facet>>) -> Self {
251        Self { facets, active: 0, fx: DeckFx::OFF, raven: None }
252    }
253    pub fn active(&self) -> usize {
254        self.active
255    }
256
257    /// The title of the currently-active facet (the deck's `state_json["active"]`),
258    /// or `None` if the deck is empty.
259    pub fn active_title(&self) -> Option<&str> {
260        self.facets.get(self.active).map(|f| f.title())
261    }
262
263    /// The titles of every tabbed facet, in tab order — the discoverable surface a
264    /// host (or a robot-UI control channel) enumerates to know which tabs exist.
265    pub fn titles(&self) -> Vec<&str> {
266        self.facets.iter().map(|f| f.title()).collect()
267    }
268
269    /// Make the facet titled `title` the active tab — the programmatic (headless,
270    /// robot-addressable) equivalent of clicking its tab header. Returns `true` if a
271    /// facet with that title exists (and is now active), `false` otherwise. This is
272    /// the named boundary a control channel switches tabs through (the deck analogue
273    /// of the viz's `Tab::from_name`), so a driver needn't replay a pointer click.
274    pub fn set_active_by_title(&mut self, title: &str) -> bool {
275        match self.facets.iter().position(|f| f.title() == title) {
276            Some(i) => {
277                self.active = i;
278                true
279            }
280            None => false,
281        }
282    }
283
284    /// Typed mutable access to the facet with `title`, downcast to `T` — `None` if
285    /// no such facet, or it doesn't opt into [`Facet::as_any_mut`], or the type
286    /// mismatches. Lets a host drive a concrete component's own API (e.g. a
287    /// robot-UI control forwarding a node selection to a `SystemChart`).
288    pub fn facet_mut<T: std::any::Any>(&mut self, title: &str) -> Option<&mut T> {
289        self.facets
290            .iter_mut()
291            .find(|f| f.title() == title)
292            .and_then(|f| f.as_any_mut())
293            .and_then(|a| a.downcast_mut::<T>())
294    }
295
296    /// Replace the facet whose `title` matches with `facet` (the box's own title is
297    /// what the deck enumerates afterwards). Returns `true` if a facet was replaced.
298    /// Used by hosts that **reload** a tab's data in place — e.g. the OSM region
299    /// picker rebuilds the `OSM 2D` / `OSM 3D` views from a freshly clipped region
300    /// and swaps them in, keeping the same tab slots (and the active selection).
301    pub fn replace_facet(&mut self, title: &str, facet: Box<dyn Facet>) -> bool {
302        if let Some(slot) = self.facets.iter_mut().find(|f| f.title() == title) {
303            *slot = facet;
304            true
305        } else {
306            false
307        }
308    }
309
310    // ── opt-in effects + theming (see deckfx.rs) ─────────────────────────────
311
312    /// Enable deck effects up front (builder form of [`fx_mut`](Self::fx_mut)).
313    pub fn with_fx(mut self, fx: DeckFx) -> Self {
314        self.fx = fx;
315        self
316    }
317    /// The current deck-effects config (read-only).
318    pub fn fx(&self) -> &DeckFx {
319        &self.fx
320    }
321    /// Mutate the deck-effects config (toggle glow, pin a palette, …).
322    pub fn fx_mut(&mut self) -> &mut DeckFx {
323        &mut self.fx
324    }
325    /// Override the deck theme with palette index `i` (wraps); enables the
326    /// override. Convenience over `fx_mut().set_palette(i)`.
327    pub fn set_palette(&mut self, i: usize) {
328        self.fx.set_palette(i);
329    }
330    /// Advance to the next palette in [`Theme::ALL`] (wrapping); returns the new
331    /// index. Convenience over `fx_mut().cycle_palette()`.
332    pub fn cycle_palette(&mut self) -> usize {
333        self.fx.cycle_palette()
334    }
335
336    /// **Summon the raven** to perch on `target` — any rect a facet/host hands us
337    /// (a table row, a node, a header). Replaces any raven already in flight. The
338    /// body is tinted from the deck's current palette (or the host theme). Logs an
339    /// activity trail entry. Drive/paint happens automatically inside
340    /// [`ui`](Self::ui).
341    pub fn send_raven(&mut self, target: Rect) {
342        let theme = self.effective_theme();
343        self.raven = Some(DeckRaven::new(target, &theme));
344        harness::trail(
345            harness::Kind::Render,
346            format!("raven launched → perch ({:.0},{:.0})", target.center().x, target.top()),
347        );
348    }
349    /// True while a raven is present (flying or perched).
350    pub fn has_raven(&self) -> bool {
351        self.raven.is_some()
352    }
353    /// True once the summoned raven has landed (false if none).
354    pub fn raven_perched(&self) -> bool {
355        self.raven.as_ref().map(|r| r.is_perched()).unwrap_or(false)
356    }
357    /// Dismiss any raven.
358    pub fn clear_raven(&mut self) {
359        self.raven = None;
360    }
361
362    /// The theme the deck paints with: the fx palette override if set, else
363    /// [`Theme::default`] (the host's own `set_theme` still applies its visuals;
364    /// this is just the colour source for deck-owned effects/picker).
365    fn effective_theme(&self) -> Theme {
366        self.fx.theme().unwrap_or_default()
367    }
368
369    /// Draw a one-line **palette picker** — a switcher over [`Theme::ALL`] the
370    /// host can place anywhere (toolbar, menu). Selecting a palette pins the fx
371    /// override; `ui()` then applies it each frame. Returns the chosen index if it
372    /// changed this frame.
373    ///
374    /// The override stays **off until the user actually clicks** a palette: merely
375    /// drawing the picker must not pin index 0, otherwise a host that drives its
376    /// own theme (e.g. the rich [`crate::look::Theme`]) would be silently clobbered
377    /// every frame by the legacy `set_theme` in [`ui`](Self::ui) — size still
378    /// changing (spacing) but colour frozen on `Theme::ALL[0]`. So we only pin when
379    /// the selection genuinely changed this frame.
380    pub fn palette_picker(&mut self, ui: &mut Ui) -> Option<usize> {
381        let mut sel = self.fx.palette().unwrap_or(0);
382        let before = sel;
383        ui.horizontal_wrapped(|ui| {
384            ui.label("Palette:");
385            for (i, ctor) in Theme::ALL.iter().enumerate() {
386                ui.selectable_value(&mut sel, i, ctor().name);
387            }
388        });
389        if sel != before {
390            self.fx.set_palette(sel);
391        }
392        (sel != before).then_some(sel)
393    }
394
395    /// The capabilities of the currently-active facet (or `NONE` if empty).
396    pub fn active_caps(&self) -> FacetCaps {
397        self.facets.get(self.active).map(|f| f.caps()).unwrap_or(FacetCaps::NONE)
398    }
399
400    /// The active facet's current scale (1.0 if none / not scalable).
401    fn active_scale(&self) -> f32 {
402        self.facets.get(self.active).map(|f| f.scale()).unwrap_or(1.0)
403    }
404
405    /// Multiply the active facet's scale by `k`, clamped to a sane range.
406    fn scale_active(&mut self, k: f32) {
407        if let Some(f) = self.facets.get_mut(self.active) {
408            let s = (f.scale() * k).clamp(0.25, 4.0);
409            f.set_scale(s);
410        }
411    }
412
413    /// Reset the active facet's scale to native.
414    fn reset_scale(&mut self) {
415        if let Some(f) = self.facets.get_mut(self.active) {
416            f.set_scale(1.0);
417        }
418    }
419
420    /// Draw the tab bar + capability toolbar + the active facet, and route
421    /// capability-gated shortcuts (Ctrl-+/-/0 for scale; Ctrl-C/X/V for clipboard).
422    pub fn ui(&mut self, ui: &mut Ui) {
423        // Opt-in palette override: apply the chosen Theme::ALL palette + its
424        // egui Visuals each frame so the whole deck (and every facet that reads
425        // `theme(ui)`) follows. No override → the host's own theme stays.
426        if let Some(theme) = self.fx.theme() {
427            set_theme(ui.ctx(), theme);
428        }
429
430        let titles: Vec<String> = self.facets.iter().map(|f| f.title().to_string()).collect();
431        // Wrap the tab bar: with many facets a single non-wrapping row overflows
432        // the panel width and the trailing tabs become unreachable (off-screen,
433        // unclickable for a robot driver / pointer). Wrapping keeps every tab
434        // visible + clickable no matter how many facets the deck holds.
435        ui.horizontal_wrapped(|ui| {
436            for (i, t) in titles.iter().enumerate() {
437                ui.selectable_value(&mut self.active, i, t);
438            }
439        });
440
441        let caps = self.active_caps();
442
443        // Capability-driven toolbar: only show controls the active facet honors.
444        if caps.scalable {
445            ui.horizontal(|ui| {
446                if ui.button("−").on_hover_text("Zoom out (Ctrl-−)").clicked() {
447                    self.scale_active(1.0 / 1.1);
448                }
449                ui.label(format!("{:.0}%", self.active_scale() * 100.0));
450                if ui.button("+").on_hover_text("Zoom in (Ctrl-+)").clicked() {
451                    self.scale_active(1.1);
452                }
453                if ui.button("Reset").on_hover_text("Reset zoom (Ctrl-0)").clicked() {
454                    self.reset_scale();
455                }
456            });
457        }
458
459        // Capability-gated scale shortcuts. egui has no semantic event for these,
460        // so we hand-detect the key combos (clipboard uses semantic events below).
461        if caps.scalable {
462            let (cmd, plus, minus, zero) = ui.input(|i| {
463                (
464                    i.modifiers.command,
465                    i.key_pressed(egui::Key::Plus) || i.key_pressed(egui::Key::Equals),
466                    i.key_pressed(egui::Key::Minus),
467                    i.key_pressed(egui::Key::Num0),
468                )
469            });
470            if cmd {
471                if plus {
472                    self.scale_active(1.1);
473                }
474                if minus {
475                    self.scale_active(1.0 / 1.1);
476                }
477                if zero {
478                    self.reset_scale();
479                }
480            }
481        }
482
483        // Clipboard routing: drain semantic events and dispatch to the active
484        // facet, gated by its caps. A focused TextEdit already consumed its own.
485        self.route_clipboard(ui.ctx());
486
487        ui.separator();
488        // Render the active facet, capturing the rect it occupied so the deck can
489        // bloom it (opt-in glow) without the facet knowing.
490        let content = ui.scope(|ui| {
491            if let Some(f) = self.facets.get_mut(self.active) {
492                f.ui(ui);
493            }
494        });
495        let content_rect = content.response.rect;
496
497        // Opt-in glow on the active facet's content rect, pulsing.
498        if self.fx.glow && content_rect.is_positive() {
499            let theme = self.effective_theme();
500            let time = ui.input(|i| i.time);
501            let painter = ui.painter_at(content_rect);
502            deckfx::paint_active_glow(&painter, content_rect.shrink(2.0), &theme, &self.fx, time);
503            ui.ctx().request_repaint(); // keep the pulse animating
504        }
505
506        // Drive + paint a summoned raven on a foreground layer above everything.
507        self.drive_raven(ui.ctx());
508    }
509
510    /// Advance + paint the summoned raven (if any) on a foreground layer. Pins its
511    /// launch time on the first frame and keeps repainting while it flies.
512    fn drive_raven(&mut self, ctx: &egui::Context) {
513        let Some(raven) = self.raven.as_mut() else { return };
514        raven.sprite.update(ctx);
515        let painter =
516            ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("facett_deck_raven")));
517        raven.sprite.paint(&painter);
518    }
519
520    /// Route this frame's clipboard events to the active facet, gated by caps.
521    /// The single OS-touching write (`clipboard::put`) lives here.
522    fn route_clipboard(&mut self, ctx: &egui::Context) {
523        let caps = self.active_caps();
524        if !(caps.copyable || caps.cuttable || caps.pasteable) {
525            return;
526        }
527        for action in clipboard::poll(ctx) {
528            let Some(f) = self.facets.get_mut(self.active) else { continue };
529            match action {
530                ClipAction::Copy if caps.copyable => {
531                    if let Some(t) = f.copy() {
532                        clipboard::put(ctx, t);
533                    }
534                }
535                ClipAction::Cut if caps.cuttable => {
536                    if let Some(t) = f.cut() {
537                        clipboard::put(ctx, t);
538                    }
539                }
540                ClipAction::Paste(s) if caps.pasteable => {
541                    f.paste(&s);
542                }
543                // Capability not declared → ignore (event may belong to a focused
544                // sub-widget egui already handled).
545                _ => {}
546            }
547        }
548    }
549
550    /// The whole-app observable state: the active facet + each facet's
551    /// `state_json`, plus an **additive** sibling `caps` map (title → caps JSON)
552    /// so the existing flat `facets[title]` shape is unchanged for consumers.
553    pub fn state_json(&self) -> serde_json::Value {
554        let mut facets = serde_json::Map::new();
555        let mut caps = serde_json::Map::new();
556        for f in &self.facets {
557            facets.insert(f.title().to_string(), f.state_json());
558            caps.insert(f.title().to_string(), f.caps().to_json());
559        }
560        serde_json::json!({
561            "active": self.facets.get(self.active).map(|f| f.title()),
562            "facets": facets,
563            "caps": caps,
564        })
565    }
566}
567
568/// A stable, bright-ish colour from a string (FNV-1a). Handy default node colour.
569pub fn hash_color(s: &str) -> Color32 {
570    let mut h: u32 = 2166136261;
571    for b in s.bytes() {
572        h = (h ^ b as u32).wrapping_mul(16777619);
573    }
574    Color32::from_rgb((h & 0xFF) as u8 | 0x60, ((h >> 8) & 0xFF) as u8 | 0x60, ((h >> 16) & 0xFF) as u8 | 0x60)
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    #[test]
582    fn scene_builds() {
583        let mut s = Scene::new();
584        let a = s.node("Person", hash_color("Person"));
585        let b = s.node("Company", hash_color("Company"));
586        s.edge(a, b);
587        assert_eq!(s.nodes.len(), 2);
588        assert_eq!(s.edges.len(), 1);
589        assert!(!s.is_empty());
590    }
591
592    #[test]
593    fn force_layout_produces_finite_bounded_positions() {
594        let mut scene = Scene::new();
595        for i in 0..12 { scene.node(format!("n{i}"), hash_color("n")); }
596        for i in 0..12 { scene.edge(i, (i + 1) % 12); }
597        let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(400.0, 400.0));
598        let pos = positions(Layout::Force, &scene, rect);
599        assert_eq!(pos.len(), 12);
600        for p in &pos {
601            assert!(p.x.is_finite() && p.y.is_finite(), "finite");
602            assert!(rect.expand(50.0).contains(*p), "roughly within the rect");
603        }
604    }
605
606    #[test]
607    fn hash_color_is_stable() {
608        assert_eq!(hash_color("Person"), hash_color("Person"));
609        assert_ne!(hash_color("Person"), hash_color("Company"));
610    }
611
612    /// A minimal facet for deck tests.
613    struct Stub(&'static str);
614    impl Facet for Stub {
615        fn title(&self) -> &str {
616            self.0
617        }
618        fn ui(&mut self, ui: &mut Ui) {
619            ui.label(self.0);
620        }
621        fn state_json(&self) -> serde_json::Value {
622            serde_json::json!({ "t": self.0 })
623        }
624    }
625
626    #[test]
627    fn deck_fx_is_off_by_default() {
628        let deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
629        assert_eq!(*deck.fx(), DeckFx::OFF, "no effects until the host opts in");
630        assert!(!deck.has_raven());
631        assert!(!deck.fx().glow);
632        assert!(deck.fx().palette().is_none());
633    }
634
635    #[test]
636    fn deck_cycle_palette_walks_theme_all() {
637        let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
638        let first = deck.cycle_palette();
639        assert_eq!(first, 0);
640        assert_eq!(deck.fx().theme().map(|t| t.name), Some(Theme::ALL[0]().name));
641        // walks forward and wraps
642        for _ in 1..Theme::ALL.len() {
643            deck.cycle_palette();
644        }
645        assert_eq!(deck.cycle_palette(), 0, "wraps back to the first palette");
646    }
647
648    #[test]
649    fn deck_send_raven_launches_and_perches_after_a_full_flight() {
650        use crate::effects::RAVEN_FLIGHT_SECS;
651        let mut deck = FacetDeck::new(vec![Box::new(Stub("rows"))]);
652        assert!(!deck.has_raven());
653        let target = egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(200.0, 28.0));
654        deck.send_raven(target);
655        assert!(deck.has_raven(), "raven summoned");
656        assert!(!deck.raven_perched(), "not perched at launch");
657
658        // Drive the sprite headlessly past the flight duration → it perches.
659        if let Some(r) = deck.raven.as_mut() {
660            r.sprite.advance(RAVEN_FLIGHT_SECS + 0.1);
661        }
662        assert!(deck.raven_perched(), "perched after the flight duration");
663
664        deck.clear_raven();
665        assert!(!deck.has_raven());
666    }
667
668    /// REGRESSION (inject-assert): merely *drawing* the palette picker without a
669    /// user click must NOT pin a palette override. The bug: the picker auto-pinned
670    /// index 0 on the first passive frame, turning the legacy `set_theme` override
671    /// permanently on and clobbering a host's own theme (the rich `look::Theme`)
672    /// every frame. We render one frame with no interaction and assert the override
673    /// is still `None` (host theme wins).
674    #[test]
675    fn palette_picker_does_not_pin_without_a_user_click() {
676        let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
677        assert!(deck.fx().palette().is_none(), "starts with no override");
678        let ctx = egui::Context::default();
679        let mut chosen = Some(7usize);
680        let _ = ctx.run(egui::RawInput::default(), |ctx| {
681            egui::CentralPanel::default().show(ctx, |ui| {
682                // No synthetic click is fed → the picker is drawn but not used.
683                chosen = deck.palette_picker(ui);
684            });
685        });
686        assert_eq!(chosen, None, "drawing the picker reports no selection without a click");
687        assert!(
688            deck.fx().palette().is_none(),
689            "drawing the picker must not pin index 0 — that would clobber the host's own theme each frame"
690        );
691    }
692
693    #[test]
694    fn deck_palette_override_applies_theme_in_a_ui_pass() {
695        let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
696        deck.set_palette(1); // sci-fi
697        let ctx = egui::Context::default();
698        let mut seen = "";
699        let _ = ctx.run(egui::RawInput::default(), |ctx| {
700            egui::CentralPanel::default().show(ctx, |ui| {
701                deck.ui(ui);
702                seen = theme(ui).name;
703            });
704        });
705        assert_eq!(seen, Theme::ALL[1]().name, "deck applied its palette override");
706    }
707}