react-draft-wysiwyg
Version:
A wysiwyg on top of DraftJS.
113 lines (98 loc) • 2.98 kB
JavaScript
/* @flow */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
toggleCustomInlineStyle,
getSelectionCustomInlineStyle,
} from 'draftjs-utils';
import LayoutComponent from './Component';
class ColorPicker extends Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
editorState: PropTypes.object.isRequired,
modalHandler: PropTypes.object,
config: PropTypes.object,
translations: PropTypes.object,
};
state: Object = {
expanded: false,
currentColor: undefined,
currentBgColor: undefined,
};
componentWillMount(): void {
const { editorState, modalHandler } = this.props;
if (editorState) {
this.setState({
currentColor: getSelectionCustomInlineStyle(editorState, ['COLOR']).COLOR,
currentBgColor: getSelectionCustomInlineStyle(editorState, ['BGCOLOR']).BGCOLOR,
});
}
modalHandler.registerCallBack(this.expandCollapse);
}
componentWillReceiveProps(properties: Object): void {
const newState = {};
if (properties.editorState &&
this.props.editorState !== properties.editorState) {
newState.currentColor
= getSelectionCustomInlineStyle(properties.editorState, ['COLOR']).COLOR;
newState.currentBgColor
= getSelectionCustomInlineStyle(properties.editorState, ['BGCOLOR']).BGCOLOR;
}
this.setState(newState);
}
componentWillUnmount(): void {
const { modalHandler } = this.props;
modalHandler.deregisterCallBack(this.expandCollapse);
}
onExpandEvent: Function = (): void => {
this.signalExpanded = !this.state.expanded;
};
expandCollapse: Function = (): void => {
this.setState({
expanded: this.signalExpanded,
});
this.signalExpanded = false;
}
doExpand: Function = (): void => {
this.setState({
expanded: true,
});
};
doCollapse: Function = (): void => {
this.setState({
expanded: false,
});
};
toggleColor: Function = (style: string, color: string): void => {
const { editorState, onChange } = this.props;
const newState = toggleCustomInlineStyle(
editorState,
style,
color,
);
if (newState) {
onChange(newState);
}
this.doCollapse();
};
render(): Object {
const { config, translations } = this.props;
const { currentColor, currentBgColor, expanded } = this.state;
const ColorPickerComponent = config.component || LayoutComponent;
const color = currentColor && currentColor.substring(6);
const bgColor = currentBgColor && currentBgColor.substring(8);
return (
<ColorPickerComponent
config={config}
translations={translations}
onChange={this.toggleColor}
expanded={expanded}
onExpandEvent={this.onExpandEvent}
doExpand={this.doExpand}
doCollapse={this.doCollapse}
currentState={{ color, bgColor }}
/>
);
}
}
export default ColorPicker;