Replies: 2 comments 1 reply
-
Will plugin-listener be helpful? It can help you to watch the state change in milkdown. |
Beta Was this translation helpful? Give feedback.
1 reply
-
I've blatantly ripped off plugin-listener to make this selectionListener plugin import {createSlice} from '@milkdown/ctx';
// eslint-disable-next-line import/no-unresolved
import {Plugin, PluginKey} from '@milkdown/prose/state';
import {InitReady, prosePluginsCtx} from '@milkdown/core';
import {debounce} from 'lodash';
export class SelectionManager {
selectionListeners = [];
get listeners() {
return {
selection: this.selectionListeners,
}
}
selection(fn) {
this.selectionListeners.push(fn);
return this;
}
}
export const selectionCtx = createSlice(new SelectionManager(), 'selection-listener');
export const key = new PluginKey('MILKDOWN_SELECTION_LISTENER');
export const selectionListener = (ctx) => {
ctx.inject(selectionCtx, new SelectionManager());
return async () => {
await ctx.wait(InitReady);
const listener = ctx.get(selectionCtx);
const {listeners} = listener;
let prevSelection = null;
const plugin = new Plugin({
key,
state: {
init: () => {
// do nothing
},
apply: (tr) => {
if (tr.selection.eq(prevSelection)) return;
const handler = debounce(() => {
const {selection, doc} = tr;
if (listeners.selection.length > 0 && (prevSelection == null || !prevSelection.eq(selection))) {
listeners.selection.forEach((fn) => {
fn(ctx, selection, doc);
});
}
prevSelection = tr.selection;
}, 200);
return handler();
},
},
});
ctx.update(prosePluginsCtx, (x) => x.concat(plugin));
};
}; The selection listener could easily just be added to the existing listener plugin—let me know if a pull request to do so would be welcome |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have some serious hacks to trigger a function whenever the editor ref changes in a React context.
Is there a non-hacky way to trigger such an action?
Specifically I'm hoping to be able to call a callback function whenever the selection changes within React--is this possible?
Beta Was this translation helpful? Give feedback.
All reactions