silverbullet/web/commands.ts

65 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

2024-08-02 23:14:40 +08:00
import {
EditorSelection,
type StateCommand,
Transaction,
} from "@codemirror/state";
2022-06-28 20:14:15 +08:00
import { Text } from "@codemirror/state";
export function insertMarker(marker: string): StateCommand {
return ({ state, dispatch }) => {
const changes = state.changeByRange((range) => {
const isBoldBefore =
state.sliceDoc(range.from - marker.length, range.from) === marker;
const isBoldAfter =
state.sliceDoc(range.to, range.to + marker.length) === marker;
const changes = [];
changes.push(
isBoldBefore
? {
2022-10-12 17:47:13 +08:00
from: range.from - marker.length,
to: range.from,
insert: Text.of([""]),
}
2022-06-28 20:14:15 +08:00
: {
2022-10-12 17:47:13 +08:00
from: range.from,
insert: Text.of([marker]),
},
2022-06-28 20:14:15 +08:00
);
changes.push(
isBoldAfter
? {
2022-10-12 17:47:13 +08:00
from: range.to,
to: range.to + marker.length,
insert: Text.of([""]),
}
2022-06-28 20:14:15 +08:00
: {
2022-10-12 17:47:13 +08:00
from: range.to,
insert: Text.of([marker]),
},
2022-06-28 20:14:15 +08:00
);
const extendBefore = isBoldBefore ? -marker.length : marker.length;
const extendAfter = isBoldAfter ? -marker.length : marker.length;
return {
changes,
range: EditorSelection.range(
range.from + extendBefore,
2022-10-12 17:47:13 +08:00
range.to + extendAfter,
2022-06-28 20:14:15 +08:00
),
};
});
dispatch(
state.update(changes, {
scrollIntoView: true,
annotations: Transaction.userEvent.of("input"),
2022-10-12 17:47:13 +08:00
}),
2022-06-28 20:14:15 +08:00
);
return true;
};
}