diff src/layout/rdf_value.ts @ 106:2468f2227d22

make src/layout/ and src/render/ separation
author drewp@bigasterisk.com
date Sun, 13 Mar 2022 22:00:30 -0700
parents src/rdf_value.ts@47d3b5a5bd5e
children 5e6840229a05
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/layout/rdf_value.ts	Sun Mar 13 22:00:30 2022 -0700
@@ -0,0 +1,46 @@
+import { Store, Term, NamedNode } from "n3";
+import { RDFS } from "./namespaces";
+
+function _singleValue(g: Store, s: Term, p: Term): Term {
+  const quads = g.getQuads(s, p, null, null);
+  const objs = new Set(quads.map((q) => q.object));
+  if (objs.size == 0) {
+    throw new Error("no value for " + s.value + " " + p.value);
+  } else if (objs.size == 1) {
+    const obj = objs.values().next().value;
+    return obj as Term;
+  } else {
+    throw new Error("too many different values: " + JSON.stringify(quads));
+  }
+}
+
+export function stringValue(g: Store, s: Term, p: Term): string {
+  const ret = _singleValue(g, s, p);
+  if (ret.termType != "Literal") {
+    throw new Error(`ret=${ret}`);
+  }
+  return ret.value as string;
+}
+
+export function uriValue(g: Store, s: Term, p: Term): NamedNode {
+  const ret = _singleValue(g, s, p);
+  if (ret.termType != "NamedNode") {
+    throw new Error(`ret=${ret}`);
+  }
+
+  return ret;
+}
+
+export function labelOrTail(g: Store, uri: NamedNode): string {
+  let ret: string;
+  try {
+    ret = stringValue(g, uri, RDFS("label"));
+  } catch (e) {
+    const words = uri.value.split("/");
+    ret = words[words.length - 1];
+  }
+  if (!ret) {
+    ret = uri.value;
+  }
+  return ret;
+}