silverbullet/plugs/editor/complete.ts

213 lines
7.0 KiB
TypeScript
Raw Normal View History

2024-07-30 23:33:33 +08:00
import type {
2024-05-28 02:33:41 +08:00
AttachmentMeta,
CompleteEvent,
FileMeta,
PageMeta,
QueryExpression,
} from "@silverbulletmd/silverbullet/types";
import { listFilesCached } from "../federation/federation.ts";
2023-12-22 01:37:50 +08:00
import { queryObjects } from "../index/plug_api.ts";
import { folderName } from "@silverbulletmd/silverbullet/lib/resolve";
import type { AspiringPageObject } from "../index/page_links.ts";
import { localDateString } from "$lib/dates.ts";
// A meta page is a page tagged with either #template or #meta
const isMetaPageFilter: QueryExpression = ["or", ["=", ["attr", "tags"], [
"string",
"template",
]], ["=", [
"attr",
"tags",
], ["string", "meta"]]];
// Completion
export async function pageComplete(completeEvent: CompleteEvent) {
2024-05-28 02:33:41 +08:00
// Try to match [[wikilink]]
let isWikilink = true;
let match = /\[\[([^\]@$#:\{}]*)$/.exec(completeEvent.linePrefix);
if (!match) {
// Try to match [markdown link]()
match = /\[.*\]\(([^\]\)@$#:\{}]*)$/.exec(completeEvent.linePrefix);
isWikilink = false;
}
if (!match) {
return null;
}
const prefix = match[1];
2024-05-28 02:33:41 +08:00
let allPages: (PageMeta | AttachmentMeta)[] = [];
if (prefix.startsWith("^")) {
// A carrot prefix means we're looking for a meta page
allPages = await queryObjects<PageMeta>("page", {
filter: isMetaPageFilter,
}, 5);
// Let's prefix the names with a caret to make them match
allPages = allPages.map((page) => ({
...page,
name: "^" + page.name,
}));
} // Let's try to be smart about the types of completions we're offering based on the context
else if (
2023-12-22 01:37:50 +08:00
completeEvent.parentNodes.find((node) => node.startsWith("FencedCode")) &&
// either a render [[bla]] clause
2024-02-04 23:36:59 +08:00
/(render\s+|template\()\[\[/.test(
2023-12-22 01:37:50 +08:00
completeEvent.linePrefix,
)
) {
// We're quite certainly in a template context, let's only complete templates
allPages = await queryObjects<PageMeta>("template", {}, 5);
} else if (
completeEvent.parentNodes.find((node) =>
node.startsWith("FencedCode:include") ||
node.startsWith("FencedCode:template")
)
) {
// Include both pages and meta in page completion in ```include and ```template blocks
allPages = await queryObjects<PageMeta>("page", {}, 5);
} else {
2024-07-25 21:18:58 +08:00
// This is the most common case, we're combining three types of completions here:
allPages = (await Promise.all([
// All non-meta pages
queryObjects<PageMeta>("page", {
filter: ["not", isMetaPageFilter],
}, 5),
// All attachments
2024-07-29 18:16:12 +08:00
queryObjects<AttachmentMeta>("attachment", {
// All attachment that do not start with a _ (internal attachments)
filter: ["!=~", ["attr", "name"], ["regexp", "^_", ""]],
}, 5),
2024-07-25 21:18:58 +08:00
// And all links to non-existing pages (to augment the existing ones)
queryObjects<AspiringPageObject>("aspiring-page", {
distinct: true,
select: [{ name: "name" }],
}, 5).then((aspiringPages) =>
2024-07-25 21:18:58 +08:00
// Rewrite them to PageMeta shaped objects
aspiringPages.map((aspiringPage): PageMeta => ({
ref: aspiringPage.name,
2024-07-25 21:18:58 +08:00
tag: "page",
tags: ["non-existing"], // Picked up later in completion
name: aspiringPage.name,
2024-07-25 21:18:58 +08:00
created: "",
lastModified: "",
perm: "rw",
}))
),
])).flat();
}
// Don't complete hidden pages
allPages = allPages.filter((page) => !(page.pageDecoration?.hide === true));
if (prefix.startsWith("!")) {
// Federation!
// Let's see if this URI is complete enough to try to fetch index.json
if (prefix.includes("/")) {
// Yep
const domain = prefix.split("/")[0];
// Cached listing
const federationPages = (await listFilesCached(domain)).filter((fm) =>
fm.name.endsWith(".md")
).map(fileMetaToPageMeta);
if (federationPages.length > 0) {
allPages = allPages.concat(federationPages);
}
}
}
2024-05-28 02:33:41 +08:00
const folder = folderName(completeEvent.pageName);
2024-07-14 17:29:43 +08:00
return {
from: completeEvent.pos - prefix.length,
options: allPages.map((pageMeta) => {
2023-12-22 01:37:50 +08:00
const completions: any[] = [];
const namePrefix = (pageMeta as PageMeta).pageDecoration?.prefix || "";
const cssClass = ((pageMeta as PageMeta).pageDecoration?.cssClasses || [])
.join(" ").replaceAll(/[^a-zA-Z0-9-_ ]/g, "");
2024-05-28 02:33:41 +08:00
if (isWikilink) {
// A [[wikilink]]
2024-05-28 02:33:41 +08:00
if (pageMeta.displayName) {
const decoratedName = namePrefix + pageMeta.displayName;
2024-09-29 19:39:08 +08:00
let boost = new Date(pageMeta.lastModified).getTime();
if (pageMeta._isAspiring) {
boost = -Infinity;
}
2023-12-22 01:37:50 +08:00
completions.push({
label: pageMeta.displayName,
displayLabel: decoratedName,
2024-09-29 19:39:08 +08:00
boost,
apply: pageMeta.tag === "template"
2023-12-22 01:37:50 +08:00
? pageMeta.name
2024-05-28 02:33:41 +08:00
: `${pageMeta.name}|${pageMeta.displayName}`,
detail: `displayName for: ${pageMeta.name}`,
2023-12-22 01:37:50 +08:00
type: "page",
cssClass,
2023-12-22 01:37:50 +08:00
});
}
2024-05-28 02:33:41 +08:00
if (Array.isArray(pageMeta.aliases)) {
for (const alias of pageMeta.aliases) {
const decoratedName = namePrefix + alias;
2024-05-28 02:33:41 +08:00
completions.push({
label: alias,
displayLabel: decoratedName,
2024-05-28 02:33:41 +08:00
boost: new Date(pageMeta.lastModified).getTime(),
apply: pageMeta.tag === "template"
? pageMeta.name
: `${pageMeta.name}|${alias}`,
detail: `alias to: ${pageMeta.name}`,
type: "page",
cssClass,
2024-05-28 02:33:41 +08:00
});
}
}
const decoratedName = namePrefix + pageMeta.name;
2024-05-28 02:33:41 +08:00
completions.push({
label: pageMeta.name,
displayLabel: decoratedName,
2024-05-28 02:33:41 +08:00
boost: new Date(pageMeta.lastModified).getTime(),
2024-07-25 21:18:58 +08:00
detail: pageMeta.tags?.includes("non-existing")
? "Linked but not created"
: undefined,
2024-05-28 02:33:41 +08:00
type: "page",
cssClass,
2024-05-28 02:33:41 +08:00
});
} else {
// A markdown link []()
2024-05-28 02:33:41 +08:00
let labelText = pageMeta.name;
let boost = new Date(pageMeta.lastModified).getTime();
// Relative path if in the same folder or a subfolder
if (folder.length > 0 && labelText.startsWith(folder)) {
labelText = labelText.slice(folder.length + 1);
boost = boost * 1.1;
} else {
// Absolute path otherwise
labelText = "/" + labelText;
}
completions.push({
label: labelText,
displayLabel: namePrefix + labelText,
2024-05-28 02:33:41 +08:00
boost: boost,
apply: labelText.includes(" ") ? "<" + labelText + ">" : labelText,
type: "page",
cssClass,
2024-05-28 02:33:41 +08:00
});
2023-12-22 01:37:50 +08:00
}
return completions;
}).flat(),
};
}
2023-11-06 16:14:16 +08:00
function fileMetaToPageMeta(fileMeta: FileMeta): PageMeta {
const name = fileMeta.name.substring(0, fileMeta.name.length - 3);
return {
...fileMeta,
ref: fileMeta.name,
tag: "page",
2023-11-06 16:14:16 +08:00
name,
created: localDateString(new Date(fileMeta.created)),
lastModified: localDateString(new Date(fileMeta.lastModified)),
2023-11-06 16:14:16 +08:00
} as PageMeta;
}