|
| 1 | +/** |
| 2 | + * Tooltip content for an IRI hovered in the query editor: its label, description and type, fetched with a small |
| 3 | + * background query against the endpoint of the tab (with its authentication), cached per endpoint and IRI. |
| 4 | + * When the endpoint doesn't describe the IRI, LOV (Linked Open Vocabularies) is tried for vocabulary terms. |
| 5 | + */ |
| 6 | +import { Parser } from "@matdata/yasr"; |
| 7 | +import type { IriAtPosition } from "@matdata/yasqe"; |
| 8 | +import type Tab from "./Tab"; |
| 9 | +import "./IriHoverInfo.scss"; |
| 10 | + |
| 11 | +const SPARQL_JSON = "application/sparql-results+json"; |
| 12 | +const LOV_ENDPOINT = "https://lov.linkeddata.es/dataset/lov/sparql"; |
| 13 | +const TIMEOUT_MS = 10000; |
| 14 | +const MAX_CACHE_SIZE = 500; |
| 15 | +const MAX_COMMENT_LENGTH = 280; |
| 16 | + |
| 17 | +const RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; |
| 18 | +const RDFS = "http://www.w3.org/2000/01/rdf-schema#"; |
| 19 | +const SKOS = "http://www.w3.org/2004/02/skos/core#"; |
| 20 | +const LABEL_PROPERTIES = [`${RDFS}label`, `${SKOS}prefLabel`]; |
| 21 | +const COMMENT_PROPERTIES = [`${RDFS}comment`, `${SKOS}definition`]; |
| 22 | +const TYPE = `${RDF}type`; |
| 23 | +const DOMAIN = `${RDFS}domain`; |
| 24 | +const RANGE = `${RDFS}range`; |
| 25 | +const PROPERTIES = [...LABEL_PROPERTIES, ...COMMENT_PROPERTIES, TYPE, DOMAIN, RANGE]; |
| 26 | +// Used to shorten types, domains and ranges in addition to the prefixes of the query |
| 27 | +const COMMON_PREFIXES: { [prefix: string]: string } = { |
| 28 | + rdf: RDF, |
| 29 | + rdfs: RDFS, |
| 30 | + owl: "http://www.w3.org/2002/07/owl#", |
| 31 | + skos: SKOS, |
| 32 | + xsd: "http://www.w3.org/2001/XMLSchema#", |
| 33 | + sh: "http://www.w3.org/ns/shacl#", |
| 34 | +}; |
| 35 | + |
| 36 | +interface Literal { |
| 37 | + value: string; |
| 38 | + lang: string; |
| 39 | +} |
| 40 | + |
| 41 | +export interface IriInfo { |
| 42 | + labels: Literal[]; |
| 43 | + comments: Literal[]; |
| 44 | + types: string[]; |
| 45 | + domains: string[]; |
| 46 | + ranges: string[]; |
| 47 | + /** Where the information came from */ |
| 48 | + source: "endpoint" | "lov"; |
| 49 | +} |
| 50 | + |
| 51 | +// Shared by all tabs: hovering the same IRI on the same endpoint doesn't query it again |
| 52 | +const cache = new Map<string, Promise<IriInfo | undefined>>(); |
| 53 | + |
| 54 | +/** The query that fetches the label, description and type of an IRI. */ |
| 55 | +export function buildIriInfoQuery(iri: string, inAnyGraph = false): string { |
| 56 | + const triple = `<${iri}> ?p ?o .`; |
| 57 | + return [ |
| 58 | + "SELECT ?p ?o WHERE {", |
| 59 | + ` VALUES ?p { ${PROPERTIES.map((p) => `<${p}>`).join(" ")} }`, |
| 60 | + inAnyGraph ? ` GRAPH ?g { ${triple} }` : ` ${triple}`, |
| 61 | + "} LIMIT 200", |
| 62 | + ].join("\n"); |
| 63 | +} |
| 64 | + |
| 65 | +/** Group the ?p ?o bindings of the info query; undefined when the IRI isn't described at all. */ |
| 66 | +export function parseIriInfo(bindings: any[], source: IriInfo["source"]): IriInfo | undefined { |
| 67 | + const info: IriInfo = { labels: [], comments: [], types: [], domains: [], ranges: [], source }; |
| 68 | + const addIri = (list: string[], value: string) => { |
| 69 | + if (!list.includes(value)) list.push(value); |
| 70 | + }; |
| 71 | + for (const binding of bindings) { |
| 72 | + const p = binding.p?.value; |
| 73 | + const o = binding.o; |
| 74 | + if (!p || !o || typeof o.value !== "string") continue; |
| 75 | + const literal = { value: o.value, lang: (o["xml:lang"] || o.lang || "").toLowerCase() }; |
| 76 | + if (LABEL_PROPERTIES.includes(p) && o.type !== "uri") info.labels.push(literal); |
| 77 | + else if (COMMENT_PROPERTIES.includes(p) && o.type !== "uri") info.comments.push(literal); |
| 78 | + else if (o.type === "uri" && p === TYPE) addIri(info.types, o.value); |
| 79 | + else if (o.type === "uri" && p === DOMAIN) addIri(info.domains, o.value); |
| 80 | + else if (o.type === "uri" && p === RANGE) addIri(info.ranges, o.value); |
| 81 | + } |
| 82 | + const empty = !info.labels.length && !info.comments.length && !info.types.length; |
| 83 | + return empty && !info.domains.length && !info.ranges.length ? undefined : info; |
| 84 | +} |
| 85 | + |
| 86 | +/** The literal in the most preferred language: the browser languages, then English, then without language tag. */ |
| 87 | +export function pickLiteral(literals: Literal[], languages: string[]): Literal | undefined { |
| 88 | + if (!literals.length) return undefined; |
| 89 | + const wanted = [...languages.map((l) => l.toLowerCase()), "en", ""]; |
| 90 | + for (const lang of wanted) { |
| 91 | + const exact = literals.find((l) => l.lang === lang); |
| 92 | + if (exact) return exact; |
| 93 | + const base = lang.split("-")[0]; |
| 94 | + const sameBase = base && literals.find((l) => l.lang.split("-")[0] === base); |
| 95 | + if (sameBase) return sameBase; |
| 96 | + } |
| 97 | + return literals[0]; |
| 98 | +} |
| 99 | + |
| 100 | +async function runQuery(run: (signal: AbortSignal) => Promise<any>): Promise<any[]> { |
| 101 | + const controller = new AbortController(); |
| 102 | + const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS); |
| 103 | + try { |
| 104 | + const response = await run(controller.signal); |
| 105 | + const parser = new Parser(response, 0); |
| 106 | + if (parser.hasError()) throw new Error(parser.getError()?.text || "Query failed"); |
| 107 | + return parser.getBindings() || []; |
| 108 | + } finally { |
| 109 | + clearTimeout(timeout); |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +async function fetchFromLov(iri: string): Promise<IriInfo | undefined> { |
| 114 | + const url = `${LOV_ENDPOINT}?query=${encodeURIComponent(buildIriInfoQuery(iri, true))}`; |
| 115 | + const bindings = await runQuery(async (signal) => { |
| 116 | + const response = await fetch(url, { headers: { Accept: SPARQL_JSON }, signal }); |
| 117 | + if (!response.ok) throw new Error(response.statusText); |
| 118 | + return { content: await response.text(), status: response.status, headers: response.headers }; |
| 119 | + }); |
| 120 | + return parseIriInfo(bindings, "lov"); |
| 121 | +} |
| 122 | + |
| 123 | +async function fetchIriInfo(tab: Tab, iri: string, lovFallback: boolean): Promise<IriInfo | undefined> { |
| 124 | + const bindings = await runQuery((signal) => |
| 125 | + tab.runBackgroundQuery(buildIriInfoQuery(iri), { accept: SPARQL_JSON, signal }), |
| 126 | + ); |
| 127 | + const info = parseIriInfo(bindings, "endpoint"); |
| 128 | + if (info || !lovFallback) return info; |
| 129 | + // LOV is a nice-to-have: a failure there just means there is nothing to show |
| 130 | + return fetchFromLov(iri).catch(() => undefined); |
| 131 | +} |
| 132 | + |
| 133 | +/** Cached lookup of the info of an IRI on the endpoint of the tab. A failed lookup is retried on the next hover. */ |
| 134 | +export function getIriInfo(tab: Tab, iri: string, lovFallback = true): Promise<IriInfo | undefined> { |
| 135 | + const key = `${tab.getEndpoint()}\n${iri}`; |
| 136 | + let info = cache.get(key); |
| 137 | + if (!info) { |
| 138 | + info = fetchIriInfo(tab, iri, lovFallback); |
| 139 | + info.catch(() => cache.delete(key)); |
| 140 | + if (cache.size >= MAX_CACHE_SIZE) cache.delete(cache.keys().next().value as string); |
| 141 | + cache.set(key, info); |
| 142 | + } |
| 143 | + return info; |
| 144 | +} |
| 145 | + |
| 146 | +export function clearIriInfoCache() { |
| 147 | + cache.clear(); |
| 148 | +} |
| 149 | + |
| 150 | +function languages(): string[] { |
| 151 | + return typeof navigator !== "undefined" ? [...(navigator.languages || []), navigator.language].filter(Boolean) : []; |
| 152 | +} |
| 153 | + |
| 154 | +function truncate(text: string, max: number) { |
| 155 | + const clean = text.replace(/\s+/g, " ").trim(); |
| 156 | + return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean; |
| 157 | +} |
| 158 | + |
| 159 | +function el<K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text?: string) { |
| 160 | + const element = document.createElement(tag); |
| 161 | + element.className = className; |
| 162 | + if (text !== undefined) element.textContent = text; |
| 163 | + return element; |
| 164 | +} |
| 165 | + |
| 166 | +/** Shorten an IRI with the prefixes of the query, e.g. `rdfs:Class` */ |
| 167 | +function compact(iri: string, prefixes: { [prefix: string]: string }): string { |
| 168 | + let best: string | undefined; |
| 169 | + for (const prefix in prefixes) { |
| 170 | + const namespace = prefixes[prefix]; |
| 171 | + if (!namespace || !iri.startsWith(namespace)) continue; |
| 172 | + const local = iri.slice(namespace.length); |
| 173 | + if (!/^[^\s/#?:]*$/.test(local)) continue; |
| 174 | + const candidate = `${prefix}:${local}`; |
| 175 | + if (!best || candidate.length < best.length) best = candidate; |
| 176 | + } |
| 177 | + return best || `<${iri}>`; |
| 178 | +} |
| 179 | + |
| 180 | +function renderInfo(container: HTMLElement, info: IriInfo | undefined, tab: Tab) { |
| 181 | + container.querySelector(".yasgui-iriHover__status")?.remove(); |
| 182 | + const details = el("div", "yasgui-iriHover__details"); |
| 183 | + if (!info) { |
| 184 | + details.appendChild(el("div", "yasgui-iriHover__status", "No label, description or type found on this endpoint.")); |
| 185 | + container.insertBefore(details, container.lastChild); |
| 186 | + return; |
| 187 | + } |
| 188 | + const langs = languages(); |
| 189 | + const label = pickLiteral(info.labels, langs); |
| 190 | + if (label) { |
| 191 | + const labelEl = el("div", "yasgui-iriHover__label", label.value); |
| 192 | + if (label.lang) labelEl.appendChild(el("span", "yasgui-iriHover__lang", label.lang)); |
| 193 | + container.insertBefore(labelEl, container.firstChild); |
| 194 | + } |
| 195 | + const comment = pickLiteral(info.comments, langs); |
| 196 | + if (comment) details.appendChild(el("div", "yasgui-iriHover__comment", truncate(comment.value, MAX_COMMENT_LENGTH))); |
| 197 | + const prefixes = { ...COMMON_PREFIXES, ...(tab.getYasqe()?.getPrefixesFromQuery() || {}) }; |
| 198 | + const rows: [string, string[]][] = [ |
| 199 | + ["Type", info.types], |
| 200 | + ["Domain", info.domains], |
| 201 | + ["Range", info.ranges], |
| 202 | + ]; |
| 203 | + for (const [name, values] of rows) { |
| 204 | + if (!values.length) continue; |
| 205 | + const row = el("div", "yasgui-iriHover__row"); |
| 206 | + row.appendChild(el("span", "yasgui-iriHover__key", name)); |
| 207 | + const shown = values.slice(0, 5).map((value) => compact(value, prefixes)); |
| 208 | + if (values.length > 5) shown.push(`+${values.length - 5} more`); |
| 209 | + row.appendChild(el("span", "yasgui-iriHover__value", shown.join(", "))); |
| 210 | + details.appendChild(row); |
| 211 | + } |
| 212 | + if (info.source === "lov") details.appendChild(el("div", "yasgui-iriHover__source", "Description from LOV")); |
| 213 | + container.insertBefore(details, container.lastChild); |
| 214 | +} |
| 215 | + |
| 216 | +/** The tooltip for an IRI hovered in the editor of the tab. */ |
| 217 | +export function createIriHover(tab: Tab, iri: IriAtPosition, lovFallback = true): HTMLElement | undefined { |
| 218 | + if (!iri.expanded) return undefined; |
| 219 | + const container = el("div", "yasgui-iriHover"); |
| 220 | + if (iri.text !== `<${iri.iri}>`) container.appendChild(el("div", "yasgui-iriHover__iri", iri.iri)); |
| 221 | + container.appendChild(el("div", "yasgui-iriHover__status", "Loading…")); |
| 222 | + container.appendChild( |
| 223 | + el("div", "yasgui-iriHover__hint", "Ctrl+click: triples with this IRI as subject. Ctrl+Shift+click: as object."), |
| 224 | + ); |
| 225 | + getIriInfo(tab, iri.iri, lovFallback).then( |
| 226 | + (info) => { |
| 227 | + renderInfo(container, info, tab); |
| 228 | + }, |
| 229 | + () => { |
| 230 | + const status = container.querySelector(".yasgui-iriHover__status"); |
| 231 | + if (status) status.textContent = "Couldn't load information from this endpoint."; |
| 232 | + }, |
| 233 | + ); |
| 234 | + return container; |
| 235 | +} |
0 commit comments