1
0
silverbullet/web/cm_plugins/directive.ts
Zef Hemel 24c17a793f
Live Preview (#119)
Live preview mode is here
2022-11-18 16:04:37 +01:00

71 lines
1.6 KiB
TypeScript

import {
Decoration,
DecorationSet,
EditorView,
syntaxTree,
ViewPlugin,
ViewUpdate,
} from "../deps.ts";
import { isCursorInRange } from "./util.ts";
function getDirectives(view: EditorView) {
const widgets: any[] = [];
for (const { from, to } of view.visibleRanges) {
syntaxTree(view.state).iterate({
from,
to,
enter: ({ type, from, to }) => {
if (type.name !== "CommentBlock") {
return;
}
const text = view.state.sliceDoc(from, to);
if (/<!--\s*#/.exec(text)) {
// Open directive
widgets.push(
Decoration.line({
class: "sb-directive-start",
}).range(from),
);
} else if (/<!--\s*\//.exec(text)) {
widgets.push(
Decoration.line({
class: "sb-directive-end",
}).range(from),
);
} else {
return;
}
if (!isCursorInRange(view.state, [from, to])) {
widgets.push(
Decoration.line({
class: "sb-directive-outside",
}).range(from),
);
}
},
});
}
return Decoration.set(widgets, true);
}
export const directivePlugin = ViewPlugin.fromClass(
class {
decorations: DecorationSet = Decoration.none;
constructor(view: EditorView) {
this.decorations = getDirectives(view);
}
update(update: ViewUpdate) {
if (
update.docChanged ||
update.viewportChanged ||
update.selectionSet
) {
this.decorations = getDirectives(update.view);
}
}
},
{ decorations: (v) => v.decorations },
);