fix(widget-string): fix cursor jumping to end of line (#4607)

This commit is contained in:
Ian Sinnott 2020-11-27 02:11:10 +08:00 committed by GitHub
parent c1a7c476cd
commit 1413d04d7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -15,23 +15,44 @@ export default class StringControl extends React.Component {
value: '', value: '',
}; };
// The selection to maintain for the input element
_sel = 0;
// The input element ref
_el = null;
// NOTE: This prevents the cursor from jumping to the end of the text for
// nested inputs. In other words, this is not an issue on top-level text
// fields such as the `title` of a collection post. However, it becomes an
// issue on fields nested within other components, namely widgets nested
// within a `markdown` widget. For example, the alt text on a block image
// within markdown.
// SEE: https://github.com/netlify/netlify-cms/issues/4539
// SEE: https://github.com/netlify/netlify-cms/issues/3578
componentDidUpdate() {
if (this._el && this._el.selectionStart !== this._sel) {
this._el.setSelectionRange(this._sel, this._sel);
}
}
handleChange = e => {
this._sel = e.target.selectionStart;
this.props.onChange(e.target.value);
};
render() { render() {
const { const { forID, value, classNameWrapper, setActiveStyle, setInactiveStyle } = this.props;
forID,
value,
onChange,
classNameWrapper,
setActiveStyle,
setInactiveStyle,
} = this.props;
return ( return (
<input <input
ref={el => {
this._el = el;
}}
type="text" type="text"
id={forID} id={forID}
className={classNameWrapper} className={classNameWrapper}
value={value || ''} value={value || ''}
onChange={e => onChange(e.target.value)} onChange={this.handleChange}
onFocus={setActiveStyle} onFocus={setActiveStyle}
onBlur={setInactiveStyle} onBlur={setInactiveStyle}
/> />