react-codemirror2 icon indicating copy to clipboard operation
react-codemirror2 copied to clipboard

selection prop ignored after component did mount

Open li4man0v opened this issue 6 years ago • 5 comments

The selection prop seems to be working only on componentDidMount. This makes controlled selection not working (onSelection => state => selection).

li4man0v avatar Jun 17 '18 08:06 li4man0v

@reanimatter this should intentional, selection is not continuously controlled by state as codemirror does a nice job handling that on it's own. You can set an initial and subsequently retrieve the values from the onSelection callback.

Perhaps this can become controlled? Can you please explain your use case so I can understand what you're trying to solve here? Happy to look into this more

scniro avatar Jul 01 '18 17:07 scniro

In my scenario, selection can be triggered outside the editor. When it happens, I want the code to be selected and scrolled into the view. I can achieve this behavior by creating a wrapper component around Controlled and adding setSelection to componentDidUpdate

componentDidUpdate() {
  // assuming we don't need multi-range selections
  const { selection: { anchor, head } } = this.props;
  this.editor.setSelection(anchor, head);
}

A more sophisticated use case is to be able to amend selection. This can be done by overriding onSelection in the wrapper

onSelection = (editor, data) => {
  const { selection, onSelection } = this.props;
  const { ranges: [ range ] } = data;
  // if you use lodash, you should strip cm ranges to have only required props
  if (!isEqual(selection, range)) {
    onSelection(range);
  }
};

I'm not sure how useful is to have all this as part of the core component. Probably, proper documentation can handle it. Also, renaming selection prop to initialSelection may be a viable option.

li4man0v avatar Jul 01 '18 21:07 li4man0v

From reading the docs, I also expected selection to be controllable on a controlled component. I think it should either be controlled, or the prop should be renamed to something like initialSelection.

mhuebert avatar Mar 10 '19 10:03 mhuebert

Ditto, I shared mhuebert and reanimatter's expectations about the selection property remaining live after the component was mounted. In my case, I want to mirror two editors, where a change in the text or selections of one gets mirrored by another, with selections kept in a shared store. Would be rad if this was an option for this already hella useful component :-)

andrewhead avatar Aug 16 '19 04:08 andrewhead

@reanimatter @mhuebert @andrewhead I am a lot shorter on time these days as when I started this project. Codemirror & React APIs are moving to quickly for me to keep atop of for the day-to-day. I am looking for a co-maintainer of this project. Please contact me directly if you are interested. Thank you for understanding.

scniro avatar Jan 19 '20 16:01 scniro