1
0
silverbullet/plugs/directive/data.ts

66 lines
1.8 KiB
TypeScript
Raw Normal View History

// Index key space:
// data:page@pos
2022-10-14 13:11:33 +00:00
import type { IndexTreeEvent, QueryProviderEvent } from "$sb/app_event.ts";
import { index } from "$sb/silverbullet-syscall/mod.ts";
2022-11-24 11:04:00 +00:00
import { collectNodesOfType, findNodeOfType } from "$sb/lib/tree.ts";
2022-10-14 13:11:33 +00:00
import { applyQuery, removeQueries } from "$sb/lib/query.ts";
import * as YAML from "yaml";
export async function indexData({ name, tree }: IndexTreeEvent) {
2022-10-14 13:11:33 +00:00
const dataObjects: { key: string; value: any }[] = [];
removeQueries(tree);
collectNodesOfType(tree, "FencedCode").forEach((t) => {
2022-10-14 13:11:33 +00:00
const codeInfoNode = findNodeOfType(t, "CodeInfo");
if (!codeInfoNode) {
return;
}
if (codeInfoNode.children![0].text !== "data") {
return;
}
2022-10-14 13:11:33 +00:00
const codeTextNode = findNodeOfType(t, "CodeText");
if (!codeTextNode) {
// Honestly, this shouldn't happen
return;
}
2022-10-14 13:11:33 +00:00
const codeText = codeTextNode.children![0].text!;
try {
2022-10-14 13:11:33 +00:00
const docs = codeText.split("---").map((d) => YAML.parse(d));
// We support multiple YAML documents in one block
2022-10-14 13:11:33 +00:00
for (let i = 0; i < docs.length; i++) {
const doc = docs[i];
if (!doc) {
continue;
}
dataObjects.push({
2022-10-14 13:11:33 +00:00
key: `data:${name}@${i}`,
value: doc,
});
}
// console.log("Parsed data", parsedData);
} catch (e) {
console.error("Could not parse data", codeText, "error:", e);
return;
}
});
// console.log("Found", dataObjects.length, "data objects");
2022-10-14 13:11:33 +00:00
await index.batchSet(name, dataObjects);
}
export async function queryProvider({
query,
}: QueryProviderEvent): Promise<any[]> {
2022-10-14 13:11:33 +00:00
const allData: any[] = [];
for (const { key, page, value } of await index.queryPrefix("data:")) {
const [, pos] = key.split("@");
allData.push({
...value,
page: page,
pos: +pos,
});
}
return applyQuery(query, allData);
}