Search code examples
reactjsfluxcaret

Updating caret position within Flux store


I have a component that wraps around a form input. For the purpose of a collaborative editing, I need to watch over changes not just to the text, but also position of a caret. Partially the position of caret will be determined by selectionchange event and it can be changed with some keyboard shortcuts too.

Now I am thinking how to fit this into Flux architecture. I mean, when this position changes, I should dispatch an action that updates store accordingly, right? Then the re-render happens and the component wrapping input reads information about caret position and updates it in the DOM.

In theory this should work out nicely, but imagine that I would be updating caret position every time the user types a letter. For a fast-typers it could cause issues as the caret would be jumping back where it shouldn't.

I could implement some deboucing and dispatch action only after certain time user stop typing, but that's hardly a robust solution.

So I am wondering how this could be done in a mature way. Only thing that comes into my mind is flagging dispatched action if it was caused by typing or keyboard shortcuts and simply ignore former ones. Is that a "correct" approach or would you recommend something else?


Solution

  • In theory this should work out nicely, but imagine that I would be updating caret position every time the user types a letter. For a fast-typers it could cause issues as the caret would be jumping back where it shouldn't.

    There wouldn't be such an issue. Dispatching an action is no different than updating React component state on every key press that works just fine. Because dispatches are synchronous, the state will always be up to date, and the caret won't jump.