Hello everyone,
I am currently working on a ProseMirror-based document editor and have implemented a feature to track selection changes using a custom plugin. In my current implementation, I’ve used editorView.dom.addEventListener
to listen for mousedown
and mouseup
events. Here’s a snippet of my code:
const selectionPlugin = new Plugin({
view(editorView) {
let selectionChanged = false;
const { onSelectionRange } = reactPropsKey.getState(editorView.state);
editorView.dom.addEventListener("mousedown", () => {
onSelectionRange(null);
});
editorView.dom.addEventListener("mouseup", () => {
if (selectionChanged) {
handleSelectionChange(editorView, onSelectionRange);
selectionChanged = false;
}
});
return {
update(view, prevState) {
if (
!prevState ||
!prevState.doc.eq(view.state.doc) ||
!prevState.selection.eq(view.state.selection)
) {
selectionChanged = true;
}
},
};
},
});
function handleSelectionChange(view, onSelectionRange) {
let state = view.state;
if (state.selection.empty) {
onSelectionRange(null);
console.log("The selection is empty.");
} else {
const { ranges } = state.selection;
const from = Math.min(...ranges.map((range) => range.$from.pos));
const to = Math.max(...ranges.map((range) => range.$to.pos));
const start = view.domAtPos(from);
const end = view.domAtPos(to);
const range = document.createRange();
range.setStart(start.node, start.offset);
range.setEnd(end.node, end.offset);
onSelectionRange(range);
}
}
I am considering replacing this approach with ProseMirror’s built-in handleDOMEvents
within the plugin system. I believe this could lead to a more integrated and possibly efficient solution. However, I am unsure how to properly implement mousedown
and mouseup
handling using handleDOMEvents
.
Could anyone provide guidance or examples on how to effectively use handleDOMEvents
for this purpose? Specifically, I am looking to understand how to transition from using editorView.dom.addEventListener
to handleDOMEvents
for detecting selection changes in a ProseMirror plugin.
Thank you in advance for your insights and assistance!