2023-10-12 18:30:47 +00:00
|
|
|
import type { IndexTreeEvent } from "$sb/app_event.ts";
|
|
|
|
import { indexObjects } from "./api.ts";
|
2023-10-13 13:37:25 +00:00
|
|
|
import {
|
|
|
|
addParentPointers,
|
|
|
|
collectNodesOfType,
|
|
|
|
findParentMatching,
|
|
|
|
renderToText,
|
|
|
|
traverseTreeAsync,
|
|
|
|
} from "$sb/lib/tree.ts";
|
2023-10-12 18:30:47 +00:00
|
|
|
import { extractAttributes } from "$sb/lib/attribute.ts";
|
|
|
|
|
|
|
|
/** ParagraphObject An index object for the top level text nodes */
|
|
|
|
export type ParagraphObject = {
|
|
|
|
ref: string;
|
|
|
|
tags: string[];
|
|
|
|
text: string;
|
|
|
|
page: string;
|
|
|
|
pos: number;
|
|
|
|
} & Record<string, any>;
|
|
|
|
|
|
|
|
export async function indexParagraphs({ name: page, tree }: IndexTreeEvent) {
|
|
|
|
const objects: ParagraphObject[] = [];
|
2023-10-13 13:37:25 +00:00
|
|
|
addParentPointers(tree);
|
2023-10-12 18:30:47 +00:00
|
|
|
|
|
|
|
await traverseTreeAsync(tree, async (p) => {
|
2023-10-13 13:37:25 +00:00
|
|
|
if (p.type !== "Paragraph") {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (findParentMatching(p, (n) => n.type === "ListItem")) {
|
|
|
|
// Not looking at paragraphs nested in a list
|
|
|
|
return false;
|
|
|
|
}
|
2023-10-12 18:30:47 +00:00
|
|
|
|
2023-10-13 13:37:25 +00:00
|
|
|
// So we're looking at indexable a paragraph now
|
2023-10-12 18:30:47 +00:00
|
|
|
const tags = new Set<string>(["paragraph"]);
|
|
|
|
// tag the paragraph with any hashtags inside it
|
2023-10-13 13:37:25 +00:00
|
|
|
collectNodesOfType(p, "Hashtag").forEach((tagNode) => {
|
|
|
|
tags.add(tagNode.children![0].text!.substring(1));
|
2023-10-12 18:30:47 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const attrs = await extractAttributes(p, false);
|
|
|
|
const pos = p.from!;
|
|
|
|
objects.push({
|
|
|
|
ref: `${page}@${pos}`,
|
|
|
|
text: renderToText(p),
|
|
|
|
tags: [...tags.values()],
|
|
|
|
page,
|
|
|
|
pos,
|
|
|
|
...attrs,
|
|
|
|
});
|
|
|
|
|
|
|
|
// stop on every element except document, including paragraphs
|
|
|
|
return true;
|
|
|
|
});
|
|
|
|
|
2023-10-13 13:37:25 +00:00
|
|
|
// console.log("Paragraph objects", objects);
|
|
|
|
|
2023-10-12 18:30:47 +00:00
|
|
|
await indexObjects<ParagraphObject>(page, objects);
|
|
|
|
}
|