Skip to main content

kernel/
verso_address.rs

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