Skip to main content

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