1
0
silverbullet/packages/plugs/core/navigate.ts

74 lines
2.2 KiB
TypeScript
Raw Normal View History

import type { ClickEvent } from "@silverbulletmd/web/app_event";
import {
2022-08-29 13:40:38 +00:00
flashNotification,
2022-08-30 08:44:20 +00:00
getCurrentPage,
getCursor,
getText,
navigate as navigateTo,
2022-04-25 08:33:38 +00:00
openUrl,
2022-04-25 09:24:13 +00:00
} from "@silverbulletmd/plugos-silverbullet-syscall/editor";
import { parseMarkdown } from "@silverbulletmd/plugos-silverbullet-syscall/markdown";
import { nodeAtPos, ParseTree } from "@silverbulletmd/common/tree";
import { invokeCommand } from "@silverbulletmd/plugos-silverbullet-syscall/system";
2022-03-29 15:02:28 +00:00
2022-04-11 18:34:09 +00:00
async function actionClickOrActionEnter(mdTree: ParseTree | null) {
if (!mdTree) {
return;
}
2022-05-13 12:36:26 +00:00
// console.log("Attempting to navigate based on syntax node", mdTree);
switch (mdTree.type) {
case "WikiLinkPage":
let pageLink = mdTree.children![0].text!;
2022-08-30 08:44:20 +00:00
let pos;
2022-03-28 13:25:05 +00:00
if (pageLink.includes("@")) {
[pageLink, pos] = pageLink.split("@");
2022-08-30 08:44:20 +00:00
if (pos.match(/^\d+$/)) {
pos = +pos;
}
2022-03-28 13:25:05 +00:00
}
2022-08-30 08:44:20 +00:00
if (!pageLink) {
pageLink = await getCurrentPage();
}
await navigateTo(pageLink, pos);
break;
case "URL":
case "NakedURL":
await openUrl(mdTree.children![0].text!);
break;
case "Link":
2022-08-29 13:40:38 +00:00
const url = mdTree.children![4].children![0].text!;
if (url.length <= 1) {
return flashNotification("Empty link, ignoring", "error");
}
await openUrl(url);
2022-03-07 09:21:02 +00:00
break;
case "CommandLink":
let command = mdTree
.children![0].text!.substring(2, mdTree.children![0].text!.length - 2)
.trim();
console.log("Got command link", command);
await invokeCommand(command);
break;
2022-02-26 16:50:50 +00:00
}
}
export async function linkNavigate() {
2022-04-04 09:51:41 +00:00
let mdTree = await parseMarkdown(await getText());
2022-04-04 13:25:07 +00:00
let newNode = nodeAtPos(mdTree, await getCursor());
await actionClickOrActionEnter(newNode);
}
2022-02-26 16:50:50 +00:00
export async function clickNavigate(event: ClickEvent) {
2022-04-11 18:34:09 +00:00
// Navigate by default, don't navigate when Ctrl or Cmd is held
2022-02-26 16:50:50 +00:00
if (event.ctrlKey || event.metaKey) {
2022-04-11 18:34:09 +00:00
return;
2022-02-26 16:50:50 +00:00
}
2022-04-11 18:34:09 +00:00
let mdTree = await parseMarkdown(await getText());
let newNode = nodeAtPos(mdTree, event.pos);
await actionClickOrActionEnter(newNode);
2022-02-26 16:50:50 +00:00
}
export async function navigateCommand(cmdDef: any) {
await navigateTo(cmdDef.page);
}