2023-10-03 12:16:33 +00:00
|
|
|
import type { IndexTreeEvent } from "$sb/app_event.ts";
|
|
|
|
import { YAML } from "$sb/syscalls.ts";
|
2022-11-24 11:04:00 +00:00
|
|
|
import { collectNodesOfType, findNodeOfType } from "$sb/lib/tree.ts";
|
2023-10-03 12:16:33 +00:00
|
|
|
import { ObjectValue } from "$sb/types.ts";
|
|
|
|
import { indexObjects } from "./api.ts";
|
|
|
|
import { TagObject } from "./tags.ts";
|
|
|
|
|
|
|
|
type DataObject = ObjectValue<
|
|
|
|
{
|
|
|
|
pos: number;
|
|
|
|
page: string;
|
|
|
|
} & Record<string, any>
|
|
|
|
>;
|
2022-04-12 11:33:07 +00:00
|
|
|
|
2022-04-20 08:56:43 +00:00
|
|
|
export async function indexData({ name, tree }: IndexTreeEvent) {
|
2023-10-03 12:16:33 +00:00
|
|
|
const dataObjects: ObjectValue<DataObject>[] = [];
|
2022-04-12 11:33:07 +00:00
|
|
|
|
2023-05-23 18:53:53 +00:00
|
|
|
await Promise.all(
|
|
|
|
collectNodesOfType(tree, "FencedCode").map(async (t) => {
|
|
|
|
const codeInfoNode = findNodeOfType(t, "CodeInfo");
|
|
|
|
if (!codeInfoNode) {
|
|
|
|
return;
|
|
|
|
}
|
2023-10-03 12:16:33 +00:00
|
|
|
const fenceType = codeInfoNode.children![0].text!;
|
|
|
|
if (fenceType !== "data" && !fenceType.startsWith("#")) {
|
2023-05-23 18:53:53 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
const codeTextNode = findNodeOfType(t, "CodeText");
|
|
|
|
if (!codeTextNode) {
|
|
|
|
// Honestly, this shouldn't happen
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const codeText = codeTextNode.children![0].text!;
|
2023-10-03 12:16:33 +00:00
|
|
|
const dataType = fenceType === "data" ? "data" : fenceType.substring(1);
|
2023-05-23 18:53:53 +00:00
|
|
|
try {
|
|
|
|
const docs = codeText.split("---");
|
|
|
|
// We support multiple YAML documents in one block
|
|
|
|
for (let i = 0; i < docs.length; i++) {
|
|
|
|
const doc = await YAML.parse(docs[i]);
|
|
|
|
if (!doc) {
|
|
|
|
continue;
|
|
|
|
}
|
2023-10-03 12:16:33 +00:00
|
|
|
const pos = t.from! + i;
|
2023-05-23 18:53:53 +00:00
|
|
|
dataObjects.push({
|
2023-10-03 12:16:33 +00:00
|
|
|
ref: `${name}@${pos}`,
|
|
|
|
tags: [dataType],
|
|
|
|
...doc,
|
|
|
|
pos,
|
|
|
|
page: name,
|
2023-05-23 18:53:53 +00:00
|
|
|
});
|
2022-04-12 11:33:07 +00:00
|
|
|
}
|
2023-05-23 18:53:53 +00:00
|
|
|
// console.log("Parsed data", parsedData);
|
2023-10-03 12:16:33 +00:00
|
|
|
await indexObjects<TagObject>(name, [
|
|
|
|
{
|
|
|
|
ref: dataType,
|
|
|
|
tags: ["tag"],
|
|
|
|
name: dataType,
|
|
|
|
page: name,
|
|
|
|
parent: "data",
|
|
|
|
},
|
|
|
|
]);
|
2023-05-23 18:53:53 +00:00
|
|
|
} catch (e) {
|
|
|
|
console.error("Could not parse data", codeText, "error:", e);
|
|
|
|
return;
|
2022-04-12 11:33:07 +00:00
|
|
|
}
|
2023-05-23 18:53:53 +00:00
|
|
|
}),
|
|
|
|
);
|
2022-10-21 08:00:43 +00:00
|
|
|
// console.log("Found", dataObjects.length, "data objects");
|
2023-10-03 12:16:33 +00:00
|
|
|
await indexObjects(name, dataObjects);
|
2022-04-19 14:54:47 +00:00
|
|
|
}
|