2022-04-12 11:33:07 +00:00
|
|
|
// Index key space:
|
|
|
|
// data:page@pos
|
|
|
|
|
|
|
|
import { IndexEvent } from "../../webapp/app_event";
|
|
|
|
import { batchSet } from "plugos-silverbullet-syscall";
|
|
|
|
import { parseMarkdown } from "plugos-silverbullet-syscall/markdown";
|
2022-04-13 12:46:52 +00:00
|
|
|
import { collectNodesOfType, findNodeOfType, ParseTree, replaceNodesMatching } from "../../common/tree";
|
|
|
|
import { parse as parseYaml, parseAllDocuments } from "yaml";
|
|
|
|
import { whiteOutQueries } from "./util";
|
2022-04-12 11:33:07 +00:00
|
|
|
|
|
|
|
export async function indexData({ name, text }: IndexEvent) {
|
|
|
|
let e;
|
|
|
|
text = whiteOutQueries(text);
|
2022-04-13 12:46:52 +00:00
|
|
|
// console.log("Now data indexing", name);
|
2022-04-12 11:33:07 +00:00
|
|
|
let mdTree = await parseMarkdown(text);
|
|
|
|
|
|
|
|
let dataObjects: { key: string; value: Object }[] = [];
|
|
|
|
|
|
|
|
collectNodesOfType(mdTree, "FencedCode").forEach((t) => {
|
|
|
|
let codeInfoNode = findNodeOfType(t, "CodeInfo");
|
|
|
|
if (!codeInfoNode) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (codeInfoNode.children![0].text !== "data") {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let codeTextNode = findNodeOfType(t, "CodeText");
|
|
|
|
if (!codeTextNode) {
|
|
|
|
// Honestly, this shouldn't happen
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let codeText = codeTextNode.children![0].text!;
|
|
|
|
try {
|
|
|
|
// We support multiple YAML documents in one block
|
2022-04-13 12:46:52 +00:00
|
|
|
for (let doc of parseAllDocuments(codeText)) {
|
2022-04-12 11:33:07 +00:00
|
|
|
if (!doc.contents) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
console.log(doc.contents.toJSON());
|
|
|
|
dataObjects.push({
|
|
|
|
key: `data:${name}@${t.from! + doc.range[0]}`,
|
|
|
|
value: doc.contents.toJSON(),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// console.log("Parsed data", parsedData);
|
|
|
|
} catch (e) {
|
|
|
|
console.error("Could not parse data", codeText, "error:", e);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
});
|
2022-04-13 12:46:52 +00:00
|
|
|
console.log("Found", dataObjects.length, "data objects");
|
2022-04-12 11:33:07 +00:00
|
|
|
await batchSet(name, dataObjects);
|
|
|
|
}
|
2022-04-13 12:46:52 +00:00
|
|
|
|
|
|
|
export function extractMeta(parseTree: ParseTree, remove = false): any {
|
|
|
|
let data = {};
|
|
|
|
replaceNodesMatching(parseTree, (t) => {
|
|
|
|
if (t.type !== "FencedCode") {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let codeInfoNode = findNodeOfType(t, "CodeInfo");
|
|
|
|
if (!codeInfoNode) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (codeInfoNode.children![0].text !== "meta") {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let codeTextNode = findNodeOfType(t, "CodeText");
|
|
|
|
if (!codeTextNode) {
|
|
|
|
// Honestly, this shouldn't happen
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
let codeText = codeTextNode.children![0].text!;
|
|
|
|
data = parseYaml(codeText);
|
|
|
|
return remove ? null : undefined;
|
|
|
|
});
|
|
|
|
|
|
|
|
return data;
|
|
|
|
}
|