1
0
silverbullet/web/cm_plugins/directive.ts

78 lines
2.2 KiB
TypeScript
Raw Normal View History

import { Decoration, EditorState, syntaxTree } from "../deps.ts";
2022-12-09 16:13:26 +00:00
import {
decoratorStateField,
invisibleDecoration,
isCursorInRange,
} from "./util.ts";
2022-12-09 16:13:26 +00:00
// Does a few things: hides the directives when the cursor is not placed inside
// Adds a class to the start and end of the directive when the cursor is placed inside
export function directivePlugin() {
return decoratorStateField((state: EditorState) => {
const widgets: any[] = [];
2022-12-09 16:13:26 +00:00
syntaxTree(state).iterate({
enter: ({ type, from, to, node }) => {
const parent = node.parent;
if (!parent) {
2022-12-09 16:13:26 +00:00
return;
}
const cursorInRange = isCursorInRange(state, [parent.from, parent.to]);
if (type.name === "DirectiveStart") {
if (cursorInRange) {
// Cursor outside this directive
2022-12-09 16:13:26 +00:00
widgets.push(
Decoration.line({ class: "sb-directive-start" }).range(from),
2022-12-09 16:13:26 +00:00
);
} else {
widgets.push(invisibleDecoration.range(from, to));
2022-12-09 16:13:26 +00:00
widgets.push(
Decoration.line({ class: "sb-directive-start-outside" }).range(
state.doc.lineAt(to).from,
),
2022-12-09 16:13:26 +00:00
);
}
return true;
}
if (type.name === "DirectiveEnd") {
// Cursor outside this directive
if (cursorInRange) {
2022-12-09 16:13:26 +00:00
widgets.push(
Decoration.line({ class: "sb-directive-end" }).range(from),
2022-12-09 16:13:26 +00:00
);
} else {
widgets.push(invisibleDecoration.range(from, to));
2022-12-09 16:13:26 +00:00
widgets.push(
Decoration.line({ class: "sb-directive-end-outside" }).range(
state.doc.lineAt(from - 1).from,
),
2022-12-09 16:13:26 +00:00
);
}
return true;
}
if (type.name === "DirectiveBody") {
const lines = state.sliceDoc(from, to).split("\n");
let pos = from;
for (const line of lines) {
if (pos !== to) {
widgets.push(
Decoration.line({
class: "sb-directive-body",
}).range(pos),
);
}
pos += line.length + 1;
}
2022-12-09 16:13:26 +00:00
}
},
});
2022-12-09 16:13:26 +00:00
return Decoration.set(widgets, true);
});
}