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