Skip to main content

kernel/graph/
display.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! A human-meaningful **display label** for a node.
5//!
6//! Linked-data ingest mints a node per JSON-LD subject and per referenced
7//! resource (see `linked-data`): a page's `author` / `publisher` / `image` and
8//! the like. Anonymous subjects (no `@id`) are skolemized to `urn:mere:bnode:…`,
9//! and `add_node_with_id` seeds an untitled node's `title` to its URL, so a naive
10//! `title`-or-URL label shows that raw URN (or a bare image URL) on the canvas and
11//! in the roster. This derives something a person can read instead, from data the
12//! node already carries.
13//!
14//! The derivation **branches on node kind**, which is what keeps it honest: a
15//! linked page reached by a `hyperlink` edge must not be labelled "hyperlink", so
16//! the incoming-edge *role* is consulted only for anonymous entities, where the
17//! role (`author` / `publisher` / `image`) genuinely is the node's identity.
18//!
19//! - **Anonymous entity** (`urn:mere:bnode:…`): real title → incoming-edge role →
20//!   humanized `@type` → a short id.
21//! - **Real resource** (an addressable URL): real title → filename (a URL's last
22//!   path segment when it carries an extension, e.g. `Rust_logo.svg`) →
23//!   cached host → humanized `@type` → the scheme-stripped URL.
24//!
25//! It is presentation-neutral (deterministic graph-derived text, no theme/host
26//! types) and recomputed on read, so ingest stays faithful and the label is free
27//! to evolve. Truncation to a widget's width is the caller's concern.
28
29use crate::graph::Graph;
30use crate::graph::identity::NodeKey;
31use crate::types::ClassificationScheme;
32
33/// The skolemized-blank-node URI prefix (`linked_data::ingest::skolemize`).
34const BNODE_PREFIX: &str = "urn:mere:bnode:";
35
36impl Graph {
37    /// A human-meaningful label for `key`'s node (see the module docs for the
38    /// derivation). Empty string if the key is not in the graph. Full text, not
39    /// width-clamped: a caller drawing into a fixed box truncates.
40    pub fn node_display_label(&self, key: NodeKey) -> String {
41        let Some(node) = self.get_node(key) else {
42            return String::new();
43        };
44        let url = node.url();
45
46        // A real title (one that is not just the seeded copy of the URL) is always
47        // the best label: a page's `<title>`, or an entity's `schema:name`.
48        let title = node.title.trim();
49        if !title.is_empty() && title != url {
50            return title.to_string();
51        }
52
53        if let Some(stripped) = url.strip_prefix(BNODE_PREFIX) {
54            // Anonymous linked-data entity: name it by its role to its referrer
55            // (author / publisher / image), then by its type, then a short id.
56            self.incoming_role(key)
57                .or_else(|| first_type_term(self, key))
58                .unwrap_or_else(|| short_blank_id(stripped))
59        } else {
60            // Addressable resource: a filename, else its derived host, else its
61            // type, else the scheme-stripped URL.
62            url_filename(url)
63                .or_else(|| host_of(url))
64                .or_else(|| first_type_term(self, key))
65                .unwrap_or_else(|| scheme_stripped(url))
66        }
67    }
68
69    /// The humanized role of `key`'s first meaningful incoming edge: the local term
70    /// of its predicate IRI (`https://schema.org/author` → `author`). Skips
71    /// structural link predicates (`hyperlink` / `references`) that describe the
72    /// link, not the node. `None` if no incoming edge carries a usable predicate.
73    fn incoming_role(&self, key: NodeKey) -> Option<String> {
74        for src in self.in_neighbors(key) {
75            let Some(edge_key) = self.find_edge_key(src, key) else {
76                continue;
77            };
78            let Some(sem) = self.get_edge(edge_key).and_then(|p| p.semantic_data()) else {
79                continue;
80            };
81            // The open predicate IRI (raw web predicate from ingest), or the
82            // canonical IRI of a recognized sub-kind for a natively-asserted edge.
83            let iri = sem
84                .statements()
85                .iter()
86                .map(|statement| statement.predicate.clone())
87                .next()
88                .or_else(|| {
89                    sem.predicate.clone().or_else(|| {
90                        sem.sub_kinds
91                            .iter()
92                            .next()
93                            .map(|&sk| super::predicate_iri(sk).to_string())
94                    })
95                })?;
96            let term = iri_term(&iri);
97            if term.is_empty() || term == "hyperlink" || term == "references" {
98                continue;
99            }
100            return Some(humanize_term(term));
101        }
102        None
103    }
104}
105
106/// The humanized local term of the node's first `rdf:type` classification
107/// (`https://schema.org/Organization` → `Organization`, `…/ImageObject` →
108/// `Image Object`). `None` if the node carries no ingested `@type`.
109fn first_type_term(graph: &Graph, key: NodeKey) -> Option<String> {
110    graph
111        .node_classifications(key)?
112        .iter()
113        .find(|c| matches!(&c.scheme, ClassificationScheme::Custom(s) if s == "rdf:type"))
114        .map(|c| humanize_term(iri_term(&c.value)))
115        .filter(|t| !t.is_empty())
116}
117
118/// The local term of an IRI: its fragment or last path segment
119/// (`https://schema.org/author` → `author`, `…/rel#cites` → `cites`).
120fn iri_term(iri: &str) -> &str {
121    iri.rsplit(['#', '/']).next().unwrap_or(iri)
122}
123
124/// Humanize a vocabulary term for display: split `camelCase` and `-` / `_`
125/// boundaries into spaces (`ImageObject` → `Image Object`, `thumbnail_url` →
126/// `thumbnail url`), leaving an already-plain term (`author`) unchanged.
127fn humanize_term(term: &str) -> String {
128    let mut out = String::with_capacity(term.len() + 4);
129    let mut prev_alnum = false;
130    for ch in term.chars() {
131        if ch == '-' || ch == '_' {
132            if prev_alnum {
133                out.push(' ');
134            }
135            prev_alnum = false;
136            continue;
137        }
138        if ch.is_uppercase() && prev_alnum && !out.ends_with(' ') {
139            out.push(' ');
140        }
141        out.push(ch);
142        // A lowercase letter or digit before an uppercase marks a camelCase break.
143        prev_alnum = ch.is_alphanumeric() && !ch.is_uppercase();
144    }
145    out.trim().to_string()
146}
147
148/// A fetchable URL's filename: its last non-empty path segment when that segment
149/// carries a file extension (`…/Rust_logo.svg` → `Rust_logo.svg`). `None` for a
150/// directory URL or an extensionless page slug (which falls through to the host).
151fn url_filename(url: &str) -> Option<String> {
152    let parsed = url::Url::parse(url).ok()?;
153    let last = parsed
154        .path_segments()?
155        .filter(|s| !s.is_empty())
156        .next_back()?;
157    let dot = last.rfind('.')?;
158    // A real extension: a dot with non-empty name and extension around it.
159    if dot > 0 && dot + 1 < last.len() {
160        Some(last.to_string())
161    } else {
162        None
163    }
164}
165
166/// The host of a URL (`https://en.wikipedia.org/wiki/Foo` → `en.wikipedia.org`),
167/// for a node whose `cached_host` was never computed (an ingested resource node).
168fn host_of(url: &str) -> Option<String> {
169    url::Url::parse(url).ok()?.host_str().map(str::to_string)
170}
171
172/// A short tail for an anonymous node when nothing better is known: the blank
173/// label after the leading document-hash namespace (`<16hex>:_:b3` → `node _:b3`).
174/// The namespace is the first colon segment; the blank label itself may contain a
175/// colon (`_:b3`), so split only off the namespace.
176fn short_blank_id(stripped: &str) -> String {
177    let label = stripped
178        .split_once(':')
179        .map(|(_, rest)| rest)
180        .unwrap_or(stripped);
181    format!("node {label}")
182}
183
184/// A URL with its scheme dropped, capped to a sane label width.
185fn scheme_stripped(url: &str) -> String {
186    let body = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);
187    body.chars().take(48).collect()
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use crate::types::{
194        ClassificationProvenance, ClassificationScheme, ClassificationStatus, NodeClassification,
195    };
196    use euclid::default::Point2D;
197    use uuid::Uuid;
198
199    fn rdf_type(iri: &str) -> NodeClassification {
200        NodeClassification {
201            scheme: ClassificationScheme::Custom("rdf:type".to_string()),
202            value: iri.to_string(),
203            label: None,
204            confidence: 1.0,
205            provenance: ClassificationProvenance::Imported,
206            status: ClassificationStatus::Imported,
207            primary: false,
208        }
209    }
210
211    fn add(graph: &mut Graph, url: &str) -> NodeKey {
212        graph.add_node_with_id(
213            Graph::node_namespace_id(url),
214            url.to_string(),
215            Point2D::zero(),
216        )
217    }
218
219    #[test]
220    fn real_title_wins_for_any_node() {
221        let mut g = Graph::new();
222        let page = add(&mut g, "https://ex.test/article");
223        g.get_node_mut(page).unwrap().title = "Rust (programming language)".to_string();
224        assert_eq!(g.node_display_label(page), "Rust (programming language)");
225    }
226
227    #[test]
228    fn anonymous_entity_falls_to_incoming_role_then_type() {
229        let mut g = Graph::new();
230        let page = add(&mut g, "https://ex.test/article");
231        // A nameless publisher blank node typed Organization, reached via publisher.
232        let publisher = add(&mut g, "urn:mere:bnode:deadbeefdeadbeef:_:b0");
233        g.add_node_classification(publisher, rdf_type("https://schema.org/Organization"));
234        g.assert_semantic_predicate(page, publisher, "https://schema.org/publisher".to_string());
235        // Role wins over type.
236        assert_eq!(g.node_display_label(publisher), "publisher");
237
238        // With no incoming edge, the same node falls to its humanized @type.
239        let author = add(&mut g, "urn:mere:bnode:deadbeefdeadbeef:_:b1");
240        g.add_node_classification(author, rdf_type("https://schema.org/ImageObject"));
241        assert_eq!(g.node_display_label(author), "Image Object");
242    }
243
244    #[test]
245    fn anonymous_entity_with_a_name_uses_the_name() {
246        let mut g = Graph::new();
247        let page = add(&mut g, "https://ex.test/article");
248        let publisher = add(&mut g, "urn:mere:bnode:deadbeefdeadbeef:_:b0");
249        g.get_node_mut(publisher).unwrap().title = "Wikimedia Foundation".to_string();
250        g.assert_semantic_predicate(page, publisher, "https://schema.org/publisher".to_string());
251        assert_eq!(g.node_display_label(publisher), "Wikimedia Foundation");
252    }
253
254    #[test]
255    fn image_resource_uses_its_filename() {
256        let mut g = Graph::new();
257        let img = add(&mut g, "https://upload.example.test/wiki/Rust_logo.svg");
258        assert_eq!(g.node_display_label(img), "Rust_logo.svg");
259    }
260
261    #[test]
262    fn extensionless_page_falls_to_its_host() {
263        let mut g = Graph::new();
264        let page = add(
265            &mut g,
266            "https://en.wikipedia.org/wiki/Rust_(programming_language)",
267        );
268        // No extension on the slug, so the derived host wins.
269        assert_eq!(g.node_display_label(page), "en.wikipedia.org");
270    }
271
272    #[test]
273    fn resource_host_is_derived_from_url() {
274        let mut g = Graph::new();
275        let url = "https://en.wikipedia.org/wiki/Rust_(programming_language)";
276        let key = add(&mut g, url);
277        assert_eq!(g.node_display_label(key), "en.wikipedia.org");
278    }
279
280    #[test]
281    fn anonymous_with_nothing_known_gets_a_short_id() {
282        let mut g = Graph::new();
283        let blank = add(&mut g, "urn:mere:bnode:deadbeefdeadbeef:_:b7");
284        assert_eq!(g.node_display_label(blank), "node _:b7");
285    }
286}