1
0
silverbullet/plugs/index/item.ts

77 lines
2.0 KiB
TypeScript
Raw Normal View History

import type { IndexTreeEvent } from "$sb/app_event.ts";
2022-04-01 15:07:08 +00:00
2022-10-14 13:11:33 +00:00
import { collectNodesOfType, ParseTree, renderToText } from "$sb/lib/tree.ts";
2023-07-24 17:54:31 +00:00
import { extractAttributes } from "$sb/lib/attribute.ts";
import { rewritePageRefs } from "$sb/lib/resolve.ts";
import { ObjectValue } from "$sb/types.ts";
import { indexObjects } from "./api.ts";
import { updateITags } from "$sb/lib/tags.ts";
import { extractFrontmatter } from "$sb/lib/frontmatter.ts";
2022-03-29 15:02:28 +00:00
export type ItemObject = ObjectValue<
{
name: string;
page: string;
pos: number;
} & Record<string, any>
>;
2022-03-29 15:02:28 +00:00
export async function indexItems({ name, tree }: IndexTreeEvent) {
const items: ObjectValue<ItemObject>[] = [];
2022-03-29 15:02:28 +00:00
const frontmatter = await extractFrontmatter(tree);
2022-04-04 09:51:41 +00:00
2022-10-14 13:11:33 +00:00
const coll = collectNodesOfType(tree, "ListItem");
2022-04-04 09:51:41 +00:00
2023-07-26 15:12:56 +00:00
for (const n of coll) {
2022-04-04 09:51:41 +00:00
if (!n.children) {
2023-07-26 15:12:56 +00:00
continue;
2022-04-04 09:51:41 +00:00
}
if (collectNodesOfType(n, "Task").length > 0) {
// This is a task item, skip it
2023-07-26 15:12:56 +00:00
continue;
}
const tags = new Set<string>();
const item: ItemObject = {
ref: `${name}@${n.from}`,
tag: "item",
2023-07-24 17:54:31 +00:00
name: "", // to be replaced
page: name,
pos: n.from!,
2023-07-24 17:54:31 +00:00
};
2022-10-14 13:11:33 +00:00
const textNodes: ParseTree[] = [];
collectNodesOfType(n, "Hashtag").forEach((h) => {
// Push tag to the list, removing the initial #
2023-10-13 14:33:37 +00:00
tags.add(h.children![0].text!.substring(1));
});
2022-10-14 13:11:33 +00:00
for (const child of n.children!.slice(1)) {
rewritePageRefs(child, name);
2022-04-04 09:51:41 +00:00
if (child.type === "OrderedList" || child.type === "BulletList") {
break;
}
2023-07-24 17:54:31 +00:00
// Extract attributes and remove from tree
2023-07-26 15:12:56 +00:00
const extractedAttributes = await extractAttributes(child, true);
2023-08-01 19:35:19 +00:00
2023-07-24 17:54:31 +00:00
for (const [key, value] of Object.entries(extractedAttributes)) {
item[key] = value;
}
2022-04-04 09:51:41 +00:00
textNodes.push(child);
}
2023-07-24 17:54:31 +00:00
item.name = textNodes.map(renderToText).join("").trim();
if (tags.size > 0) {
item.tags = [...tags];
}
updateITags(item, frontmatter);
2023-10-13 14:33:37 +00:00
items.push(item);
2023-07-26 15:12:56 +00:00
}
// console.log("Found", items, "item(s)");
await indexObjects(name, items);
}