scniro / react-codemirror2

Codemirror integrated components for React
MIT License
1.66k stars 193 forks source link

selection prop ignored after component did mount #95

Open li4man0v opened 6 years ago

li4man0v commented 6 years ago

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

scniro commented 6 years ago

@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

li4man0v commented 6 years ago

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.

mhuebert commented 5 years ago

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.

andrewhead commented 5 years ago

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 :-)

scniro commented 4 years ago

@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.