2022-06-28 12:14:15 +00:00
|
|
|
import { EditorSelection, StateCommand, Transaction } from "@codemirror/state";
|
|
|
|
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 09:47:13 +00:00
|
|
|
from: range.from - marker.length,
|
|
|
|
to: range.from,
|
|
|
|
insert: Text.of([""]),
|
|
|
|
}
|
2022-06-28 12:14:15 +00:00
|
|
|
: {
|
2022-10-12 09:47:13 +00:00
|
|
|
from: range.from,
|
|
|
|
insert: Text.of([marker]),
|
|
|
|
},
|
2022-06-28 12:14:15 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
changes.push(
|
|
|
|
isBoldAfter
|
|
|
|
? {
|
2022-10-12 09:47:13 +00:00
|
|
|
from: range.to,
|
|
|
|
to: range.to + marker.length,
|
|
|
|
insert: Text.of([""]),
|
|
|
|
}
|
2022-06-28 12:14:15 +00:00
|
|
|
: {
|
2022-10-12 09:47:13 +00:00
|
|
|
from: range.to,
|
|
|
|
insert: Text.of([marker]),
|
|
|
|
},
|
2022-06-28 12:14:15 +00: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 09:47:13 +00:00
|
|
|
range.to + extendAfter,
|
2022-06-28 12:14:15 +00:00
|
|
|
),
|
|
|
|
};
|
|
|
|
});
|
|
|
|
|
|
|
|
dispatch(
|
|
|
|
state.update(changes, {
|
|
|
|
scrollIntoView: true,
|
|
|
|
annotations: Transaction.userEvent.of("input"),
|
2022-10-12 09:47:13 +00:00
|
|
|
}),
|
2022-06-28 12:14:15 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
}
|