@bigfishtv/cockpit
Version:
83 lines (73 loc) • 2.25 kB
JavaScript
import PropTypes from 'prop-types'
import React, { Component } from 'react'
// eslint-disable-next-line no-unused-vars
import redactor from '../../lib/redactor/redactor'
import $ from 'jquery'
import { simplifyNonBreakingSpaces } from '../utils/stringUtils'
import { createSettings } from '../utils/redactorUtils'
const defaultCreateSettings = () => createSettings()
// @refactor this component to lazy load redactor and jquery
/**
* Rich text editor component
*/
export default class Redactor extends Component {
static propTypes = {
createSettings: PropTypes.func,
readOnly: PropTypes.bool,
}
static defaultProps = {
createSettings: defaultCreateSettings,
readOnly: false,
}
constructor({ value }) {
super()
this.state = { value }
}
componentDidMount() {
const me = this
const settings = this.props.createSettings()
settings.callbacks.change = function() {
// this version of redactor doesn't support disabling, so add hack, obviously!
if (me.props.readOnly) {
// do nothing
} else {
const value = simplifyNonBreakingSpaces(this.code.get())
me.setState({ value }, () => {
me.props.onChange(value)
})
}
}
$(this.root).redactor(settings)
// this version of redactor doesn't support disabling, so add hack, obviously!
const redactor = $.data(this.root, 'redactor')
redactor.core.editor().attr({ contenteditable: !this.props.readOnly })
}
componentDidUpdate(prevProps, prevState) {
if (this.props.value != prevState.value) {
$(this.root).redactor('code.set', this.props.value)
$(this.root).redactor('code.sync')
}
// this version of redactor doesn't support disabling, so add hack, obviously!
const redactor = $.data(this.root, 'redactor')
redactor.core.editor().attr({ contenteditable: !this.props.readOnly })
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.placeholder != nextProps.placeholder) {
return true
}
if (this.props.readOnly != nextProps.readOnly) {
return true
}
return nextProps.value != this.state.value
}
render() {
return (
<textarea
ref={input => (this.root = input)}
placeholder={this.props.placeholder}
defaultValue={this.props.value}
readOnly={this.props.readOnly}
/>
)
}
}