silverbullet/plugs/index/paragraph.ts

83 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-02-29 22:23:05 +08:00
import type { IndexTreeEvent } from "../../plug-api/types.ts";
import { indexObjects } from "./api.ts";
2023-10-13 21:37:25 +08:00
import {
collectNodesOfType,
findParentMatching,
renderToText,
traverseTreeAsync,
2024-02-29 22:23:05 +08:00
} from "../../plug-api/lib/tree.ts";
import { extractAttributes } from "@silverbulletmd/silverbullet/lib/attribute";
2024-07-30 23:33:33 +08:00
import type { ObjectValue } from "../../plug-api/types.ts";
import { updateITags } from "@silverbulletmd/silverbullet/lib/tags";
import { extractFrontmatter } from "@silverbulletmd/silverbullet/lib/frontmatter";
import { extractHashtag } from "../../plug-api/lib/tags.ts";
/** ParagraphObject An index object for the top level text nodes */
2023-10-13 22:33:37 +08:00
export type ParagraphObject = ObjectValue<
{
page: string;
pos: number;
2024-07-07 02:52:27 +08:00
text: string;
2023-10-13 22:33:37 +08:00
} & Record<string, any>
>;
export async function indexParagraphs({ name: page, tree }: IndexTreeEvent) {
const objects: ParagraphObject[] = [];
const frontmatter = await extractFrontmatter(tree);
await traverseTreeAsync(tree, async (p) => {
2023-10-13 21:37:25 +08:00
if (p.type !== "Paragraph") {
return false;
}
if (findParentMatching(p, (n) => n.type === "ListItem")) {
// Not looking at paragraphs nested in a list
return false;
}
2024-07-07 02:52:27 +08:00
const fullText = renderToText(p);
// Collect tags and remove from the tree
const tags = new Set<string>();
collectNodesOfType(p, "Hashtag").forEach((tagNode) => {
tags.add(extractHashtag(tagNode.children![0].text!));
// Hacky way to remove the hashtag
tagNode.children = [];
});
// Extract attributes and remove from tree
2024-08-22 02:13:40 +08:00
const attrs = await extractAttributes(["paragraph", ...tags], p);
const text = renderToText(p);
if (!text.trim()) {
// Empty paragraph, just tags and attributes maybe
return true;
}
const pos = p.from!;
const paragraph: ParagraphObject = {
tag: "paragraph",
2024-07-07 02:52:27 +08:00
ref: `${page}@${pos}`,
text: fullText,
page,
pos,
...attrs,
};
if (tags.size > 0) {
paragraph.tags = [...tags];
paragraph.itags = [...tags];
}
updateITags(paragraph, frontmatter);
objects.push(paragraph);
// stop on every element except document, including paragraphs
return true;
});
2023-10-13 21:37:25 +08:00
// console.log("Paragraph objects", objects);
await indexObjects<ParagraphObject>(page, objects);
}