2022-12-14 19:04:20 +00:00
|
|
|
import { commandLinkRegex } from "../../common/markdown_parser/parser.ts";
|
2022-12-09 15:09:53 +00:00
|
|
|
import { ClickEvent } from "$sb/app_event.ts";
|
|
|
|
import { Decoration, syntaxTree } from "../deps.ts";
|
2023-07-14 12:22:26 +00:00
|
|
|
import { Editor } from "../editor.ts";
|
2022-11-29 08:11:23 +00:00
|
|
|
import {
|
|
|
|
ButtonWidget,
|
2022-12-09 15:09:53 +00:00
|
|
|
decoratorStateField,
|
2022-11-29 08:11:23 +00:00
|
|
|
invisibleDecoration,
|
|
|
|
isCursorInRange,
|
|
|
|
} from "./util.ts";
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Plugin to hide path prefix when the cursor is not inside.
|
|
|
|
*/
|
|
|
|
export function cleanCommandLinkPlugin(editor: Editor) {
|
2022-12-09 15:09:53 +00:00
|
|
|
return decoratorStateField((state) => {
|
|
|
|
const widgets: any[] = [];
|
|
|
|
// let parentRange: [number, number];
|
|
|
|
syntaxTree(state).iterate({
|
|
|
|
enter: ({ type, from, to }) => {
|
|
|
|
if (type.name !== "CommandLink") {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (isCursorInRange(state, [from, to])) {
|
|
|
|
return;
|
2022-11-29 08:11:23 +00:00
|
|
|
}
|
|
|
|
|
2022-12-09 15:09:53 +00:00
|
|
|
const text = state.sliceDoc(from, to);
|
|
|
|
const match = commandLinkRegex.exec(text);
|
|
|
|
if (!match) return;
|
|
|
|
const [_fullMatch, command, _pipePart, alias] = match;
|
2022-11-29 08:11:23 +00:00
|
|
|
|
2022-12-09 15:09:53 +00:00
|
|
|
// Hide the whole thing
|
|
|
|
widgets.push(
|
|
|
|
invisibleDecoration.range(
|
|
|
|
from,
|
|
|
|
to,
|
|
|
|
),
|
|
|
|
);
|
2022-11-29 08:11:23 +00:00
|
|
|
|
2022-12-09 15:09:53 +00:00
|
|
|
const linkText = alias || command;
|
|
|
|
// And replace it with a widget
|
|
|
|
widgets.push(
|
|
|
|
Decoration.widget({
|
|
|
|
widget: new ButtonWidget(
|
|
|
|
linkText,
|
|
|
|
`Run command: ${command}`,
|
|
|
|
"sb-command-button",
|
|
|
|
(e) => {
|
|
|
|
if (e.altKey) {
|
|
|
|
// Move cursor into the link
|
|
|
|
return editor.editorView!.dispatch({
|
|
|
|
selection: { anchor: from + 2 },
|
|
|
|
});
|
|
|
|
}
|
|
|
|
// Dispatch click event to navigate there without moving the cursor
|
|
|
|
const clickEvent: ClickEvent = {
|
|
|
|
page: editor.currentPage!,
|
|
|
|
ctrlKey: e.ctrlKey,
|
|
|
|
metaKey: e.metaKey,
|
|
|
|
altKey: e.altKey,
|
|
|
|
pos: from,
|
|
|
|
};
|
|
|
|
editor.dispatchAppEvent("page:click", clickEvent).catch(
|
|
|
|
console.error,
|
|
|
|
);
|
|
|
|
},
|
|
|
|
),
|
|
|
|
}).range(from),
|
|
|
|
);
|
|
|
|
},
|
|
|
|
});
|
|
|
|
return Decoration.set(widgets, true);
|
|
|
|
});
|
2022-11-29 08:11:23 +00:00
|
|
|
}
|