Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

Studio: multilingual labels in the tree view and property inspector (#64)

ma-bee83ebf3151a6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e194f832..bf71bc3a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -154,6 +154,8 @@ All notable changes to Open Ontologies are documented here.
the validity scan is cut.
### Added
+- **Studio: Multilingual label filter in Tree view.** `TreeView` gains a language chip bar in its header, listing every BCP-47 tag present in the loaded ontology's `rdfs:label` values and shown only when more than one exists. Labels are loaded with full language-tag preservation (two-pass: collect all variants into a `labelMapRef`, then `pickLabel` to build nodes). Switching language relabels the existing React tree state in-place (`relabelTree` walk) — no SPARQL re-query. `nodeMapRef` is also updated so breadcrumbs and connection chips reflect the selected locale. Fallback chain: preferred language → `en` → untagged literal → first available → URI local name.
+- **Studio: Language badges and filter in Property Inspector.** `PropertyInspector` now parses language tags from both engine-native (`"value"@lang`) and standard SPARQL JSON (`xml:lang`) response formats. Each literal row that carries a language tag displays a small monospace badge (e.g. `en`, `cs`) to the right of the value. A language chip bar above the property list (shown only when ≥1 language tag is detected) lets users filter rows to a single locale; URI values are always shown regardless of the filter. `saveEdit` and `deleteProp` include the original language tag in the SPARQL `DELETE`/`INSERT` pattern so editing one locale does not affect sibling translations. The **+ Add** form gains an optional language tag input with quick-pick chips for languages already present on the node.
- **Optional eviction of float32 text vectors from memory**
(`VecStore::with_text_vectors_evicted`, `turbovec` feature). Without it the
TurboQuant backend's compression is a smaller SQLite blob rather than less
@@ -188,6 +190,7 @@ All notable changes to Open Ontologies are documented here.
on the exact scan.
### Fixed
+- **Studio: Tree connector lines — L vs T shape for last children.** The ancestor-continuation-line loop ran `for lvl = 0; lvl < indent`, but `lvl = indent-1` is the same pixel column as the node's own connector (`(indent-1) × INDENT_W + 16`). When the direct parent was not the last child in its group, this drew a full-height vertical at that column, overriding the correct L-shape with a T even for nodes where `isLastChild = true`. Fixed by stopping the ancestor loop at `lvl < indent - 1`; the own connector exclusively owns its column and correctly renders L or T based on `isLastChild`.
- **`search_cosine` and `search_product` no longer clone the entire corpus per
query.** Routing them through the new whole-set accessor initially copied
every float32 vector on every call, which cost 20 ms per query at 20,000 x
diff --git a/studio/src/components/PropertyInspector.tsx b/studio/src/components/PropertyInspector.tsx
index 2ec6b6f7..20e6c5fc 100644
--- a/studio/src/components/PropertyInspector.tsx
+++ b/studio/src/components/PropertyInspector.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useRef } from 'react';
+import { useState, useEffect, useRef, useMemo } from 'react';
import * as mcp from '../lib/mcp-client';
interface Props {
@@ -10,6 +10,7 @@ interface NodeProperty {
predicate: string;
value: string;
valueType: 'uri' | 'literal';
+ language?: string;
predicateLabel: string;
}
@@ -32,7 +33,9 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
const [newPred, setNewPred] = useState('');
const [newVal, setNewVal] = useState('');
const [newValType, setNewValType] = useState<'uri' | 'literal'>('literal');
+ const [newLang, setNewLang] = useState('');
const [saving, setSaving] = useState(false);
+ const [langFilter, setLangFilter] = useState<string>('all');
const editRef = useRef<HTMLInputElement>(null);
const newPredRef = useRef<HTMLInputElement>(null);
@@ -44,55 +47,99 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
try {
const data = JSON.parse(text);
const bindings = data.results?.bindings || data?.results || [];
- // Handle both engine-native format and standard SPARQL JSON
let rows: NodeProperty[] = [];
if (Array.isArray(bindings)) {
- rows = bindings.map((b: Record<string, { value: string; type?: string } | string>) => {
- let pVal: string, oVal: string, oType: 'uri' | 'literal';
+ rows = bindings.map((b: Record<string, { value: string; type?: string; 'xml:lang'?: string } | string>) => {
+ let pVal: string, oVal: string, oType: 'uri' | 'literal', lang: string | undefined;
if (typeof b.p === 'string') {
- // Engine-native: { p: "<uri>", o: "\"lit\"" | "<uri>" }
+ // Engine-native: { p: "<uri>", o: "\"lit\"@en" | "<uri>" }
const ps = b.p as string;
const os = b.o as string;
pVal = ps.startsWith('<') ? ps.slice(1, -1) : ps;
- if ((os as string).startsWith('<')) {
- oVal = (os as string).slice(1, -1);
+ if (os.startsWith('<')) {
+ oVal = os.slice(1, -1);
oType = 'uri';
} else {
- oVal = (os as string).replace(/^"(.*)"(@\w+)?(\^\^.*)?$/, '$1');
+ const m = os.match(/^"((?:[^"\\]|\\.)*)"(?:@([\w-]+))?(?:\^\^.*)?$/);
+ oVal = m ? m[1].replace(/\\"/g, '"') : os;
+ lang = m?.[2] || undefined;
oType = 'literal';
}
} else {
// Standard SPARQL JSON
const pb = b.p as { value: string };
- const ob = b.o as { value: string; type?: string };
+ const ob = b.o as { value: string; type?: string; 'xml:lang'?: string };
pVal = pb?.value || '';
oVal = ob?.value || '';
+ lang = ob?.['xml:lang'] || undefined;
oType = ob?.type === 'uri' ? 'uri' : 'literal';
}
- return { predicate: pVal, value: oVal, valueType: oType, predicateLabel: shortUri(pVal) };
+ return { predicate: pVal, value: oVal, valueType: oType, language: lang, predicateLabel: shortUri(pVal) };
});
}
- // Also parse engine-native flat results array
+ // Engine-native flat results array
if (!Array.isArray(bindings) && Array.isArray(data?.results)) {
rows = (data.results as Record<string, string>[]).map(row => {
const ps = row.p || '';
const os = row.o || '';
const pVal = ps.startsWith('<') ? ps.slice(1, -1) : ps;
- let oVal: string, oType: 'uri' | 'literal';
+ let oVal: string, oType: 'uri' | 'literal', lang: string | undefined;
if (os.startsWith('<')) {
oVal = os.slice(1, -1);
oType = 'uri';
} else {
- oVal = os.replace(/^"(.*)"(@\w+)?(\^\^.*)?$/, '$1');
+ const m = os.match(/^"((?:[^"\\]|\\.)*)"(?:@([\w-]+))?(?:\^\^.*)?$/);
+ oVal = m ? m[1].replace(/\\"/g, '"') : os;
+ lang = m?.[2] || undefined;
oType = 'literal';
}
- return { predicate: pVal, value: oVal, valueType: oType, predicateLabel: shortUri(pVal) };
+ return { predicate: pVal, value: oVal, valueType: oType, language: lang, predicateLabel: shortUri(pVal) };
});
}
setProperties(rows);
} catch { setProperties([]); }
}
+ // Derive available languages from current properties
+ const availableLangs = useMemo(() => {
+ const langs = new Set<string>();
+ for (const p of properties) {
+ if (p.valueType === 'literal' && p.language) langs.add(p.language);
+ }
+ return Array.from(langs).sort();
+ }, [properties]);
+
+ // Reset filter when node changes or new langs appear
+ useEffect(() => {
+ if (langFilter !== 'all' && !availableLangs.includes(langFilter)) {
+ setLangFilter('all');
+ }
+ }, [availableLangs, langFilter]);
+
+ // `editingIdx` is a row index into `visibleProperties`, and the language filter
+ // reshuffles that list underneath it. Left alone, an open edit would resolve to
+ // whichever property had moved into that row and `saveEdit`/`deleteProp` would
+ // run their DELETE/INSERT against the wrong triple, then persist it. The filter
+ // can change without the user touching a chip: the effect above flips it back to
+ // `all` when the last literal of the filtered language is deleted, which is
+ // reachable from the row's own delete button while an edit input is open. It can
+ // also change from a chip click that never blurs the input, as in Tauri's
+ // WKWebView, where buttons do not take focus. Closing the edit is the only
+ // response that cannot write to the wrong row.
+ useEffect(() => {
+ setEditingIdx(null);
+ setAdding(false);
+ }, [langFilter]);
+
+ const visibleProperties = useMemo(() => {
+ if (langFilter === 'all') return properties;
+ return properties.filter(p =>
+ p.valueType === 'uri' ||
+ !p.language ||
+ p.language === langFilter
+ );
+ }, [properties, langFilter]);
+
useEffect(() => {
if (!node) { setProperties([]); setValidationStatus(null); return; }
setEditingIdx(null);
@@ -118,19 +165,30 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
}, [editingIdx]);
useEffect(() => {
- if (adding && newPredRef.current) {
- newPredRef.current.focus();
- }
+ if (adding && newPredRef.current) newPredRef.current.focus();
}, [adding]);
+ function literalPart(prop: NodeProperty): string {
+ if (prop.valueType === 'uri') return `<${prop.value}>`;
+ const escaped = prop.value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
+ return prop.language ? `"${escaped}"@${prop.language}` : `"${escaped}"`;
+ }
+
async function saveEdit(idx: number) {
if (!node) return;
- const prop = properties[idx];
+ const prop = visibleProperties[idx];
if (editValue === prop.value) { setEditingIdx(null); return; }
setSaving(true);
try {
- const oldPart = prop.valueType === 'uri' ? `<${prop.value}>` : `"${prop.value.replace(/"/g, '\\"')}"`;
- const newPart = editValue.startsWith('http') ? `<${editValue}>` : `"${editValue.replace(/"/g, '\\"')}"`;
+ const oldPart = literalPart(prop);
+ // The language tag rides along with the rest of the term. Built through `literalPart` rather than inlining the escapes again: the
+ // DELETE and the INSERT below have to agree about escaping exactly, and two
+ // copies of the rule are two things to keep in step.
+ const newPart = literalPart(
+ editValue.startsWith('http') && prop.valueType !== 'uri'
+ ? { ...prop, valueType: 'uri', value: editValue }
+ : { ...prop, value: editValue },
+ );
await mcp.sparqlUpdate(
`DELETE { <${node.uri}> <${prop.predicate}> ${oldPart} } INSERT { <${node.uri}> <${prop.predicate}> ${newPart} } WHERE {}`
);
@@ -144,10 +202,10 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
async function deleteProp(idx: number) {
if (!node) return;
- const prop = properties[idx];
+ const prop = visibleProperties[idx];
setSaving(true);
try {
- const valPart = prop.valueType === 'uri' ? `<${prop.value}>` : `"${prop.value.replace(/"/g, '\\"')}"`;
+ const valPart = literalPart(prop);
await mcp.sparqlUpdate(`DELETE WHERE { <${node.uri}> <${prop.predicate}> ${valPart} }`);
await mcp.saveGraphToFile();
await loadProperties();
@@ -161,9 +219,13 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
const predUri = newPred.includes(':') && !newPred.startsWith('http')
? expandPrefix(newPred)
: newPred.startsWith('<') ? newPred.slice(1, -1) : newPred;
- const valPart = newValType === 'uri'
- ? `<${newVal.startsWith('<') ? newVal.slice(1, -1) : newVal}>`
- : `"${newVal.replace(/"/g, '\\"')}"`;
+ let valPart: string;
+ if (newValType === 'uri') {
+ valPart = `<${newVal.startsWith('<') ? newVal.slice(1, -1) : newVal}>`;
+ } else {
+ const escaped = newVal.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
+ valPart = newLang.trim() ? `"${escaped}"@${newLang.trim()}` : `"${escaped}"`;
+ }
setSaving(true);
try {
await mcp.sparqlUpdate(`INSERT DATA { <${node.uri}> <${predUri}> ${valPart} }`);
@@ -175,6 +237,7 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
setAdding(false);
setNewPred('');
setNewVal('');
+ setNewLang('');
setNewValType('literal');
}
@@ -199,7 +262,7 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
validationStatus === 'invalid' ? 'var(--error)' : 'var(--bg-panel)',
color: 'var(--bg-primary)',
}}>
- {validationStatus === 'checking' ? '...' :
+ {validationStatus === 'checking' ? '…' :
validationStatus === 'valid' ? 'Valid' :
validationStatus === 'invalid' ? 'Issues' : ''}
</span>
@@ -226,8 +289,35 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
>+ Add</button>
</div>
+ {/* Language filter */}
+ {availableLangs.length > 0 && (
+ <div className="flex flex-wrap gap-1 mb-2">
+ <button
+ onClick={() => setLangFilter('all')}
+ className="px-1.5 py-0.5 rounded text-xs font-mono"
+ style={{
+ background: langFilter === 'all' ? 'var(--accent)' : 'var(--bg-panel)',
+ color: langFilter === 'all' ? 'var(--bg-primary)' : 'var(--text-secondary)',
+ border: '1px solid var(--border)',
+ }}
+ >all</button>
+ {availableLangs.map(lang => (
+ <button
+ key={lang}
+ onClick={() => setLangFilter(lang)}
+ className="px-1.5 py-0.5 rounded text-xs font-mono"
+ style={{
+ background: langFilter === lang ? 'var(--accent)' : 'var(--bg-panel)',
+ color: langFilter === lang ? 'var(--bg-primary)' : 'var(--text-secondary)',
+ border: '1px solid var(--border)',
+ }}
+ >{lang}</button>
+ ))}
+ </div>
+ )}
+
<div className="space-y-0.5">
- {properties.map((prop, i) => (
+ {visibleProperties.map((prop, i) => (
<div key={i} className="flex items-start gap-1 group px-2 py-1 rounded"
style={{ background: 'var(--bg-primary)' }}>
<span className="shrink-0 w-24 truncate" style={{ color: 'var(--accent)' }}
@@ -261,6 +351,21 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
</span>
)}
+ {/* Language tag badge */}
+ {prop.valueType === 'literal' && prop.language && (
+ <span
+ className="shrink-0 px-1 rounded font-mono"
+ style={{
+ background: 'var(--bg-panel)',
+ color: 'var(--accent)',
+ border: '1px solid var(--border)',
+ fontSize: '0.65rem',
+ lineHeight: '1.4',
+ }}
+ title={`Language: ${prop.language}`}
+ >{prop.language}</span>
+ )}
+
<button
className="shrink-0 opacity-0 group-hover:opacity-100 ml-1"
style={{ color: 'var(--error)' }}
@@ -271,8 +376,10 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
</div>
))}
- {properties.length === 0 && (
- <div style={{ color: 'var(--text-secondary)' }} className="px-2 py-1">No properties</div>
+ {visibleProperties.length === 0 && (
+ <div style={{ color: 'var(--text-secondary)' }} className="px-2 py-1">
+ {properties.length > 0 ? `No properties for language "${langFilter}"` : 'No properties'}
+ </div>
)}
</div>
</div>
@@ -282,14 +389,13 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
<div className="rounded p-2 space-y-2" style={{ background: 'var(--bg-primary)', border: '1px solid var(--border)' }}>
<div className="font-medium" style={{ color: 'var(--text-secondary)' }}>New property</div>
- {/* Predicate input with quick-pick */}
<div>
<div style={{ color: 'var(--text-secondary)' }} className="mb-1">Predicate</div>
<input
ref={newPredRef}
className="w-full px-2 py-1 rounded outline-none text-xs"
style={{ background: 'var(--bg-panel)', color: 'var(--text-primary)', border: '1px solid var(--border)' }}
- placeholder="rdfs:label or full URI..."
+ placeholder="rdfs:label or full URI…"
value={newPred}
onChange={e => setNewPred(e.target.value)}
onKeyDown={e => { if (e.key === 'Escape') setAdding(false); }}
@@ -310,7 +416,6 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
</div>
</div>
- {/* Value input */}
<div>
<div className="flex items-center gap-2 mb-1">
<span style={{ color: 'var(--text-secondary)' }}>Value</span>
@@ -336,7 +441,7 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
<input
className="w-full px-2 py-1 rounded outline-none text-xs"
style={{ background: 'var(--bg-panel)', color: 'var(--text-primary)', border: '1px solid var(--border)' }}
- placeholder={newValType === 'uri' ? 'http://...' : 'value...'}
+ placeholder={newValType === 'uri' ? 'http://…' : 'value…'}
value={newVal}
onChange={e => setNewVal(e.target.value)}
onKeyDown={e => {
@@ -346,6 +451,42 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
/>
</div>
+ {/* Language tag input — only for literals */}
+ {newValType === 'literal' && (
+ <div>
+ <div style={{ color: 'var(--text-secondary)' }} className="mb-1">Language tag <span style={{ color: 'var(--text-secondary)', opacity: 0.6 }}>(optional)</span></div>
+ <div className="flex gap-1.5 items-center">
+ <input
+ className="w-20 px-2 py-1 rounded outline-none text-xs font-mono"
+ style={{ background: 'var(--bg-panel)', color: 'var(--text-primary)', border: '1px solid var(--border)' }}
+ placeholder="en, fr, de…"
+ value={newLang}
+ onChange={e => setNewLang(e.target.value.toLowerCase())}
+ onKeyDown={e => {
+ if (e.key === 'Enter') addProperty();
+ if (e.key === 'Escape') setAdding(false);
+ }}
+ />
+ {availableLangs.length > 0 && (
+ <div className="flex flex-wrap gap-1">
+ {availableLangs.map(lang => (
+ <button
+ key={lang}
+ onClick={() => setNewLang(lang)}
+ className="px-1.5 py-0.5 rounded text-xs font-mono"
+ style={{
+ background: newLang === lang ? 'var(--accent)' : 'var(--bg-panel)',
+ color: newLang === lang ? 'var(--bg-primary)' : 'var(--text-secondary)',
+ border: '1px solid var(--border)',
+ }}
+ >{lang}</button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
<div className="flex gap-2">
<button
className="flex-1 py-1 rounded text-xs font-medium"
@@ -356,7 +497,7 @@ export function PropertyInspector({ node, onGraphChanged }: Props) {
<button
className="flex-1 py-1 rounded text-xs"
style={{ background: 'var(--bg-panel)', color: 'var(--text-secondary)', border: '1px solid var(--border)' }}
- onClick={() => { setAdding(false); setNewPred(''); setNewVal(''); }}
+ onClick={() => { setAdding(false); setNewPred(''); setNewVal(''); setNewLang(''); }}
>Cancel</button>
</div>
</div>
diff --git a/studio/src/components/TreeView.tsx b/studio/src/components/TreeView.tsx
index f3e7835b..b0b71aaf 100644
--- a/studio/src/components/TreeView.tsx
+++ b/studio/src/components/TreeView.tsx
@@ -7,9 +7,12 @@ interface TreeViewProps {
}
interface SparqlBinding {
- [key: string]: { type: string; value: string };
+ [key: string]: { type: string; value: string; lang?: string };
}
+type LabelEntry = { value: string; lang?: string };
+type LabelMap = Map<string, LabelEntry[]>;
+
type NodeType = 'Class' | 'ObjectProperty' | 'DatatypeProperty' | 'Individual';
interface TreeNode {
@@ -26,16 +29,21 @@ interface TreeNode {
function parseSparqlResults(text: string): SparqlBinding[] {
try {
const parsed = JSON.parse(text);
- const rows: Record<string, string>[] = parsed?.results ?? [];
+ const rows: Record<string, unknown>[] = parsed?.results ?? [];
return rows.map(row => {
const binding: SparqlBinding = {};
for (const [key, val] of Object.entries(row)) {
- const s = String(val);
- if (s.startsWith('<') && s.endsWith('>')) {
- binding[key] = { type: 'uri', value: s.slice(1, -1) };
+ if (val && typeof val === 'object' && 'value' in val) {
+ const v = val as Record<string, string>;
+ binding[key] = { type: v.type ?? 'literal', value: v.value ?? '', lang: v['xml:lang'] || undefined };
} else {
- const unquoted = s.replace(/^"(.*)"(@\w+)?(\^\^.*)?$/, '$1').replace(/\\"/g, '"');
- binding[key] = { type: 'literal', value: unquoted };
+ const s = String(val);
+ if (s.startsWith('<') && s.endsWith('>')) {
+ binding[key] = { type: 'uri', value: s.slice(1, -1) };
+ } else {
+ const m = s.match(/^"((?:[^"\\]|\\.)*)"(?:@([\w-]+))?(?:\^\^.*)?$/);
+ binding[key] = { type: 'literal', value: m ? m[1].replace(/\\"/g, '"') : s, lang: m?.[2] || undefined };
+ }
}
}
return binding;
@@ -45,6 +53,29 @@ function parseSparqlResults(text: string): SparqlBinding[] {
}
}
+function pickLabel(labels: LabelEntry[], preferred: string, fallbackUri: string): string {
+ if (labels.length === 0) return shortUri(fallbackUri);
+ const find = (tag: string) => labels.find(l => (l.lang ?? '') === tag);
+ return find(preferred)?.value ?? find('en')?.value ?? labels.find(l => !l.lang)?.value ?? labels[0].value ?? shortUri(fallbackUri);
+}
+
+function addLabel(map: LabelMap, uri: string, entry: LabelEntry) {
+ if (!entry.value) return;
+ if (!map.has(uri)) map.set(uri, []);
+ const arr = map.get(uri)!;
+ if (!arr.some(e => e.value === entry.value && e.lang === entry.lang)) arr.push(entry);
+}
+
+function relabelTree(nodes: TreeNode[], lmap: LabelMap, lang: string): TreeNode[] {
+ return nodes.map(n => {
+ const children = relabelTree(n.children, lmap, lang);
+ if (n.id.startsWith('__')) return { ...n, children };
+ const labels = lmap.get(n.uri) ?? [];
+ const label = labels.length > 0 ? pickLabel(labels, lang, n.uri) : n.label;
+ return { ...n, label, children };
+ });
+}
+
function shortUri(uri: string): string {
const hash = uri.lastIndexOf('#');
if (hash >= 0) return uri.slice(hash + 1);
@@ -165,6 +196,17 @@ export function TreeView({ onNodeSelect }: TreeViewProps) {
const [connections, setConnections] = useState<{ label: string; targetId: string; targetLabel: string }[]>([]);
const [versionStack, setVersionStack] = useState<string[]>([]);
const [undoInProgress, setUndoInProgress] = useState(false);
+ const [langFilter, setLangFilter] = useState<string>('en');
+ // `loadTree` is published as `window.__refreshGraph` and re-runs after every
+ // mutation, so it must not close over `langFilter`: with the value captured in
+ // its dependency array it would rebuild every label at the mount-time locale
+ // while the selected chip stayed highlighted, and the `[langFilter]` relabel
+ // effect would not re-fire because the state had not changed. Reading through
+ // a ref keeps the current locale available without making the reload depend on
+ // it, which is what lets a language switch stay a relabel rather than a
+ // re-query.
+ const langFilterRef = useRef<string>('en');
+ const [availableLangs, setAvailableLangs] = useState<string[]>([]);
const scrollRef = useRef<HTMLDivElement>(null);
const [scrollTop, setScrollTop] = useState(0);
const [viewHeight, setViewHeight] = useState(600);
@@ -172,6 +214,7 @@ export function TreeView({ onNodeSelect }: TreeViewProps) {
// Node lookup for connections
const nodeMapRef = useRef<Map<string, { label: string; uri: string; nodeType: NodeType }>>(new Map());
+ const labelMapRef = useRef<LabelMap>(new Map());
const loadTree = useCallback(async () => {
try {
@@ -183,21 +226,45 @@ export function TreeView({ onNodeSelect }: TreeViewProps) {
mcp.sparqlQuery(QUERIES.individuals),
]);
+ // Pass 1: collect all label variants for every entity
+ const lmap: LabelMap = new Map();
+ const classBindings = parseSparqlResults(classesText);
+ const objPropBindings = parseSparqlResults(objPropsText);
+ const dataPropBindings = parseSparqlResults(dataPropsText);
+ const individualBindings = parseSparqlResults(individualsText);
+
+ for (const b of classBindings) { if (b.c?.value && b.label?.value) addLabel(lmap, b.c.value, { value: b.label.value, lang: b.label.lang }); }
+ for (const b of objPropBindings) { if (b.p?.value && b.label?.value) addLabel(lmap, b.p.value, { value: b.label.value, lang: b.label.lang }); }
+ for (const b of dataPropBindings) { if (b.p?.value && b.label?.value) addLabel(lmap, b.p.value, { value: b.label.value, lang: b.label.lang }); }
+ for (const b of individualBindings) { if (b.ind?.value && b.label?.value) addLabel(lmap, b.ind.value, { value: b.label.value, lang: b.label.lang }); }
+
+ labelMapRef.current = lmap;
+
+ // Detect available languages
+ const langSet = new Set<string>();
+ for (const labels of lmap.values()) for (const l of labels) if (l.lang) langSet.add(l.lang);
+ setAvailableLangs(Array.from(langSet).sort());
+
+ const currentLang = langFilterRef.current;
+
+ // Pass 2: build nodeMap with picked labels
const nodeMap = new Map<string, { label: string; uri: string; nodeType: NodeType }>();
const parentToChildren = new Map<string, Set<string>>();
const hasParent = new Set<string>();
- for (const b of parseSparqlResults(classesText)) {
+ const seenClasses = new Set<string>();
+ for (const b of classBindings) {
const uri = b.c?.value; if (!uri) continue;
const id = shortUri(uri);
- if (!nodeMap.has(id)) nodeMap.set(id, { label: b.label?.value || id, uri, nodeType: 'Class' });
+ seenClasses.add(uri);
+ if (!nodeMap.has(id)) nodeMap.set(id, { label: pickLabel(lmap.get(uri) ?? [], currentLang, uri), uri, nodeType: 'Class' });
}
for (const b of parseSparqlResults(subclassText)) {
const subUri = b.sub?.value, parentUri = b.parent?.value;
if (!subUri || !parentUri) continue;
const sid = shortUri(subUri), pid = shortUri(parentUri);
- if (!nodeMap.has(pid)) nodeMap.set(pid, { label: pid, uri: parentUri, nodeType: 'Class' });
+ if (!nodeMap.has(pid)) nodeMap.set(pid, { label: pickLabel(lmap.get(parentUri) ?? [], currentLang, parentUri), uri: parentUri, nodeType: 'Class' });
if (!parentToChildren.has(pid)) parentToChildren.set(pid, new Set());
parentToChildren.get(pid)!.add(sid);
hasParent.add(sid);
@@ -205,10 +272,10 @@ export function TreeView({ onNodeSelect }: TreeViewProps) {
const propParentToChildren = new Map<string, Set<string>>();
const propHasParent = new Set<string>();
- for (const b of parseSparqlResults(objPropsText)) {
+ for (const b of objPropBindings) {
const uri = b.p?.value; if (!uri) continue;
const id = shortUri(uri);
- if (!nodeMap.has(id)) nodeMap.set(id, { label: b.label?.value || id, uri, nodeType: 'ObjectProperty' });
+ if (!nodeMap.has(id)) nodeMap.set(id, { label: pickLabel(lmap.get(uri) ?? [], currentLang, uri), uri, nodeType: 'ObjectProperty' });
if (b.parent?.value) {
const pid = shortUri(b.parent.value);
if (!propParentToChildren.has(pid)) propParentToChildren.set(pid, new Set());
@@ -217,18 +284,18 @@ export function TreeView({ onNodeSelect }: TreeViewProps) {
}
}
- for (const b of parseSparqlResults(dataPropsText)) {
+ for (const b of dataPropBindings) {
const uri = b.p?.value; if (!uri) continue;
const id = shortUri(uri);
- if (!nodeMap.has(id)) nodeMap.set(id, { label: b.label?.value || id, uri, nodeType: 'DatatypeProperty' });
+ if (!nodeMap.has(id)) nodeMap.set(id, { label: pickLabel(lmap.get(uri) ?? [], currentLang, uri), uri, nodeType: 'DatatypeProperty' });
}
const indsByClass = new Map<string, string[]>();
- for (const b of parseSparqlResults(individualsText)) {
+ for (const b of individualBindings) {
const uri = b.ind?.value, typeUri = b.type?.value;
if (!uri || !typeUri) continue;
const id = shortUri(uri), tid = shortUri(typeUri);
- if (!nodeMap.has(id)) nodeMap.set(id, { label: b.label?.value || id, uri, nodeType: 'Individual' });
+ if (!nodeMap.has(id)) nodeMap.set(id, { label: pickLabel(lmap.get(uri) ?? [], currentLang, uri), uri, nodeType: 'Individual' });
if (!indsByClass.has(tid)) indsByClass.set(tid, []);
indsByClass.get(tid)!.push(id);
}
@@ -361,6 +428,21 @@ SELECT ?prop ?propLabel ?target ?targetLabel ?dir WHERE {
return () => { delete (window as unknown as Record<string, unknown>).__refreshGraph; };
}, [loadTree]);
+ // Relabel tree when language filter changes — no re-query needed
+ useEffect(() => {
+ // Ahead of the early return: a language picked before the first load must
+ // still be the one `loadTree` reads when it arrives.
+ langFilterRef.current = langFilter;
+ if (labelMapRef.current.size === 0) return;
+ const lmap = labelMapRef.current;
+ setRoots(prev => relabelTree(prev, lmap, langFilter));
+ // Also update nodeMapRef so connection labels and breadcrumbs stay in sync
+ for (const [id, data] of nodeMapRef.current) {
+ const labels = lmap.get(data.uri) ?? [];
+ if (labels.length > 0) nodeMapRef.current.set(id, { ...data, label: pickLabel(labels, langFilter, data.uri) });
+ }
+ }, [langFilter]);
+
const toggleExpand = useCallback((id: string) => {
setExpanded(prev => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; });
}, []);
@@ -521,6 +603,22 @@ SELECT ?prop ?propLabel ?target ?targetLabel ?dir WHERE {
)}
</div>
+ {/* Language filter */}
+ {availableLangs.length > 0 && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }}>
+ <span style={{ fontSize: 10, color: '#585b70' }}>Label:</span>
+ {availableLangs.map(lang => (
+ <button key={lang} onClick={() => setLangFilter(lang)} style={{
+ background: langFilter === lang ? '#89b4fa' : '#1e1e2e',
+ border: '1px solid #313244', borderRadius: 4, padding: '1px 6px',
+ fontSize: 10, cursor: 'pointer', fontFamily: 'monospace',
+ color: langFilter === lang ? '#1e1e2e' : '#6c7086',
+ fontWeight: langFilter === lang ? 600 : 400,
+ }}>{lang}</button>
+ ))}
+ </div>
+ )}
+
<div style={{ display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }}>
{typeOrder.filter(t => (typeCounts.get(t) ?? 0) > 0).map(type => (
<button key={type} onClick={() => toggleType(type)} style={{
@@ -581,9 +679,16 @@ SELECT ?prop ?propLabel ?target ?targetLabel ?dir WHERE {
// Tree connector lines
const lines: React.ReactNode[] = [];
- for (let lvl = 0; lvl < indent; lvl++) {
- // Vertical continuation line for ancestors that are NOT the last child
- if (lvl < parentIsLast.length && !parentIsLast[lvl]) {
+ // Run up to indent-2: the direct-parent column (lvl = indent-1) is handled
+ // by the own connector below — mixing both draws a phantom T on last children.
+ for (let lvl = 0; lvl < indent - 1; lvl++) {
+ // Vertical continuation line for ancestors that are NOT the last child.
+ // Column `lvl` belongs to the ancestor at indent `lvl + 1`, not `lvl`:
+ // a node at indent k draws its elbow and its sibling line at column
+ // k - 1. Gating on `parentIsLast[lvl]` dropped the vertical joining an
+ // ancestor to its next sibling across that ancestor's whole subtree,
+ // and drew a floating line under an L in the converse case.
+ if (lvl + 1 < parentIsLast.length && !parentIsLast[lvl + 1]) {
lines.push(
<span key={`v${lvl}`} style={{
position: 'absolute', left: lvl * INDENT_W + 16, top: 0, bottom: 0, width: 1,