UNPKG

2.41 kBJavaScriptView Raw
1// @flow
2import * as React from 'react';
3import type {IconProps} from 'shared/src/types';
4import ToolbarIcon, {markAttrs} from '@canner/slate-icon-shared';
5import addMarkOverwrite from '@canner/slate-helper-mark-addoverwrite';
6import {haveMarks} from '@canner/slate-util-have';
7import {getMarkType} from '@canner/slate-util-get';
8import ColorPicker from 'rc-color-picker';
9import hexRgb from 'hex-rgb';
10import {FONTBGCOLOR} from '@canner/slate-constant/lib/marks';
11import omit from 'lodash.omit';
12import commonMark from '@canner/slate-editor-renderer/lib/commonMark';
13
14import 'rc-color-picker/assets/index.css';
15
16export const FontBgColorPlugin = (opt) => {
17 const options = Object.assign({
18 type: FONTBGCOLOR,
19 tagName: 'span',
20 backgroundColor: markAttrs.backgroundColor
21 }, opt);
22
23 return {
24 renderMark: (props) => {
25 if (props.mark.type === options.type)
26 return commonMark(options.tagName, omit(options, ['type', 'tagName']))(props);
27 }
28 }
29}
30
31export default class fontBgColor extends React.Component<IconProps, {color: Object}> {
32 typeName: string
33 constructor(props: IconProps) {
34 super(props);
35 this.typeName = this.props.type || FONTBGCOLOR;
36 this.state = {
37 color: {}
38 };
39 }
40
41 static defaultProps = {
42 colorKey: 'color'
43 }
44
45 onChange = (color: {color: string, alpha: number, open: boolean}) => {
46 let {change, onChange, colorKey} = this.props;
47
48 // $FlowFixMe
49 color.rgba = `rgba(${hexRgb(color.color, {format: 'array'}).join(',')}, ${color.alpha / 100})`;
50 this.setState({color});
51 onChange(
52 addMarkOverwrite(change, {type: this.typeName, data: {[colorKey]: color}})
53 .collapseToStartOfNextText()
54 .focus()
55 );
56 }
57
58 render() {
59 const {icon, change, ...rest} = this.props;
60 const isActive = haveMarks(change, this.typeName);
61 let colorStyle = {};
62
63 if (isActive) {
64 const first = getMarkType(change, this.typeName).first().get('data');
65 const color = first.get('color');
66 const alpha = first.get('alpha');
67
68 colorStyle = {
69 fill: color,
70 opacity: alpha
71 };
72 }
73
74 return (
75 <ColorPicker
76 onChange={this.onChange}>
77 <ToolbarIcon
78 colorStyle={colorStyle}
79 type={this.typeName}
80 icon={icon || 'Background'}
81 isActive={isActive}
82 {...rest}
83 />
84 </ColorPicker>
85 );
86 }
87}