2022-10-14 13:11:33 +00:00
|
|
|
import { collectNodesOfType } from "$sb/lib/tree.ts";
|
|
|
|
import { editor, index } from "$sb/silverbullet-syscall/mod.ts";
|
|
|
|
import type { IndexTreeEvent } from "$sb/app_event.ts";
|
|
|
|
import { removeQueries } from "$sb/lib/query.ts";
|
2022-08-30 08:44:20 +00:00
|
|
|
|
|
|
|
// Key space
|
|
|
|
// a:pageName:anchorName => pos
|
|
|
|
|
|
|
|
export async function indexAnchors({ name: pageName, tree }: IndexTreeEvent) {
|
|
|
|
removeQueries(tree);
|
2022-10-14 13:11:33 +00:00
|
|
|
const anchors: { key: string; value: string }[] = [];
|
2022-08-30 08:44:20 +00:00
|
|
|
|
|
|
|
collectNodesOfType(tree, "NamedAnchor").forEach((n) => {
|
2022-10-24 17:40:52 +00:00
|
|
|
const aName = n.children![0].text!.substring(1);
|
2022-08-30 08:44:20 +00:00
|
|
|
anchors.push({
|
|
|
|
key: `a:${pageName}:${aName}`,
|
|
|
|
value: "" + n.from,
|
|
|
|
});
|
|
|
|
});
|
2022-10-21 08:00:43 +00:00
|
|
|
// console.log("Found", anchors.length, "anchors(s)");
|
2022-10-14 13:11:33 +00:00
|
|
|
await index.batchSet(pageName, anchors);
|
2022-08-30 08:44:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function anchorComplete() {
|
2022-10-14 13:11:33 +00:00
|
|
|
const prefix = await editor.matchBefore("\\[\\[[^\\]@:]*@[\\w\\.\\-\\/]*");
|
2022-08-30 08:44:20 +00:00
|
|
|
if (!prefix) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
const [pageRefPrefix, anchorRef] = prefix.text.split("@");
|
|
|
|
let pageRef = pageRefPrefix.substring(2);
|
|
|
|
if (!pageRef) {
|
2022-10-14 13:11:33 +00:00
|
|
|
pageRef = await editor.getCurrentPage();
|
2022-08-30 08:44:20 +00:00
|
|
|
}
|
2022-10-24 17:40:52 +00:00
|
|
|
const allAnchors = await index.queryPrefix(
|
|
|
|
`a:${pageRef}:${anchorRef}`,
|
|
|
|
);
|
2022-08-30 08:44:20 +00:00
|
|
|
return {
|
|
|
|
from: prefix.from + pageRefPrefix.length + 1,
|
|
|
|
options: allAnchors.map((a) => ({
|
2022-10-24 17:40:52 +00:00
|
|
|
label: a.key.split(":")[2],
|
2022-08-30 08:44:20 +00:00
|
|
|
type: "anchor",
|
|
|
|
})),
|
|
|
|
};
|
|
|
|
}
|