1
0
silverbullet/plugs/core/item.ts

88 lines
2.0 KiB
TypeScript
Raw Normal View History

import type { IndexTreeEvent } from "../../web/app_event.ts";
2022-04-01 15:07:08 +00:00
2022-04-25 08:33:38 +00:00
import {
batchSet,
queryPrefix,
} from "../../syscall/silverbullet-syscall/index.ts";
2022-04-25 08:33:38 +00:00
import {
collectNodesOfType,
ParseTree,
renderToText,
} from "../../common/tree.ts";
import { removeQueries } from "../query/util.ts";
import { applyQuery, QueryProviderEvent } from "../query/engine.ts";
2022-03-29 15:02:28 +00:00
export type Item = {
name: string;
2022-04-04 09:51:41 +00:00
nested?: string;
tags?: string[];
// Not stored in DB
page?: string;
pos?: number;
2022-03-29 15:02:28 +00:00
};
export async function indexItems({ name, tree }: IndexTreeEvent) {
2022-03-29 15:02:28 +00:00
let items: { key: string; value: Item }[] = [];
removeQueries(tree);
2022-03-29 15:02:28 +00:00
2022-04-04 09:51:41 +00:00
console.log("Indexing items", name);
let coll = collectNodesOfType(tree, "ListItem");
2022-04-04 09:51:41 +00:00
coll.forEach((n) => {
if (!n.children) {
return;
}
if (collectNodesOfType(n, "Task").length > 0) {
// This is a task item, skip it
return;
}
2022-04-11 18:34:09 +00:00
let textNodes: ParseTree[] = [];
2022-04-04 09:51:41 +00:00
let nested: string | undefined;
for (let child of n.children!.slice(1)) {
if (child.type === "OrderedList" || child.type === "BulletList") {
2022-04-11 18:34:09 +00:00
nested = renderToText(child);
2022-04-04 09:51:41 +00:00
break;
}
textNodes.push(child);
}
let itemText = textNodes.map(renderToText).join("").trim();
let item: Item = {
name: itemText,
2022-03-29 15:02:28 +00:00
};
2022-04-04 09:51:41 +00:00
if (nested) {
item.nested = nested;
2022-03-29 15:02:28 +00:00
}
collectNodesOfType(n, "Hashtag").forEach((h) => {
if (!item.tags) {
item.tags = [];
}
item.tags.push(h.children![0].text!);
});
2022-03-29 15:02:28 +00:00
items.push({
2022-04-04 09:51:41 +00:00
key: `it:${n.from}`,
value: item,
2022-03-29 15:02:28 +00:00
});
2022-04-04 09:51:41 +00:00
});
2022-03-29 15:02:28 +00:00
console.log("Found", items.length, "item(s)");
2022-04-01 15:07:08 +00:00
await batchSet(name, items);
2022-03-29 15:02:28 +00:00
}
export async function queryProvider({
query,
}: QueryProviderEvent): Promise<any[]> {
let allItems: Item[] = [];
for (let { key, page, value } of await queryPrefix("it:")) {
let [, pos] = key.split(":");
allItems.push({
...value,
page: page,
pos: +pos,
});
}
return applyQuery(query, allItems);
}