1
0
silverbullet/plug-api/lib/resolve.ts

69 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-07-30 09:30:01 +00:00
import { findNodeOfType, ParseTree, traverseTree } from "$sb/lib/tree.ts";
2023-07-29 21:41:37 +00:00
export function resolvePath(
currentPage: string,
pathToResolve: string,
fullUrl = false,
): string {
2023-07-30 06:56:44 +00:00
if (isFederationPath(currentPage) && !isFederationPath(pathToResolve)) {
2023-07-29 21:41:37 +00:00
let domainPart = currentPage.split("/")[0];
if (fullUrl) {
2023-07-30 09:30:01 +00:00
domainPart = federatedPathToUrl(domainPart);
2023-07-29 21:41:37 +00:00
}
return `${domainPart}/${pathToResolve}`;
} else {
return pathToResolve;
}
}
2023-07-30 06:56:44 +00:00
2023-07-30 09:30:01 +00:00
export function federatedPathToUrl(path: string): string {
path = path.substring(1);
if (path.startsWith("localhost")) {
path = "http://" + path;
} else {
path = "https://" + path;
}
return path;
}
2023-07-30 06:56:44 +00:00
export function isFederationPath(path: string) {
return path.startsWith("!");
}
2023-07-30 09:30:01 +00:00
export function rewritePageRefs(tree: ParseTree, containerPageName: string) {
2023-07-30 09:30:01 +00:00
traverseTree(tree, (n): boolean => {
if (n.type === "DirectiveStart") {
const pageRef = findNodeOfType(n, "PageRef")!;
if (pageRef) {
const pageRefName = pageRef.children![0].text!.slice(2, -2);
pageRef.children![0].text = `[[${
resolvePath(containerPageName, pageRefName)
2023-07-30 09:30:01 +00:00
}]]`;
}
const directiveText = n.children![0].text;
// #use or #import
if (directiveText) {
const match = /\[\[(.+)\]\]/.exec(directiveText);
if (match) {
const pageRefName = match[1];
n.children![0].text = directiveText.replace(
match[0],
`[[${resolvePath(containerPageName, pageRefName)}]]`,
2023-07-30 09:30:01 +00:00
);
}
}
return true;
}
if (n.type === "WikiLinkPage") {
n.children![0].text = resolvePath(
containerPageName,
n.children![0].text!,
);
2023-07-30 09:30:01 +00:00
return true;
}
return false;
});
}