EDIT Currently I have the following:
const contextMenuPlugin = new Plugin<IContextMenuState>({
key: CONTEXT_MENU_PLUGIN_KEY,
state: {
init(config, instance) {
return {
active: false,
pos: 0,
};
},
apply(tr, value, oldState, newState) {
const newPluginState =
tr.getMeta(CONTEXT_MENU_PLUGIN_KEY) || tr.getMeta('contextMenu');
if (newPluginState) return newPluginState;
return value;
},
},
props: {
decorations(state) {
const pluginState = CONTEXT_MENU_PLUGIN_KEY.getState(state);
if (!pluginState?.active) return null;
const pos = pluginState.pos;
const node = state.doc.nodeAt(pos);
const Deco =
node?.type.name === 'text' ? Decoration.inline : Decoration.node;
const highlightClasses = [
'outline-primary',
'outline-[2px]',
'outline-offset-2',
'outline',
'bg-primary/30',
'rounded-md',
'cursor-pointer',
];
const decoration = Deco(pos, pos + node?.nodeSize!, {
class: highlightClasses.join(' '),
});
return DecorationSet.create(state.doc, [decoration]);
},
handleDOMEvents: {
mouseover: (view, event) => {
var state = CONTEXT_MENU_PLUGIN_KEY.getState(view.state);
if (!state?.active) return;
let target = event.target as HTMLElement;
let selectableTarget: HTMLElement | null = target.hasAttribute(
'data-copyable'
)
? target
: null;
while (!selectableTarget && target.parentElement) {
target = target.parentElement;
selectableTarget = target.hasAttribute('data-copyable')
? target
: null;
}
if (!selectableTarget) return;
const parent = selectableTarget.parentElement;
let children = Array.from(parent?.childNodes || []);
let offset = children.indexOf(selectableTarget);
const pos = view.posAtDOM(parent!, offset);
const newState = {
...state,
pos,
};
view.dispatch(
view.state.tr.setMeta(CONTEXT_MENU_PLUGIN_KEY, newState)
);
},
mousedown: (view, event) => {
var state = CONTEXT_MENU_PLUGIN_KEY.getState(view.state);
if (!state?.active) return false;
const newState = { ...state, active: false };
// const tr = view.state.tr;
// tr.setSelection(NodeSelection.create(tr.doc, newState.pos))
editor
.chain()
// .focus()
.setNodeSelection(newState.pos)
.setMeta('contextMenu', newState)
.run();
},
},
},
});
Decorations are properly added on hover but there is a problem with mousedown
event. In DevTools everthing works fine, i.e. node is selected and ProseMIrror.selectedNode
class is added. However when I close devtools, for some reason the ProseMIrror.selectedNode
class disappear immidiately, i.e. code works fine because it selects a node but then it unselect it immidiately. Any suggestions what might be the reason?
EDIT For some reason switching from mousedown
to click
event solves the problem, why?