facett-core/src/panel.rs
//! **The `Panel` trait — the constellation-wide UI-pane seam (Phase 0 foundation).**
//!
//! Every UI pane in every egui app in the nordisk constellation becomes one
//! `Panel` value; the app holds `Box<dyn Panel>` per tab and never cares which
//! *backend* is behind it (see `.nornir/wasm-ui-panels-design.md` §1). The trait
//! is the PRIMARY seam and it has four backends, in priority order:
//!
//! 1. **native in-process** (fastest, default) — a facett [`Facet`](crate::Facet)
//! painting straight into `egui::Ui`. This module provides it as the **blanket
//! [`impl<T: Facet> Panel for T`]**: because [`Facet`](crate::Facet) now carries
//! a defaulted `update_json`, its four methods line up 1:1 with `Panel`, so
//! **every existing `Facet` is a `Panel` for free** — no per-facet code.
//! 2. **native cross-host adapter** (app↔app embedding, no wasm) — a `<guest>-embed`
//! bridge crate wraps a guest component crate as `Box<dyn Panel>` (design §3).
//! 3. **wasm Component** — only when the target is the browser (design §2).
//! 4. **headless** — for tests: `ui()` is a no-op, `update_json` applies messages,
//! `state_json` snapshots. [`drive`] is that driver (reuses the same seam the
//! facett-core [`harness`](crate::harness) drives for `Facet`/`Elm`).
//!
//! The four methods are exactly the facett Elm contract projected onto a
//! host-agnostic, object-safe trait — the SAME `state_json` the nornir test-matrix
//! and robot-UI already consume, so "headless drive falls out for free".
/// One pane, host-/backend-agnostic. The single seam every UI pane implements.
///
/// It is **object-safe** (`Box<dyn Panel>` is the currency the deck/host holds),
/// and it mirrors [`Facet`](crate::Facet)'s four core methods so the blanket impl
/// below makes every `Facet` a `Panel`.
pub trait Panel {
/// Tab label / panel heading.
fn title(&self) -> &str;
/// Paint into the live egui frame. Backends: native paints directly; the
/// native cross-host adapter forwards to the guest pane's own `ui`; the wasm
/// backend paints a decoded display-list; headless paints nothing.
fn ui(&mut self, ui: &mut egui::Ui);
/// FC-3 observable state — the common currency for tests + the web state-hook.
fn state_json(&self) -> serde_json::Value;
/// The Elm mutation path — apply one message (JSON). Used by the headless
/// drive + robotui, and by the wasm/adapter backends to route host-side input.
fn update_json(&mut self, msg_json: &str);
/// The pane's **STRUCTURAL severity** — the RESOLVED Robot-UI error signal that
/// the headless robot reads through this seam (decision (a)). Mirrors
/// [`Facet::severity`](crate::Facet::severity); the blanket impl below forwards
/// to it. **Defaulted to [`Severity::Info`]**(crate::Severity::Info) so it is
/// purely ADDITIVE — no existing `Panel` backend has to change. The Robot-UI
/// HARD GATE fails on any driven pane that returns
/// [`Severity::Error`](crate::Severity::Error).
fn severity(&self) -> crate::Severity {
crate::Severity::Info
}
/// The pane's stable DEV-ID — mirrors [`Facet::component`](crate::Facet::component);
/// the blanket impl below forwards to it. Defaulted to `""` so it is purely
/// ADDITIVE — no existing `Panel` backend has to change.
fn component(&self) -> &'static str {
""
}
}
/// **Backend (1): native in-process.** The blanket impl that makes every facett
/// [`Facet`](crate::Facet) a [`Panel`] with zero per-facet code. It forwards each
/// of the four `Panel` methods to the identically-shaped `Facet` method (the
/// `update_json` default landed on `Facet` for exactly this convergence). There is
/// no boundary, no serialize, no wasm toolchain — this is what a pane runs in its
/// own app's desktop client, the common case for every inventoried pane.
impl<T: crate::Facet + ?Sized> Panel for T {
fn title(&self) -> &str {
crate::Facet::title(self)
}
fn ui(&mut self, ui: &mut egui::Ui) {
crate::Facet::ui(self, ui)
}
fn state_json(&self) -> serde_json::Value {
crate::Facet::state_json(self)
}
fn update_json(&mut self, msg_json: &str) {
crate::Facet::update_json(self, msg_json)
}
fn severity(&self) -> crate::Severity {
crate::Facet::severity(self)
}
fn component(&self) -> &'static str {
crate::Facet::component(self)
}
}
/// **Backend (4): headless.** Apply `msgs` to `panel` in order via
/// [`Panel::update_json`], snapshotting [`Panel::state_json`] **after each
/// message**. Returns one JSON snapshot per applied message (same length + order as
/// `msgs`), so a test can assert the whole state *transition sequence*, not just
/// the final state. No egui, no GPU — `ui()` is never called, so this runs
/// anywhere, deterministically, with zero device. This is the `Panel` analogue of
/// the [`harness`](crate::harness) `Elm` driver.
pub fn drive<'a>(panel: &mut dyn Panel, msgs: impl IntoIterator<Item = &'a str>) -> Vec<serde_json::Value> {
let mut snapshots = Vec::new();
for m in msgs {
panel.update_json(m);
snapshots.push(panel.state_json());
}
snapshots
}
/// [`drive`] `panel` through `msgs`, then return **only** the final
/// [`Panel::state_json`] snapshot — the terminal FC-3 state after the sequence.
pub fn snapshot<'a>(panel: &mut dyn Panel, msgs: impl IntoIterator<Item = &'a str>) -> serde_json::Value {
drive(panel, msgs);
panel.state_json()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Facet;
use egui::Ui;
/// A trivial `Facet` that does NOT override `update_json` — it exercises the
/// defaulted no-op path. Proves the blanket impl compiles + a plain `Facet` is
/// usable as `Box<dyn Panel>`.
struct Static {
title: String,
items: usize,
}
impl Facet for Static {
fn title(&self) -> &str {
&self.title
}
fn ui(&mut self, _ui: &mut Ui) {}
fn state_json(&self) -> serde_json::Value {
serde_json::json!({ "items": self.items })
}
}
/// A `Facet` that DOES override `update_json` (the Elm mutation path). Proves an
/// existing hand-written `update_json` override still works — the blanket
/// `Panel::update_json` routes into the override, not the `Facet` default no-op.
struct Counter {
count: i64,
last: Option<String>,
}
impl Facet for Counter {
fn title(&self) -> &str {
"counter"
}
fn ui(&mut self, _ui: &mut Ui) {}
fn state_json(&self) -> serde_json::Value {
serde_json::json!({ "count": self.count, "last": self.last })
}
fn update_json(&mut self, msg_json: &str) {
let Ok(v) = serde_json::from_str::<serde_json::Value>(msg_json) else {
return;
};
if let Some(n) = v.get("add").and_then(|n| n.as_i64()) {
self.count += n;
}
if let Some(s) = v.get("mark").and_then(|s| s.as_str()) {
self.last = Some(s.to_string());
}
}
}
/// Backend (1): the blanket impl compiles and a sample `Facet` is usable as
/// `Box<dyn Panel>` — the whole point of Phase 0.
#[test]
fn blanket_impl_makes_a_facet_usable_as_box_dyn_panel() {
let mut p: Box<dyn Panel> = Box::new(Static { title: "s".into(), items: 3 });
assert_eq!(Panel::title(&*p), "s");
assert_eq!(p.state_json()["items"], 3);
// Default `update_json` is a no-op on a facet that doesn't override it.
p.update_json(r#"{"anything":true}"#);
assert_eq!(p.state_json()["items"], 3, "defaulted update_json is a no-op");
}
/// A hand-written `update_json` override on a `Facet` is what the `Panel`
/// mutation path calls — verifying the ADDITIVE default did not shadow overrides.
#[test]
fn override_update_json_is_routed_through_panel() {
let mut c = Counter { count: 0, last: None };
// Call through the `Panel` seam specifically (not the inherent/Facet path).
Panel::update_json(&mut c, r#"{"add": 5}"#);
assert_eq!(Panel::state_json(&c)["count"], 5, "Panel routed into the Facet override");
}
/// Backend (4): the headless driver applies a `Vec` of JSON messages and the
/// `state_json` snapshots show the transition sequence.
#[test]
fn headless_driver_applies_msgs_and_state_json_transitions() {
let mut c = Counter { count: 0, last: None };
let snaps = drive(
&mut c as &mut dyn Panel,
[r#"{"add": 1}"#, r#"{"add": 2}"#, r#"{"mark": "done"}"#, r#"{"add": -3}"#],
);
// One snapshot per message, in order — the whole transition, not just the end.
assert_eq!(snaps.len(), 4);
assert_eq!(snaps[0]["count"], 1);
assert_eq!(snaps[1]["count"], 3);
assert_eq!(snaps[2]["count"], 3, "the mark message doesn't change count");
assert_eq!(snaps[2]["last"], "done");
assert_eq!(snaps[3]["count"], 0, "1+2-3 = 0");
}
/// The STRUCTURAL severity (decision (a)) rides the `Facet` → blanket `Panel`
/// seam: a facet reporting `Severity::Error` is RED *through the `Panel`
/// contract* the headless robot drives — no text scan involved. Default facets
/// are the `Info` (green) floor.
#[test]
fn structural_severity_rides_the_facet_panel_seam() {
use crate::Severity;
/// A facet whose severity depends on its state: it goes RED (Error) when a
/// load flag is set — the shape a real pane uses (fold over its atoms).
struct Loader {
failed: bool,
}
impl Facet for Loader {
fn title(&self) -> &str {
"loader"
}
fn ui(&mut self, _ui: &mut Ui) {}
fn state_json(&self) -> serde_json::Value {
serde_json::json!({ "failed": self.failed })
}
fn update_json(&mut self, msg_json: &str) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(msg_json)
&& let Some(b) = v.get("failed").and_then(|b| b.as_bool())
{
self.failed = b;
}
}
fn severity(&self) -> Severity {
// Fold: the "load failed" atom is the only non-Info atom.
crate::worst_severity([if self.failed {
Severity::Error
} else {
Severity::Info
}])
}
}
// Green pane: Info through both the Facet and the Panel seam.
let mut p: Box<dyn Panel> = Box::new(Loader { failed: false });
assert_eq!(Panel::severity(&*p), Severity::Info, "clean pane is green");
assert!(!Panel::severity(&*p).is_error());
// Drive it into a failure — the Panel seam now reports Error (RED).
p.update_json(r#"{"failed": true}"#);
assert_eq!(
Panel::severity(&*p),
Severity::Error,
"a driven load failure is RED through the Panel seam (the gate signal)"
);
assert!(Panel::severity(&*p).is_error(), "this is what FAILS the Robot-UI gate");
// A default facet that never overrides severity() stays green (additive).
let d: Box<dyn Panel> = Box::new(Static { title: "s".into(), items: 1 });
assert_eq!(Panel::severity(&*d), Severity::Info, "defaulted facet is green");
}
/// `snapshot` returns just the terminal state after the whole sequence.
#[test]
fn snapshot_returns_terminal_state() {
let mut c = Counter { count: 10, last: None };
let final_state = snapshot(&mut c as &mut dyn Panel, [r#"{"add": 4}"#, r#"{"add": 6}"#]);
assert_eq!(final_state["count"], 20);
}
/// A heterogeneous deck of `Box<dyn Panel>` from DIFFERENT concrete `Facet`
/// types — the compose-uniformly property the whole factoring rests on.
#[test]
fn box_dyn_panel_deck_is_heterogeneous() {
let mut deck: Vec<Box<dyn Panel>> = vec![
Box::new(Static { title: "a".into(), items: 1 }),
Box::new(Counter { count: 7, last: None }),
];
let titles: Vec<String> = deck.iter().map(|p| p.title().to_string()).collect();
assert_eq!(titles, vec!["a".to_string(), "counter".to_string()]);
// Driving one pane doesn't touch the other.
deck[1].update_json(r#"{"add": 3}"#);
assert_eq!(deck[1].state_json()["count"], 10);
assert_eq!(deck[0].state_json()["items"], 1);
}
}