Skip to main content

cartography/
request.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Request side: graph + signals + intent → projection request.
5
6use std::collections::HashMap;
7
8use kernel::geometry::PortableSize;
9use kernel::graph::NodeKey;
10use serde::{Deserialize, Serialize};
11
12use crate::signals::IntelligenceSignals;
13
14/// Inputs to a single projection call.
15///
16/// The borrow lifetimes communicate the contract: cartography sees
17/// graph truth and intelligence signals as immutable references; it
18/// never mutates either. The view intent is owned because it carries
19/// per-call configuration (target size, focus node, filter), not
20/// long-lived state.
21///
22/// Not `Debug` because `Graph` is not `Debug` (its `petgraph` backing
23/// type is opaque on purpose). Consumers wanting to log a request
24/// should log the `intent` and signal-presence flags separately.
25#[derive(Clone)]
26pub struct ProjectionRequest<'a> {
27    pub graph: &'a kernel::graph::Graph,
28    pub signals: &'a IntelligenceSignals,
29    pub intent: ViewIntent,
30}
31
32/// What the user is trying to see right now.
33///
34/// `ViewIntent` is the **only** call-site way to tell a strategy what
35/// kind of map it should produce. Strategies should treat it as
36/// declarative: the same intent should yield the same projection shape
37/// for the same `(graph, signals)` pair.
38#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
39pub struct ViewIntent {
40    pub form_factor: FormFactor,
41    pub dimension: ProjectionDimension,
42    pub focus: Option<NodeKey>,
43    pub filter: Option<NodeFilter>,
44    pub target_size: TargetSize,
45    /// Per-node axis values for axial strategies (Timeline, Kanban).
46    /// Lives on the intent (not on [`IntelligenceSignals`]) because
47    /// "this node's place on the time axis is X" is a *view-config*
48    /// decision about how to map graph nodes to an axis, not an
49    /// emergent statistical signal.
50    #[serde(default)]
51    pub axis_values: Option<HashMap<NodeKey, AxisValue>>,
52    /// Per-node visual extents `(w, h)` in target-size units — what each
53    /// node's representation occupies, so extent-aware strategies can
54    /// space placements to clear them (the projection-proofs P1 finding:
55    /// a position-only contract cannot avoid overlap). View-config like
56    /// `axis_values`: the host measures, the strategy places. Strategies
57    /// that ignore extents behave as before (additive contract).
58    #[serde(default)]
59    pub extents: Option<HashMap<NodeKey, (f32, f32)>>,
60}
61
62/// Host-provided axis coordinate for axial strategies that project onto
63/// one or two explicit axes (Timeline, Kanban, future axial variants).
64///
65/// Mirrors [`graph_layout::AxisValue`] so the cartography
66/// contract stays decoupled from graph-canvas's internals; the
67/// adapter for each axial strategy maps between them.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub enum AxisValue {
70    /// Numeric coordinate. Ordered relatively; strategies map to world
71    /// units via their own scale config.
72    Numeric(f64),
73    /// Categorical tag. Groups nodes into buckets by tag; strategies
74    /// pick bucket ordering from their config.
75    Categorical(String),
76}
77
78/// What surface the projection is destined for.
79///
80/// Strategies can specialize on this — a `Minimap` form factor should
81/// strip detail overlays; a `Volvelle` form factor should prefer
82/// radial layouts; an `Astroid` form factor expects hub-collapse.
83#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
84pub enum FormFactor {
85    /// Default: a full-size graph view (orrery root, workbench tile).
86    #[default]
87    Canvas,
88    /// The cosmos form: a whole mere seen at once, special-cased so
89    /// strategies can emphasize map-shape over network-shape. See lexicon:
90    /// *orrery* (a form factor, narrowed 2026-07-26; the tier-1 sense it used
91    /// to carry is now *your root mere*).
92    Orrery,
93    /// Expanded-moot radial form. See lexicon: *volvelle*.
94    Volvelle,
95    /// Hub-collapsed view. See lexicon: *astroid*.
96    Astroid,
97    /// Thumbnail/minimap projection. Strategies strip detail and emit
98    /// a [`crate::MinimapDescriptor`] on the resulting
99    /// [`crate::Projection`].
100    Minimap,
101}
102
103/// Which projection dimension to render in.
104///
105/// `(x, y)` is identical across all variants; the `z` axis (when
106/// applicable) is metadata-driven, not strategy-driven. This is the
107/// *position parity contract* inherited from the graphshell field
108/// algebra plan and the Mere field algebra plan.
109#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
110pub enum ProjectionDimension {
111    #[default]
112    TwoD,
113    /// 2.5D — top-down with depth illusion. `z` is decorative.
114    TwoPointFive,
115    /// Discrete depth layers. `z` is quantized.
116    Isometric,
117    /// Full reorientable 3D. `z` is semantic.
118    ThreeD,
119}
120
121/// Subset filter applied before strategy projection.
122///
123/// Cartography is responsible for materializing the filtered subgraph
124/// reference handed to the strategy; the strategy operates on the
125/// already-filtered set.
126#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
127pub enum NodeFilter {
128    /// Only nodes within `hops` of `center` in the undirected graph.
129    Neighborhood { center: NodeKey, hops: u32 },
130    /// Only nodes carrying any of the listed tag strings.
131    Tagged(Vec<String>),
132    /// Only the explicit node set (used for "show selection" views).
133    Explicit(Vec<NodeKey>),
134}
135
136/// Target render size for the projection.
137///
138/// `Pixels` for canvas-bound projections, `Logical` for minimaps and
139/// abstract diagrams. Strategies pick spring constants / scaling /
140/// label density based on this.
141#[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize)]
142pub enum TargetSize {
143    /// Default: render at a logical reference size (480×360).
144    #[default]
145    Default,
146    /// Pixels — for direct canvas binding at known DP dimensions.
147    Pixels { width: u32, height: u32 },
148    /// Logical — for minimap thumbnails and resolution-independent
149    /// projections.
150    Logical { width: f32, height: f32 },
151}
152
153impl ViewIntent {
154    /// Convenience builder for the most common case: a canvas-bound
155    /// view at known pixel dimensions.
156    pub fn canvas_pixels(width: u32, height: u32) -> Self {
157        Self {
158            form_factor: FormFactor::Canvas,
159            dimension: ProjectionDimension::TwoD,
160            focus: None,
161            filter: None,
162            target_size: TargetSize::Pixels { width, height },
163            axis_values: None,
164            extents: None,
165        }
166    }
167
168    /// Convenience builder for a minimap.
169    pub fn minimap(width: f32, height: f32) -> Self {
170        Self {
171            form_factor: FormFactor::Minimap,
172            dimension: ProjectionDimension::TwoD,
173            focus: None,
174            filter: None,
175            target_size: TargetSize::Logical { width, height },
176            axis_values: None,
177            extents: None,
178        }
179    }
180
181    pub fn with_focus(mut self, focus: NodeKey) -> Self {
182        self.focus = Some(focus);
183        self
184    }
185
186    pub fn with_filter(mut self, filter: NodeFilter) -> Self {
187        self.filter = Some(filter);
188        self
189    }
190
191    pub fn with_axis_values(mut self, values: HashMap<NodeKey, AxisValue>) -> Self {
192        self.axis_values = Some(values);
193        self
194    }
195}
196
197impl TargetSize {
198    /// Logical-unit dimensions for whichever variant we are.
199    /// Pixel-bound sizes round to f32 for layout math.
200    pub fn logical_size(self) -> PortableSize {
201        match self {
202            TargetSize::Default => PortableSize::new(480.0, 360.0),
203            TargetSize::Pixels { width, height } => PortableSize::new(width as f32, height as f32),
204            TargetSize::Logical { width, height } => PortableSize::new(width, height),
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn view_intent_canvas_pixels_builder_sets_pixel_target() {
215        let intent = ViewIntent::canvas_pixels(800, 600);
216        assert_eq!(intent.form_factor, FormFactor::Canvas);
217        assert_eq!(intent.dimension, ProjectionDimension::TwoD);
218        assert!(intent.focus.is_none());
219        assert_eq!(
220            intent.target_size,
221            TargetSize::Pixels {
222                width: 800,
223                height: 600
224            }
225        );
226    }
227
228    #[test]
229    fn view_intent_minimap_builder_sets_minimap_form_factor() {
230        let intent = ViewIntent::minimap(120.0, 90.0);
231        assert_eq!(intent.form_factor, FormFactor::Minimap);
232        assert_eq!(
233            intent.target_size,
234            TargetSize::Logical {
235                width: 120.0,
236                height: 90.0
237            }
238        );
239    }
240
241    #[test]
242    fn target_size_default_logical_size_is_reference() {
243        let s = TargetSize::Default.logical_size();
244        assert_eq!(s.width, 480.0);
245        assert_eq!(s.height, 360.0);
246    }
247}