Skip to main content

kernel/
verso_address.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Verso URI scheme parsing — `verso://`, `graphshell://`, `graph://`,
5//! `node://`, `notes://`. Includes the address types that the rest of
6//! Graphshell uses to address durable subsystem surfaces (settings
7//! pages, frame-by-id, tile-group-by-id, view targets, tool panes,
8//! clip captures, plus generic graph/node/note addresses).
9//!
10//! Promoted from `graphshell::util` per Slice 56 — these types were
11//! pure URI-string parsing (no egui, no euclid) but lived next to the
12//! `CoordBridge` egui-glue trait in `util.rs`, which forced every
13//! portable consumer (the viewer registry, several services, action
14//! routing, settings persistence) to reach into the binary root for a
15//! primitive. The egui-flavored `CoordBridge` trait stayed behind in
16//! `util.rs`.
17
18use std::fmt;
19
20pub const VERSO_SCHEME_PREFIX: &str = "verso://";
21pub const GRAPHSHELL_SCHEME_PREFIX: &str = "graphshell://";
22pub const GRAPH_SCHEME_PREFIX: &str = "graph://";
23pub const NODE_SCHEME_PREFIX: &str = "node://";
24pub const NOTES_SCHEME_PREFIX: &str = "notes://";
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum VersoAddress {
28    Settings(GraphshellSettingsPath),
29    Frame(String),
30    TileGroup(String),
31    View(VersoViewTarget),
32    Tool {
33        name: String,
34        instance: Option<u32>,
35    },
36    Clip(String),
37    Other {
38        category: String,
39        segments: Vec<String>,
40    },
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum VersoViewTarget {
45    Legacy(String),
46    Graph(String),
47    Node(String),
48    Note(String),
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum GraphshellSettingsPath {
53    General,
54    Persistence,
55    Physics,
56    Sync,
57    Appearance,
58    Keybindings,
59    Advanced,
60    History,
61    Other(String),
62}
63
64impl VersoAddress {
65    pub fn parse(input: &str) -> Option<Self> {
66        let normalized = normalize_internal_uri(input)?;
67        let tail = normalized
68            .strip_prefix(VERSO_SCHEME_PREFIX)
69            .or_else(|| normalized.strip_prefix(GRAPHSHELL_SCHEME_PREFIX))?;
70        let mut segments = tail
71            .split('/')
72            .filter(|segment| !segment.is_empty())
73            .map(str::to_string);
74        let category = segments.next()?;
75
76        match category.as_str() {
77            "settings" => {
78                let settings_path = match segments.next() {
79                    None => GraphshellSettingsPath::General,
80                    Some(segment) => GraphshellSettingsPath::from_segment(&segment),
81                };
82                Some(Self::Settings(settings_path))
83            }
84            "frame" => Some(Self::Frame(segments.next()?)),
85            "tile-group" => Some(Self::TileGroup(segments.next()?)),
86            "view" => {
87                let first = segments.next()?;
88                match segments.next() {
89                    None => Some(Self::View(VersoViewTarget::Legacy(first))),
90                    Some(target_id) => {
91                        let view_target = match first.as_str() {
92                            "graph" => VersoViewTarget::Graph(target_id),
93                            "node" => VersoViewTarget::Node(target_id),
94                            "note" => VersoViewTarget::Note(target_id),
95                            _ => {
96                                let mut preserved_segments = vec![first, target_id];
97                                preserved_segments.extend(segments);
98                                return Some(Self::Other {
99                                    category,
100                                    segments: preserved_segments,
101                                });
102                            }
103                        };
104                        Some(Self::View(view_target))
105                    }
106                }
107            }
108            "tool" => {
109                let name = segments.next()?;
110                let instance = segments
111                    .next()
112                    .and_then(|segment| segment.parse::<u32>().ok());
113                Some(Self::Tool { name, instance })
114            }
115            "clip" => Some(Self::Clip(segments.next()?)),
116            _ => Some(Self::Other {
117                category,
118                segments: segments.collect(),
119            }),
120        }
121    }
122
123    pub fn is_settings(&self) -> bool {
124        matches!(self, Self::Settings(_))
125    }
126
127    pub fn settings(path: GraphshellSettingsPath) -> Self {
128        Self::Settings(path)
129    }
130
131    pub fn frame(frame_id: impl Into<String>) -> Self {
132        Self::Frame(frame_id.into())
133    }
134
135    pub fn tile_group(group_id: impl Into<String>) -> Self {
136        Self::TileGroup(group_id.into())
137    }
138
139    pub fn view(view_id: impl Into<String>) -> Self {
140        Self::View(VersoViewTarget::Legacy(view_id.into()))
141    }
142
143    pub fn view_graph(graph_id: impl Into<String>) -> Self {
144        Self::View(VersoViewTarget::Graph(graph_id.into()))
145    }
146
147    pub fn view_node(node_id: impl Into<String>) -> Self {
148        Self::View(VersoViewTarget::Node(node_id.into()))
149    }
150
151    pub fn view_note(note_id: impl Into<String>) -> Self {
152        Self::View(VersoViewTarget::Note(note_id.into()))
153    }
154
155    pub fn tool(name: impl Into<String>, instance: Option<u32>) -> Self {
156        Self::Tool {
157            name: name.into(),
158            instance,
159        }
160    }
161
162    pub fn clip(clip_id: impl Into<String>) -> Self {
163        Self::Clip(clip_id.into())
164    }
165
166    pub fn inferred_mime_hint(&self) -> &'static str {
167        match self {
168            Self::Settings(_) => "application/x-graphshell-settings",
169            Self::Frame(_)
170            | Self::TileGroup(_)
171            | Self::View(_)
172            | Self::Tool { .. }
173            | Self::Clip(_)
174            | Self::Other { .. } => "application/x-graphshell-internal",
175        }
176    }
177}
178
179impl GraphshellSettingsPath {
180    fn from_segment(segment: &str) -> Self {
181        match segment {
182            "general" => Self::General,
183            "persistence" => Self::Persistence,
184            "physics" => Self::Physics,
185            "sync" => Self::Sync,
186            "appearance" => Self::Appearance,
187            "keybindings" => Self::Keybindings,
188            "advanced" => Self::Advanced,
189            "history" => Self::History,
190            other => Self::Other(other.to_string()),
191        }
192    }
193
194    fn as_segment(&self) -> Option<&str> {
195        match self {
196            Self::General => None,
197            Self::Persistence => Some("persistence"),
198            Self::Physics => Some("physics"),
199            Self::Sync => Some("sync"),
200            Self::Appearance => Some("appearance"),
201            Self::Keybindings => Some("keybindings"),
202            Self::Advanced => Some("advanced"),
203            Self::History => Some("history"),
204            Self::Other(other) => Some(other.as_str()),
205        }
206    }
207}
208
209impl fmt::Display for VersoAddress {
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        match self {
212            Self::Settings(path) => match path.as_segment() {
213                Some(segment) => write!(f, "{VERSO_SCHEME_PREFIX}settings/{segment}"),
214                None => write!(f, "{VERSO_SCHEME_PREFIX}settings"),
215            },
216            Self::Frame(frame_id) => write!(f, "{VERSO_SCHEME_PREFIX}frame/{frame_id}"),
217            Self::TileGroup(group_id) => {
218                write!(f, "{VERSO_SCHEME_PREFIX}tile-group/{group_id}")
219            }
220            Self::View(VersoViewTarget::Legacy(view_id)) => {
221                write!(f, "{VERSO_SCHEME_PREFIX}view/{view_id}")
222            }
223            Self::View(VersoViewTarget::Graph(graph_id)) => {
224                write!(f, "{VERSO_SCHEME_PREFIX}view/graph/{graph_id}")
225            }
226            Self::View(VersoViewTarget::Node(node_id)) => {
227                write!(f, "{VERSO_SCHEME_PREFIX}view/node/{node_id}")
228            }
229            Self::View(VersoViewTarget::Note(note_id)) => {
230                write!(f, "{VERSO_SCHEME_PREFIX}view/note/{note_id}")
231            }
232            Self::Tool { name, instance } => match instance {
233                Some(instance) => write!(f, "{VERSO_SCHEME_PREFIX}tool/{name}/{instance}"),
234                None => write!(f, "{VERSO_SCHEME_PREFIX}tool/{name}"),
235            },
236            Self::Clip(clip_id) => write!(f, "{VERSO_SCHEME_PREFIX}clip/{clip_id}"),
237            Self::Other { category, segments } => {
238                write!(f, "{VERSO_SCHEME_PREFIX}{category}")?;
239                for segment in segments {
240                    write!(f, "/{segment}")?;
241                }
242                Ok(())
243            }
244        }
245    }
246}
247
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct GraphAddress {
250    pub graph_id: String,
251}
252
253impl GraphAddress {
254    pub fn parse(input: &str) -> Option<Self> {
255        let normalized = normalize_scheme_uri(input, GRAPH_SCHEME_PREFIX)?;
256        let graph_id = normalized.strip_prefix(GRAPH_SCHEME_PREFIX)?;
257        (!graph_id.is_empty()).then_some(Self {
258            graph_id: graph_id.to_string(),
259        })
260    }
261
262    pub fn graph(graph_id: impl Into<String>) -> Self {
263        Self {
264            graph_id: graph_id.into(),
265        }
266    }
267}
268
269impl fmt::Display for GraphAddress {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        write!(f, "{GRAPH_SCHEME_PREFIX}{}", self.graph_id)
272    }
273}
274
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct NodeAddress {
277    pub node_id: String,
278}
279
280impl NodeAddress {
281    pub fn parse(input: &str) -> Option<Self> {
282        let normalized = normalize_scheme_uri(input, NODE_SCHEME_PREFIX)?;
283        let node_id = normalized.strip_prefix(NODE_SCHEME_PREFIX)?;
284        (!node_id.is_empty()).then_some(Self {
285            node_id: node_id.to_string(),
286        })
287    }
288
289    pub fn node(node_id: impl Into<String>) -> Self {
290        Self {
291            node_id: node_id.into(),
292        }
293    }
294}
295
296impl fmt::Display for NodeAddress {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        write!(f, "{NODE_SCHEME_PREFIX}{}", self.node_id)
299    }
300}
301
302#[derive(Debug, Clone, PartialEq, Eq)]
303pub struct NoteAddress {
304    pub note_id: String,
305}
306
307impl NoteAddress {
308    pub fn parse(input: &str) -> Option<Self> {
309        let normalized = normalize_scheme_uri(input, NOTES_SCHEME_PREFIX)?;
310        let note_id = normalized.strip_prefix(NOTES_SCHEME_PREFIX)?;
311        (!note_id.is_empty()).then_some(Self {
312            note_id: note_id.to_string(),
313        })
314    }
315
316    pub fn note(note_id: impl Into<String>) -> Self {
317        Self {
318            note_id: note_id.into(),
319        }
320    }
321}
322
323impl fmt::Display for NoteAddress {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        write!(f, "{NOTES_SCHEME_PREFIX}{}", self.note_id)
326    }
327}
328
329fn normalize_internal_uri(input: &str) -> Option<String> {
330    normalize_scheme_uri(input, VERSO_SCHEME_PREFIX)
331        .or_else(|| normalize_scheme_uri(input, GRAPHSHELL_SCHEME_PREFIX))
332}
333
334fn normalize_scheme_uri(input: &str, scheme_prefix: &str) -> Option<String> {
335    let trimmed = input.trim();
336    let no_fragment = trimmed.split('#').next().unwrap_or(trimmed);
337    let no_query = no_fragment.split('?').next().unwrap_or(no_fragment);
338    let normalized = no_query.to_ascii_lowercase();
339    normalized.starts_with(scheme_prefix).then_some(normalized)
340}
341
342/// Truncate a string to `max_chars` characters, appending an ellipsis if truncated.
343/// Uses character counting (not byte length) so it's safe for multi-byte UTF-8.
344pub fn truncate_with_ellipsis(input: &str, max_chars: usize) -> String {
345    if input.chars().count() > max_chars {
346        let truncated: String = input.chars().take(max_chars.saturating_sub(1)).collect();
347        format!("{truncated}\u{2026}")
348    } else {
349        input.to_string()
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356
357    #[test]
358    fn parse_graphshell_settings_history_route() {
359        let parsed = VersoAddress::parse(" graphshell://settings/history ");
360        assert_eq!(
361            parsed,
362            Some(VersoAddress::settings(GraphshellSettingsPath::History))
363        );
364    }
365
366    #[test]
367    fn parse_verso_settings_history_route() {
368        let parsed = VersoAddress::parse(" verso://settings/history ");
369        assert_eq!(
370            parsed,
371            Some(VersoAddress::settings(GraphshellSettingsPath::History))
372        );
373    }
374
375    #[test]
376    fn parse_graphshell_settings_root_as_general() {
377        let parsed = VersoAddress::parse("graphshell://settings");
378        assert_eq!(
379            parsed,
380            Some(VersoAddress::settings(GraphshellSettingsPath::General))
381        );
382    }
383
384    #[test]
385    fn parse_graphshell_unknown_route_preserves_segments() {
386        let parsed = VersoAddress::parse("graphshell://frame/abc123");
387        assert_eq!(parsed, Some(VersoAddress::frame("abc123")));
388    }
389
390    #[test]
391    fn parse_graphshell_tile_group_route() {
392        let parsed = VersoAddress::parse("graphshell://tile-group/group-123");
393        assert_eq!(parsed, Some(VersoAddress::tile_group("group-123")));
394    }
395
396    #[test]
397    fn parse_verso_view_note_route() {
398        let parsed = VersoAddress::parse("verso://view/note/550e8400-e29b-41d4-a716-446655440000");
399        assert_eq!(
400            parsed,
401            Some(VersoAddress::view_note(
402                "550e8400-e29b-41d4-a716-446655440000"
403            ))
404        );
405    }
406
407    #[test]
408    fn parse_graphshell_strips_query_and_fragment() {
409        let parsed = VersoAddress::parse("graphshell://settings/physics?tab=1#focus");
410        assert_eq!(
411            parsed,
412            Some(VersoAddress::settings(GraphshellSettingsPath::Physics))
413        );
414    }
415
416    #[test]
417    fn graphshell_address_display_roundtrips_settings_route() {
418        let address = VersoAddress::settings(GraphshellSettingsPath::Appearance);
419        assert_eq!(address.to_string(), "verso://settings/appearance");
420    }
421
422    #[test]
423    fn parse_graphshell_settings_advanced_route() {
424        let parsed = VersoAddress::parse("graphshell://settings/advanced");
425        assert_eq!(
426            parsed,
427            Some(VersoAddress::settings(GraphshellSettingsPath::Advanced))
428        );
429    }
430
431    #[test]
432    fn graphshell_address_display_roundtrips_other_route() {
433        let address = VersoAddress::frame("abc123");
434        assert_eq!(address.to_string(), "verso://frame/abc123");
435    }
436
437    #[test]
438    fn graphshell_address_display_roundtrips_tile_group_route() {
439        let address = VersoAddress::tile_group("group-123");
440        assert_eq!(address.to_string(), "verso://tile-group/group-123");
441    }
442
443    #[test]
444    fn parse_graphshell_tool_route_with_instance() {
445        let parsed = VersoAddress::parse("graphshell://tool/history/2");
446        assert_eq!(parsed, Some(VersoAddress::tool("history", Some(2))));
447    }
448
449    #[test]
450    fn graphshell_address_display_roundtrips_view_route() {
451        let address = VersoAddress::view("view-123");
452        assert_eq!(address.to_string(), "verso://view/view-123");
453    }
454
455    #[test]
456    fn graphshell_address_display_roundtrips_note_view_route() {
457        let address = VersoAddress::view_note("550e8400-e29b-41d4-a716-446655440000");
458        assert_eq!(
459            address.to_string(),
460            "verso://view/note/550e8400-e29b-41d4-a716-446655440000"
461        );
462    }
463
464    #[test]
465    fn graphshell_address_display_roundtrips_tool_route_without_instance() {
466        let address = VersoAddress::tool("history", None);
467        assert_eq!(address.to_string(), "verso://tool/history");
468    }
469
470    #[test]
471    fn graphshell_address_display_roundtrips_clip_route() {
472        let address = VersoAddress::clip("clip-123");
473        assert_eq!(address.to_string(), "verso://clip/clip-123");
474    }
475
476    #[test]
477    fn parse_note_address_strips_query_and_fragment() {
478        let parsed =
479            NoteAddress::parse(" notes://550e8400-e29b-41d4-a716-446655440000?mode=edit#top ");
480        assert_eq!(
481            parsed,
482            Some(NoteAddress::note("550e8400-e29b-41d4-a716-446655440000"))
483        );
484    }
485
486    #[test]
487    fn note_address_display_roundtrips() {
488        let address = NoteAddress::note("550e8400-e29b-41d4-a716-446655440000");
489        assert_eq!(
490            address.to_string(),
491            "notes://550e8400-e29b-41d4-a716-446655440000"
492        );
493    }
494
495    #[test]
496    fn graph_address_display_roundtrips() {
497        let address = GraphAddress::graph("550e8400-e29b-41d4-a716-446655440000");
498        assert_eq!(
499            address.to_string(),
500            "graph://550e8400-e29b-41d4-a716-446655440000"
501        );
502    }
503
504    #[test]
505    fn node_address_display_roundtrips() {
506        let address = NodeAddress::node("550e8400-e29b-41d4-a716-446655440000");
507        assert_eq!(
508            address.to_string(),
509            "node://550e8400-e29b-41d4-a716-446655440000"
510        );
511    }
512
513    #[test]
514    fn test_short_string_unchanged() {
515        assert_eq!(truncate_with_ellipsis("short", 20), "short");
516    }
517
518    #[test]
519    fn test_long_string_truncated() {
520        let result =
521            truncate_with_ellipsis("this is a very long title that should be truncated", 20);
522        assert_eq!(result.chars().count(), 20);
523        assert!(result.ends_with('\u{2026}'));
524    }
525
526    #[test]
527    fn test_exact_length_unchanged() {
528        assert_eq!(
529            truncate_with_ellipsis("exactly twenty chars", 20),
530            "exactly twenty chars"
531        );
532    }
533
534    #[test]
535    fn test_emoji_safe() {
536        // Emoji are multi-byte but single chars — should not panic
537        let input = "Hello \u{1F600} World! This is long enough to truncate";
538        let result = truncate_with_ellipsis(input, 15);
539        assert!(result.chars().count() <= 15);
540        assert!(result.ends_with('\u{2026}'));
541    }
542
543    #[test]
544    fn test_cjk_safe() {
545        // CJK characters are 3 bytes each — byte slicing would panic
546        let input = "\u{4F60}\u{597D}\u{4E16}\u{754C}\u{4F60}\u{597D}\u{4E16}\u{754C}"; // 8 chars
547        let result = truncate_with_ellipsis(input, 5);
548        assert_eq!(result.chars().count(), 5);
549        assert!(result.ends_with('\u{2026}'));
550    }
551
552    #[test]
553    fn test_empty_string() {
554        assert_eq!(truncate_with_ellipsis("", 20), "");
555    }
556
557    #[test]
558    fn test_max_one() {
559        // Edge case: max_chars = 1, saturating_sub(1) = 0, so just ellipsis
560        let result = truncate_with_ellipsis("hello", 1);
561        assert_eq!(result, "\u{2026}");
562    }
563}